blob: 0878008d719e593c2b7e31f1465165070c538763 [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 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001307 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001308
1309 // If the client is only demanding bits that we know, return the known
1310 // constant.
1311 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1312 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1313 return false;
1314}
1315
Chris Lattner867b99f2006-10-05 06:55:50 +00001316
1317/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1318/// 64 or fewer elements. DemandedElts contains the set of elements that are
1319/// actually used by the caller. This method analyzes which elements of the
1320/// operand are undef and returns that information in UndefElts.
1321///
1322/// If the information about demanded elements can be used to simplify the
1323/// operation, the operation is simplified, then the resultant value is
1324/// returned. This returns null if no change was made.
1325Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1326 uint64_t &UndefElts,
1327 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001328 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001329 assert(VWidth <= 64 && "Vector too wide to analyze!");
1330 uint64_t EltMask = ~0ULL >> (64-VWidth);
1331 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1332 "Invalid DemandedElts!");
1333
1334 if (isa<UndefValue>(V)) {
1335 // If the entire vector is undefined, just return this info.
1336 UndefElts = EltMask;
1337 return 0;
1338 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1339 UndefElts = EltMask;
1340 return UndefValue::get(V->getType());
1341 }
1342
1343 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001344 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1345 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001346 Constant *Undef = UndefValue::get(EltTy);
1347
1348 std::vector<Constant*> Elts;
1349 for (unsigned i = 0; i != VWidth; ++i)
1350 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1351 Elts.push_back(Undef);
1352 UndefElts |= (1ULL << i);
1353 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1354 Elts.push_back(Undef);
1355 UndefElts |= (1ULL << i);
1356 } else { // Otherwise, defined.
1357 Elts.push_back(CP->getOperand(i));
1358 }
1359
1360 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001361 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001362 return NewCP != CP ? NewCP : 0;
1363 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001364 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001365 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001366 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001367 Constant *Zero = Constant::getNullValue(EltTy);
1368 Constant *Undef = UndefValue::get(EltTy);
1369 std::vector<Constant*> Elts;
1370 for (unsigned i = 0; i != VWidth; ++i)
1371 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1372 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001373 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001374 }
1375
1376 if (!V->hasOneUse()) { // Other users may use these bits.
1377 if (Depth != 0) { // Not at the root.
1378 // TODO: Just compute the UndefElts information recursively.
1379 return false;
1380 }
1381 return false;
1382 } else if (Depth == 10) { // Limit search depth.
1383 return false;
1384 }
1385
1386 Instruction *I = dyn_cast<Instruction>(V);
1387 if (!I) return false; // Only analyze instructions.
1388
1389 bool MadeChange = false;
1390 uint64_t UndefElts2;
1391 Value *TmpV;
1392 switch (I->getOpcode()) {
1393 default: break;
1394
1395 case Instruction::InsertElement: {
1396 // If this is a variable index, we don't know which element it overwrites.
1397 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001398 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001399 if (Idx == 0) {
1400 // Note that we can't propagate undef elt info, because we don't know
1401 // which elt is getting updated.
1402 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1403 UndefElts2, Depth+1);
1404 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1405 break;
1406 }
1407
1408 // If this is inserting an element that isn't demanded, remove this
1409 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001410 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001411 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1412 return AddSoonDeadInstToWorklist(*I, 0);
1413
1414 // Otherwise, the element inserted overwrites whatever was there, so the
1415 // input demanded set is simpler than the output set.
1416 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1417 DemandedElts & ~(1ULL << IdxNo),
1418 UndefElts, Depth+1);
1419 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1420
1421 // The inserted element is defined.
1422 UndefElts |= 1ULL << IdxNo;
1423 break;
1424 }
Chris Lattner69878332007-04-14 22:29:23 +00001425 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001426 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001427 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1428 if (!VTy) break;
1429 unsigned InVWidth = VTy->getNumElements();
1430 uint64_t InputDemandedElts = 0;
1431 unsigned Ratio;
1432
1433 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001434 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001435 // elements as are demanded of us.
1436 Ratio = 1;
1437 InputDemandedElts = DemandedElts;
1438 } else if (VWidth > InVWidth) {
1439 // Untested so far.
1440 break;
1441
1442 // If there are more elements in the result than there are in the source,
1443 // then an input element is live if any of the corresponding output
1444 // elements are live.
1445 Ratio = VWidth/InVWidth;
1446 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1447 if (DemandedElts & (1ULL << OutIdx))
1448 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1449 }
1450 } else {
1451 // Untested so far.
1452 break;
1453
1454 // If there are more elements in the source than there are in the result,
1455 // then an input element is live if the corresponding output element is
1456 // live.
1457 Ratio = InVWidth/VWidth;
1458 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1459 if (DemandedElts & (1ULL << InIdx/Ratio))
1460 InputDemandedElts |= 1ULL << InIdx;
1461 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001462
Chris Lattner69878332007-04-14 22:29:23 +00001463 // div/rem demand all inputs, because they don't want divide by zero.
1464 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1465 UndefElts2, Depth+1);
1466 if (TmpV) {
1467 I->setOperand(0, TmpV);
1468 MadeChange = true;
1469 }
1470
1471 UndefElts = UndefElts2;
1472 if (VWidth > InVWidth) {
1473 assert(0 && "Unimp");
1474 // If there are more elements in the result than there are in the source,
1475 // then an output element is undef if the corresponding input element is
1476 // undef.
1477 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1478 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1479 UndefElts |= 1ULL << OutIdx;
1480 } else if (VWidth < InVWidth) {
1481 assert(0 && "Unimp");
1482 // If there are more elements in the source than there are in the result,
1483 // then a result element is undef if all of the corresponding input
1484 // elements are undef.
1485 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1486 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1487 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1488 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1489 }
1490 break;
1491 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 case Instruction::And:
1493 case Instruction::Or:
1494 case Instruction::Xor:
1495 case Instruction::Add:
1496 case Instruction::Sub:
1497 case Instruction::Mul:
1498 // div/rem demand all inputs, because they don't want divide by zero.
1499 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1500 UndefElts, Depth+1);
1501 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1502 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1503 UndefElts2, Depth+1);
1504 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1505
1506 // Output elements are undefined if both are undefined. Consider things
1507 // like undef&0. The result is known zero, not undef.
1508 UndefElts &= UndefElts2;
1509 break;
1510
1511 case Instruction::Call: {
1512 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1513 if (!II) break;
1514 switch (II->getIntrinsicID()) {
1515 default: break;
1516
1517 // Binary vector operations that work column-wise. A dest element is a
1518 // function of the corresponding input elements from the two inputs.
1519 case Intrinsic::x86_sse_sub_ss:
1520 case Intrinsic::x86_sse_mul_ss:
1521 case Intrinsic::x86_sse_min_ss:
1522 case Intrinsic::x86_sse_max_ss:
1523 case Intrinsic::x86_sse2_sub_sd:
1524 case Intrinsic::x86_sse2_mul_sd:
1525 case Intrinsic::x86_sse2_min_sd:
1526 case Intrinsic::x86_sse2_max_sd:
1527 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1528 UndefElts, Depth+1);
1529 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1530 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1531 UndefElts2, Depth+1);
1532 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1533
1534 // If only the low elt is demanded and this is a scalarizable intrinsic,
1535 // scalarize it now.
1536 if (DemandedElts == 1) {
1537 switch (II->getIntrinsicID()) {
1538 default: break;
1539 case Intrinsic::x86_sse_sub_ss:
1540 case Intrinsic::x86_sse_mul_ss:
1541 case Intrinsic::x86_sse2_sub_sd:
1542 case Intrinsic::x86_sse2_mul_sd:
1543 // TODO: Lower MIN/MAX/ABS/etc
1544 Value *LHS = II->getOperand(1);
1545 Value *RHS = II->getOperand(2);
1546 // Extract the element as scalars.
1547 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1548 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1549
1550 switch (II->getIntrinsicID()) {
1551 default: assert(0 && "Case stmts out of sync!");
1552 case Intrinsic::x86_sse_sub_ss:
1553 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001554 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001555 II->getName()), *II);
1556 break;
1557 case Intrinsic::x86_sse_mul_ss:
1558 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001559 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001560 II->getName()), *II);
1561 break;
1562 }
1563
1564 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001565 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1566 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001567 InsertNewInstBefore(New, *II);
1568 AddSoonDeadInstToWorklist(*II, 0);
1569 return New;
1570 }
1571 }
1572
1573 // Output elements are undefined if both are undefined. Consider things
1574 // like undef&0. The result is known zero, not undef.
1575 UndefElts &= UndefElts2;
1576 break;
1577 }
1578 break;
1579 }
1580 }
1581 return MadeChange ? I : 0;
1582}
1583
Dan Gohman45b4e482008-05-19 22:14:15 +00001584
Chris Lattner564a7272003-08-13 19:01:45 +00001585/// AssociativeOpt - Perform an optimization on an associative operator. This
1586/// function is designed to check a chain of associative operators for a
1587/// potential to apply a certain optimization. Since the optimization may be
1588/// applicable if the expression was reassociated, this checks the chain, then
1589/// reassociates the expression as necessary to expose the optimization
1590/// opportunity. This makes use of a special Functor, which must define
1591/// 'shouldApply' and 'apply' methods.
1592///
1593template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001594static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001595 unsigned Opcode = Root.getOpcode();
1596 Value *LHS = Root.getOperand(0);
1597
1598 // Quick check, see if the immediate LHS matches...
1599 if (F.shouldApply(LHS))
1600 return F.apply(Root);
1601
1602 // Otherwise, if the LHS is not of the same opcode as the root, return.
1603 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001604 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001605 // Should we apply this transform to the RHS?
1606 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1607
1608 // If not to the RHS, check to see if we should apply to the LHS...
1609 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1610 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1611 ShouldApply = true;
1612 }
1613
1614 // If the functor wants to apply the optimization to the RHS of LHSI,
1615 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1616 if (ShouldApply) {
1617 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001618
Chris Lattner564a7272003-08-13 19:01:45 +00001619 // Now all of the instructions are in the current basic block, go ahead
1620 // and perform the reassociation.
1621 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1622
1623 // First move the selected RHS to the LHS of the root...
1624 Root.setOperand(0, LHSI->getOperand(1));
1625
1626 // Make what used to be the LHS of the root be the user of the root...
1627 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001628 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001629 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1630 return 0;
1631 }
Chris Lattner65725312004-04-16 18:08:07 +00001632 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001633 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001634 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1635 BasicBlock::iterator ARI = &Root; ++ARI;
1636 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1637 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001638
1639 // Now propagate the ExtraOperand down the chain of instructions until we
1640 // get to LHSI.
1641 while (TmpLHSI != LHSI) {
1642 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001643 // Move the instruction to immediately before the chain we are
1644 // constructing to avoid breaking dominance properties.
1645 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1646 BB->getInstList().insert(ARI, NextLHSI);
1647 ARI = NextLHSI;
1648
Chris Lattner564a7272003-08-13 19:01:45 +00001649 Value *NextOp = NextLHSI->getOperand(1);
1650 NextLHSI->setOperand(1, ExtraOperand);
1651 TmpLHSI = NextLHSI;
1652 ExtraOperand = NextOp;
1653 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001654
Chris Lattner564a7272003-08-13 19:01:45 +00001655 // Now that the instructions are reassociated, have the functor perform
1656 // the transformation...
1657 return F.apply(Root);
1658 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001659
Chris Lattner564a7272003-08-13 19:01:45 +00001660 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1661 }
1662 return 0;
1663}
1664
Dan Gohman844731a2008-05-13 00:00:25 +00001665namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001666
Nick Lewycky02d639f2008-05-23 04:34:58 +00001667// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001668struct AddRHS {
1669 Value *RHS;
1670 AddRHS(Value *rhs) : RHS(rhs) {}
1671 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1672 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001673 return BinaryOperator::CreateShl(Add.getOperand(0),
1674 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001675 }
1676};
1677
1678// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1679// iff C1&C2 == 0
1680struct AddMaskingAnd {
1681 Constant *C2;
1682 AddMaskingAnd(Constant *c) : C2(c) {}
1683 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001684 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001685 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001686 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001687 }
1688 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001689 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001690 }
1691};
1692
Dan Gohman844731a2008-05-13 00:00:25 +00001693}
1694
Chris Lattner6e7ba452005-01-01 16:22:27 +00001695static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001696 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001697 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001698 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001699 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001700
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001701 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001702 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001703 }
1704
Chris Lattner2eefe512004-04-09 19:05:30 +00001705 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001706 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1707 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001708
Chris Lattner2eefe512004-04-09 19:05:30 +00001709 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1710 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001711 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1712 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001713 }
1714
1715 Value *Op0 = SO, *Op1 = ConstOperand;
1716 if (!ConstIsRHS)
1717 std::swap(Op0, Op1);
1718 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001720 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001721 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001722 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001723 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001724 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001725 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001726 abort();
1727 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001728 return IC->InsertNewInstBefore(New, I);
1729}
1730
1731// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1732// constant as the other operand, try to fold the binary operator into the
1733// select arguments. This also works for Cast instructions, which obviously do
1734// not have a second operand.
1735static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1736 InstCombiner *IC) {
1737 // Don't modify shared select instructions
1738 if (!SI->hasOneUse()) return 0;
1739 Value *TV = SI->getOperand(1);
1740 Value *FV = SI->getOperand(2);
1741
1742 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001743 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001744 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001745
Chris Lattner6e7ba452005-01-01 16:22:27 +00001746 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1747 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1748
Gabor Greif051a9502008-04-06 20:25:17 +00001749 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1750 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001751 }
1752 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001753}
1754
Chris Lattner4e998b22004-09-29 05:07:12 +00001755
1756/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1757/// node as operand #0, see if we can fold the instruction into the PHI (which
1758/// is only possible if all operands to the PHI are constants).
1759Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1760 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001761 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001762 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001763
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001764 // Check to see if all of the operands of the PHI are constants. If there is
1765 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001766 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001767 BasicBlock *NonConstBB = 0;
1768 for (unsigned i = 0; i != NumPHIValues; ++i)
1769 if (!isa<Constant>(PN->getIncomingValue(i))) {
1770 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001771 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001772 NonConstBB = PN->getIncomingBlock(i);
1773
1774 // If the incoming non-constant value is in I's block, we have an infinite
1775 // loop.
1776 if (NonConstBB == I.getParent())
1777 return 0;
1778 }
1779
1780 // If there is exactly one non-constant value, we can insert a copy of the
1781 // operation in that block. However, if this is a critical edge, we would be
1782 // inserting the computation one some other paths (e.g. inside a loop). Only
1783 // do this if the pred block is unconditionally branching into the phi block.
1784 if (NonConstBB) {
1785 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1786 if (!BI || !BI->isUnconditional()) return 0;
1787 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001788
1789 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001790 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001791 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001792 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001793 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001794
1795 // Next, add all of the operands to the PHI.
1796 if (I.getNumOperands() == 2) {
1797 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001798 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001799 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001800 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001801 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1802 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1803 else
1804 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001805 } else {
1806 assert(PN->getIncomingBlock(i) == NonConstBB);
1807 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001808 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001809 PN->getIncomingValue(i), C, "phitmp",
1810 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001811 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001812 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001813 CI->getPredicate(),
1814 PN->getIncomingValue(i), C, "phitmp",
1815 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001816 else
1817 assert(0 && "Unknown binop!");
1818
Chris Lattnerdbab3862007-03-02 21:28:56 +00001819 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001820 }
1821 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001822 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001823 } else {
1824 CastInst *CI = cast<CastInst>(&I);
1825 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001826 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001827 Value *InV;
1828 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001829 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001830 } else {
1831 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001832 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001833 I.getType(), "phitmp",
1834 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001835 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001836 }
1837 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001838 }
1839 }
1840 return ReplaceInstUsesWith(I, NewPN);
1841}
1842
Chris Lattner2454a2e2008-01-29 06:52:45 +00001843
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001844/// WillNotOverflowSignedAdd - Return true if we can prove that:
1845/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1846/// This basically requires proving that the add in the original type would not
1847/// overflow to change the sign bit or have a carry out.
1848bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1849 // There are different heuristics we can use for this. Here are some simple
1850 // ones.
1851
1852 // Add has the property that adding any two 2's complement numbers can only
1853 // have one carry bit which can change a sign. As such, if LHS and RHS each
1854 // have at least two sign bits, we know that the addition of the two values will
1855 // sign extend fine.
1856 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1857 return true;
1858
1859
1860 // If one of the operands only has one non-zero bit, and if the other operand
1861 // has a known-zero bit in a more significant place than it (not including the
1862 // sign bit) the ripple may go up to and fill the zero, but won't change the
1863 // sign. For example, (X & ~4) + 1.
1864
1865 // TODO: Implement.
1866
1867 return false;
1868}
1869
Chris Lattner2454a2e2008-01-29 06:52:45 +00001870
Chris Lattner7e708292002-06-25 16:13:24 +00001871Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001872 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001873 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001874
Chris Lattner66331a42004-04-10 22:01:55 +00001875 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001876 // X + undef -> undef
1877 if (isa<UndefValue>(RHS))
1878 return ReplaceInstUsesWith(I, RHS);
1879
Chris Lattner66331a42004-04-10 22:01:55 +00001880 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001881 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001882 if (RHSC->isNullValue())
1883 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001884 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001885 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1886 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001887 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001888 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001889
Chris Lattner66331a42004-04-10 22:01:55 +00001890 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001891 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001892 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001893 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001894 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001895 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001896
1897 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1898 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001899 if (!isa<VectorType>(I.getType())) {
1900 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1901 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1902 KnownZero, KnownOne))
1903 return &I;
1904 }
Chris Lattner66331a42004-04-10 22:01:55 +00001905 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001906
1907 if (isa<PHINode>(LHS))
1908 if (Instruction *NV = FoldOpIntoPhi(I))
1909 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001910
Chris Lattner4f637d42006-01-06 17:59:59 +00001911 ConstantInt *XorRHS = 0;
1912 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001913 if (isa<ConstantInt>(RHSC) &&
1914 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001915 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001916 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001917
Zhou Sheng4351c642007-04-02 08:20:41 +00001918 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001919 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1920 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001921 do {
1922 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001923 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1924 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001925 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1926 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001927 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001928 if (!MaskedValueIsZero(XorLHS,
1929 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001930 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001931 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001932 }
1933 }
1934 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001935 C0080Val = APIntOps::lshr(C0080Val, Size);
1936 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1937 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001938
Reid Spencer35c38852007-03-28 01:36:16 +00001939 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001940 // with funny bit widths then this switch statement should be removed. It
1941 // is just here to get the size of the "middle" type back up to something
1942 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001943 const Type *MiddleType = 0;
1944 switch (Size) {
1945 default: break;
1946 case 32: MiddleType = Type::Int32Ty; break;
1947 case 16: MiddleType = Type::Int16Ty; break;
1948 case 8: MiddleType = Type::Int8Ty; break;
1949 }
1950 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001951 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001952 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001953 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001954 }
1955 }
Chris Lattner66331a42004-04-10 22:01:55 +00001956 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001957
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001958 if (I.getType() == Type::Int1Ty)
1959 return BinaryOperator::CreateXor(LHS, RHS);
1960
Nick Lewycky7d26bd82008-05-23 04:39:38 +00001961 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001962 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001963 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001964
1965 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1966 if (RHSI->getOpcode() == Instruction::Sub)
1967 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1968 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1969 }
1970 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1971 if (LHSI->getOpcode() == Instruction::Sub)
1972 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1973 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1974 }
Robert Bocchino71698282004-07-27 21:02:21 +00001975 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001976
Chris Lattner5c4afb92002-05-08 22:46:53 +00001977 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00001978 // -A + -B --> -(A + B)
1979 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00001980 if (LHS->getType()->isIntOrIntVector()) {
1981 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001982 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00001983 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001984 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00001985 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00001986 }
1987
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001988 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00001989 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001990
1991 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001992 if (!isa<Constant>(RHS))
1993 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001994 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001995
Misha Brukmanfd939082005-04-21 23:48:37 +00001996
Chris Lattner50af16a2004-11-13 19:50:12 +00001997 ConstantInt *C2;
1998 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1999 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002000 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002001
2002 // X*C1 + X*C2 --> X * (C1+C2)
2003 ConstantInt *C1;
2004 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002005 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002006 }
2007
2008 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002009 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002010 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002011
Chris Lattnere617c9e2007-01-05 02:17:46 +00002012 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002013 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2014 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002015
Chris Lattnerad3448c2003-02-18 19:57:07 +00002016
Chris Lattner564a7272003-08-13 19:01:45 +00002017 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002018 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002019 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2020 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002021
2022 // A+B --> A|B iff A and B have no bits set in common.
2023 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2024 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2025 APInt LHSKnownOne(IT->getBitWidth(), 0);
2026 APInt LHSKnownZero(IT->getBitWidth(), 0);
2027 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2028 if (LHSKnownZero != 0) {
2029 APInt RHSKnownOne(IT->getBitWidth(), 0);
2030 APInt RHSKnownZero(IT->getBitWidth(), 0);
2031 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2032
2033 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002034 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002035 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002036 }
2037 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002038
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002039 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002040 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002041 Value *W, *X, *Y, *Z;
2042 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2043 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2044 if (W != Y) {
2045 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002046 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002047 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002048 std::swap(W, X);
2049 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002050 std::swap(Y, Z);
2051 std::swap(W, X);
2052 }
2053 }
2054
2055 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002056 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002057 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002058 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002059 }
2060 }
2061 }
2062
Chris Lattner6b032052003-10-02 15:11:26 +00002063 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002064 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002065 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002066 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002067
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002068 // (X & FF00) + xx00 -> (X+xx00) & FF00
2069 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002070 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002071 if (Anded == CRHS) {
2072 // See if all bits from the first bit set in the Add RHS up are included
2073 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002074 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002075
2076 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002077 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002078
2079 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002080 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002081
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002082 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2083 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002084 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002085 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002086 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002087 }
2088 }
2089 }
2090
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002091 // Try to fold constant add into select arguments.
2092 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002093 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002094 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002095 }
2096
Reid Spencer1628cec2006-10-26 06:15:43 +00002097 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002098 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002099 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002100 CastInst *CI = dyn_cast<CastInst>(LHS);
2101 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002102 if (!CI) {
2103 CI = dyn_cast<CastInst>(RHS);
2104 Other = LHS;
2105 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002106 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002107 (CI->getType()->getPrimitiveSizeInBits() ==
2108 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002109 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002110 unsigned AS =
2111 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002112 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2113 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002114 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002115 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002116 }
2117 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002118
Chris Lattner42790482007-12-20 01:56:58 +00002119 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002120 {
2121 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2122 Value *Other = RHS;
2123 if (!SI) {
2124 SI = dyn_cast<SelectInst>(RHS);
2125 Other = LHS;
2126 }
Chris Lattner42790482007-12-20 01:56:58 +00002127 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002128 Value *TV = SI->getTrueValue();
2129 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002130 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002131
2132 // Can we fold the add into the argument of the select?
2133 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002134 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2135 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002136 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002137 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2138 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002139 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002140 }
2141 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002142
2143 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2144 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2145 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2146 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002147
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002148 // Check for (add (sext x), y), see if we can merge this into an
2149 // integer add followed by a sext.
2150 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2151 // (add (sext x), cst) --> (sext (add x, cst'))
2152 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2153 Constant *CI =
2154 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2155 if (LHSConv->hasOneUse() &&
2156 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2157 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2158 // Insert the new, smaller add.
2159 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2160 CI, "addconv");
2161 InsertNewInstBefore(NewAdd, I);
2162 return new SExtInst(NewAdd, I.getType());
2163 }
2164 }
2165
2166 // (add (sext x), (sext y)) --> (sext (add int x, y))
2167 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2168 // Only do this if x/y have the same type, if at last one of them has a
2169 // single use (so we don't increase the number of sexts), and if the
2170 // integer add will not overflow.
2171 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2172 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2173 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2174 RHSConv->getOperand(0))) {
2175 // Insert the new integer add.
2176 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2177 RHSConv->getOperand(0),
2178 "addconv");
2179 InsertNewInstBefore(NewAdd, I);
2180 return new SExtInst(NewAdd, I.getType());
2181 }
2182 }
2183 }
2184
2185 // Check for (add double (sitofp x), y), see if we can merge this into an
2186 // integer add followed by a promotion.
2187 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2188 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2189 // ... if the constant fits in the integer value. This is useful for things
2190 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2191 // requires a constant pool load, and generally allows the add to be better
2192 // instcombined.
2193 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2194 Constant *CI =
2195 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2196 if (LHSConv->hasOneUse() &&
2197 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2198 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2199 // Insert the new integer add.
2200 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2201 CI, "addconv");
2202 InsertNewInstBefore(NewAdd, I);
2203 return new SIToFPInst(NewAdd, I.getType());
2204 }
2205 }
2206
2207 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2208 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2209 // Only do this if x/y have the same type, if at last one of them has a
2210 // single use (so we don't increase the number of int->fp conversions),
2211 // and if the integer add will not overflow.
2212 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2213 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2214 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2215 RHSConv->getOperand(0))) {
2216 // Insert the new integer add.
2217 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2218 RHSConv->getOperand(0),
2219 "addconv");
2220 InsertNewInstBefore(NewAdd, I);
2221 return new SIToFPInst(NewAdd, I.getType());
2222 }
2223 }
2224 }
2225
Chris Lattner7e708292002-06-25 16:13:24 +00002226 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002227}
2228
Chris Lattner7e708292002-06-25 16:13:24 +00002229Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002230 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002231
Chris Lattner233f7dc2002-08-12 21:17:25 +00002232 if (Op0 == Op1) // sub X, X -> 0
2233 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002234
Chris Lattner233f7dc2002-08-12 21:17:25 +00002235 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002236 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002237 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002238
Chris Lattnere87597f2004-10-16 18:11:37 +00002239 if (isa<UndefValue>(Op0))
2240 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2241 if (isa<UndefValue>(Op1))
2242 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2243
Chris Lattnerd65460f2003-11-05 01:06:05 +00002244 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2245 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002246 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002247 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002248
Chris Lattnerd65460f2003-11-05 01:06:05 +00002249 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002250 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002251 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002252 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002253
Chris Lattner76b7a062007-01-15 07:02:54 +00002254 // -(X >>u 31) -> (X >>s 31)
2255 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002256 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002257 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002258 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002259 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002260 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002261 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002262 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002263 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002264 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002265 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002266 }
2267 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002268 }
2269 else if (SI->getOpcode() == Instruction::AShr) {
2270 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2271 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002272 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002273 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002274 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002275 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002276 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002277 }
2278 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002279 }
2280 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002281 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002282
2283 // Try to fold constant sub into select arguments.
2284 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002285 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002286 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002287
2288 if (isa<PHINode>(Op0))
2289 if (Instruction *NV = FoldOpIntoPhi(I))
2290 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002291 }
2292
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002293 if (I.getType() == Type::Int1Ty)
2294 return BinaryOperator::CreateXor(Op0, Op1);
2295
Chris Lattner43d84d62005-04-07 16:15:25 +00002296 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2297 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002298 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002299 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002300 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002301 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002302 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002303 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2304 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2305 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002306 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002307 Op1I->getOperand(0));
2308 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002309 }
2310
Chris Lattnerfd059242003-10-15 16:48:29 +00002311 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002312 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2313 // is not used by anyone else...
2314 //
Chris Lattner0517e722004-02-02 20:09:56 +00002315 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002316 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002317 // Swap the two operands of the subexpr...
2318 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2319 Op1I->setOperand(0, IIOp1);
2320 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002321
Chris Lattnera2881962003-02-18 19:28:33 +00002322 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002323 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002324 }
2325
2326 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2327 //
2328 if (Op1I->getOpcode() == Instruction::And &&
2329 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2330 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2331
Chris Lattnerf523d062004-06-09 05:08:07 +00002332 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002333 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2334 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002335 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002336
Reid Spencerac5209e2006-10-16 23:08:08 +00002337 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002338 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002339 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002340 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002341 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002342 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002343 ConstantExpr::getNeg(DivRHS));
2344
Chris Lattnerad3448c2003-02-18 19:57:07 +00002345 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002346 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002347 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002348 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002349 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002350 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002351
2352 // X - ((X / Y) * Y) --> X % Y
2353 if (Op1I->getOpcode() == Instruction::Mul)
2354 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2355 if (Op0 == I->getOperand(0) &&
2356 Op1I->getOperand(1) == I->getOperand(1)) {
2357 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002358 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002359 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002360 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002361 }
Chris Lattner40371712002-05-09 01:29:19 +00002362 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002363 }
Chris Lattnera2881962003-02-18 19:28:33 +00002364
Chris Lattner9919e3d2006-12-02 00:13:08 +00002365 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002366 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002367 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002368 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2369 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2370 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2371 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002372 } else if (Op0I->getOpcode() == Instruction::Sub) {
2373 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002374 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002375 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002376 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002377
Chris Lattner50af16a2004-11-13 19:50:12 +00002378 ConstantInt *C1;
2379 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002380 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002381 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002382
Chris Lattner50af16a2004-11-13 19:50:12 +00002383 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2384 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002385 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002386 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002387 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002388}
2389
Chris Lattnera0141b92007-07-15 20:42:37 +00002390/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2391/// comparison only checks the sign bit. If it only checks the sign bit, set
2392/// TrueIfSigned if the result of the comparison is true when the input value is
2393/// signed.
2394static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2395 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002396 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002397 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2398 TrueIfSigned = true;
2399 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002400 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2401 TrueIfSigned = true;
2402 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002403 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2404 TrueIfSigned = false;
2405 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002406 case ICmpInst::ICMP_UGT:
2407 // True if LHS u> RHS and RHS == high-bit-mask - 1
2408 TrueIfSigned = true;
2409 return RHS->getValue() ==
2410 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2411 case ICmpInst::ICMP_UGE:
2412 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2413 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002414 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002415 default:
2416 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002417 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002418}
2419
Chris Lattner7e708292002-06-25 16:13:24 +00002420Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002421 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002422 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002423
Chris Lattnere87597f2004-10-16 18:11:37 +00002424 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2426
Chris Lattner233f7dc2002-08-12 21:17:25 +00002427 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002428 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2429 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002430
2431 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002432 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002433 if (SI->getOpcode() == Instruction::Shl)
2434 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002435 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002436 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002437
Zhou Sheng843f07672007-04-19 05:39:12 +00002438 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002439 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2440 if (CI->equalsInt(1)) // X * 1 == X
2441 return ReplaceInstUsesWith(I, Op0);
2442 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002444
Zhou Sheng97b52c22007-03-29 01:57:21 +00002445 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002446 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002448 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002449 }
Robert Bocchino71698282004-07-27 21:02:21 +00002450 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002451 if (Op1F->isNullValue())
2452 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002453
Chris Lattnera2881962003-02-18 19:28:33 +00002454 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2455 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002456 // We need a better interface for long double here.
2457 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2458 if (Op1F->isExactlyValue(1.0))
2459 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002460 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002461
2462 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2463 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002464 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002465 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002466 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002467 Op1, "tmp");
2468 InsertNewInstBefore(Add, I);
2469 Value *C1C2 = ConstantExpr::getMul(Op1,
2470 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002472
2473 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002474
2475 // Try to fold constant mul into select arguments.
2476 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002477 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002478 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002479
2480 if (isa<PHINode>(Op0))
2481 if (Instruction *NV = FoldOpIntoPhi(I))
2482 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002483 }
2484
Chris Lattnera4f445b2003-03-10 23:23:04 +00002485 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2486 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002487 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002488
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002489 if (I.getType() == Type::Int1Ty)
2490 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2491
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002492 // If one of the operands of the multiply is a cast from a boolean value, then
2493 // we know the bool is either zero or one, so this is a 'masking' multiply.
2494 // See if we can simplify things based on how the boolean was originally
2495 // formed.
2496 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002497 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002498 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002499 BoolCast = CI;
2500 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002501 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002502 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002503 BoolCast = CI;
2504 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002505 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002506 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2507 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002508 bool TIS = false;
2509
Reid Spencere4d87aa2006-12-23 06:05:41 +00002510 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002511 // multiply into a shift/and combination.
2512 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002513 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2514 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002515 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002516 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002517 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002518 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002519 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002520 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002521 BoolCast->getOperand(0)->getName()+
2522 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002523
2524 // If the multiply type is not the same as the source type, sign extend
2525 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002526 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002527 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2528 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002529 Instruction::CastOps opcode =
2530 (SrcBits == DstBits ? Instruction::BitCast :
2531 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2532 V = InsertCastBefore(opcode, V, I.getType(), I);
2533 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002534
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002535 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002537 }
2538 }
2539 }
2540
Chris Lattner7e708292002-06-25 16:13:24 +00002541 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002542}
2543
Reid Spencer1628cec2006-10-26 06:15:43 +00002544/// This function implements the transforms on div instructions that work
2545/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2546/// used by the visitors to those instructions.
2547/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002548Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002549 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002550
Chris Lattner50b2ca42008-02-19 06:12:18 +00002551 // undef / X -> 0 for integer.
2552 // undef / X -> undef for FP (the undef could be a snan).
2553 if (isa<UndefValue>(Op0)) {
2554 if (Op0->getType()->isFPOrFPVector())
2555 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002557 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002558
2559 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002560 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002561 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002562
Chris Lattner25feae52008-01-28 00:58:18 +00002563 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2564 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002565 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002566 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2567 // the same basic block, then we replace the select with Y, and the
2568 // condition of the select with false (if the cond value is in the same BB).
2569 // If the select has uses other than the div, this allows them to be
2570 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2571 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002572 if (ST->isNullValue()) {
2573 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2574 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002575 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002576 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2577 I.setOperand(1, SI->getOperand(2));
2578 else
2579 UpdateValueUsesWith(SI, SI->getOperand(2));
2580 return &I;
2581 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002582
Chris Lattner25feae52008-01-28 00:58:18 +00002583 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2584 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002585 if (ST->isNullValue()) {
2586 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2587 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002588 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002589 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2590 I.setOperand(1, SI->getOperand(1));
2591 else
2592 UpdateValueUsesWith(SI, SI->getOperand(1));
2593 return &I;
2594 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002595 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002596
Reid Spencer1628cec2006-10-26 06:15:43 +00002597 return 0;
2598}
Misha Brukmanfd939082005-04-21 23:48:37 +00002599
Reid Spencer1628cec2006-10-26 06:15:43 +00002600/// This function implements the transforms common to both integer division
2601/// instructions (udiv and sdiv). It is called by the visitors to those integer
2602/// division instructions.
2603/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002604Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2606
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002607 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002608 if (Op0 == Op1) {
2609 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2610 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2611 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2612 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2613 }
2614
2615 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2616 return ReplaceInstUsesWith(I, CI);
2617 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002618
Reid Spencer1628cec2006-10-26 06:15:43 +00002619 if (Instruction *Common = commonDivTransforms(I))
2620 return Common;
2621
2622 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2623 // div X, 1 == X
2624 if (RHS->equalsInt(1))
2625 return ReplaceInstUsesWith(I, Op0);
2626
2627 // (X / C1) / C2 -> X / (C1*C2)
2628 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2629 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2630 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002631 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2632 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2633 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002634 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002635 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002636 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002637
Reid Spencerbca0e382007-03-23 20:05:17 +00002638 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002639 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2640 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2641 return R;
2642 if (isa<PHINode>(Op0))
2643 if (Instruction *NV = FoldOpIntoPhi(I))
2644 return NV;
2645 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002646 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002647
Chris Lattnera2881962003-02-18 19:28:33 +00002648 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002649 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002650 if (LHS->equalsInt(0))
2651 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2652
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002653 // It can't be division by zero, hence it must be division by one.
2654 if (I.getType() == Type::Int1Ty)
2655 return ReplaceInstUsesWith(I, Op0);
2656
Reid Spencer1628cec2006-10-26 06:15:43 +00002657 return 0;
2658}
2659
2660Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2661 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2662
2663 // Handle the integer div common cases
2664 if (Instruction *Common = commonIDivTransforms(I))
2665 return Common;
2666
2667 // X udiv C^2 -> X >> C
2668 // Check to see if this is an unsigned division with an exact power of 2,
2669 // if so, convert to a right shift.
2670 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002671 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002673 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002674 }
2675
2676 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002677 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002678 if (RHSI->getOpcode() == Instruction::Shl &&
2679 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002680 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002681 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002682 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002683 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002684 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002685 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002687 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002688 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002689 }
2690 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002691 }
2692
Reid Spencer1628cec2006-10-26 06:15:43 +00002693 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2694 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002695 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002696 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002697 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002698 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002699 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002700 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002701 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002702 // Construct the "on true" case of the select
2703 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002704 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002705 Op0, TC, SI->getName()+".t");
2706 TSI = InsertNewInstBefore(TSI, I);
2707
2708 // Construct the "on false" case of the select
2709 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002710 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002711 Op0, FC, SI->getName()+".f");
2712 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002713
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002714 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002715 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002716 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002717 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002718 return 0;
2719}
2720
Reid Spencer1628cec2006-10-26 06:15:43 +00002721Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2722 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2723
2724 // Handle the integer div common cases
2725 if (Instruction *Common = commonIDivTransforms(I))
2726 return Common;
2727
2728 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2729 // sdiv X, -1 == -X
2730 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002731 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002732
2733 // -X/C -> X/-C
2734 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002735 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002736 }
2737
2738 // If the sign bits of both operands are zero (i.e. we can prove they are
2739 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002740 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002741 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002742 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002743 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002744 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002745 }
2746 }
2747
2748 return 0;
2749}
2750
2751Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2752 return commonDivTransforms(I);
2753}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002754
Reid Spencer0a783f72006-11-02 01:53:59 +00002755/// This function implements the transforms on rem instructions that work
2756/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2757/// is used by the visitors to those instructions.
2758/// @brief Transforms common to all three rem instructions
2759Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002760 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002761
Chris Lattner50b2ca42008-02-19 06:12:18 +00002762 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002763 if (Constant *LHS = dyn_cast<Constant>(Op0))
2764 if (LHS->isNullValue())
2765 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2766
Chris Lattner50b2ca42008-02-19 06:12:18 +00002767 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2768 if (I.getType()->isFPOrFPVector())
2769 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002771 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002772 if (isa<UndefValue>(Op1))
2773 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002774
2775 // Handle cases involving: rem X, (select Cond, Y, Z)
2776 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2777 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2778 // the same basic block, then we replace the select with Y, and the
2779 // condition of the select with false (if the cond value is in the same
2780 // BB). If the select has uses other than the div, this allows them to be
2781 // simplified also.
2782 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2783 if (ST->isNullValue()) {
2784 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2785 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002786 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002787 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2788 I.setOperand(1, SI->getOperand(2));
2789 else
2790 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002791 return &I;
2792 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002793 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2794 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2795 if (ST->isNullValue()) {
2796 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2797 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002798 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002799 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2800 I.setOperand(1, SI->getOperand(1));
2801 else
2802 UpdateValueUsesWith(SI, SI->getOperand(1));
2803 return &I;
2804 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002805 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002806
Reid Spencer0a783f72006-11-02 01:53:59 +00002807 return 0;
2808}
2809
2810/// This function implements the transforms common to both integer remainder
2811/// instructions (urem and srem). It is called by the visitors to those integer
2812/// remainder instructions.
2813/// @brief Common integer remainder transforms
2814Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2815 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2816
2817 if (Instruction *common = commonRemTransforms(I))
2818 return common;
2819
Chris Lattner857e8cd2004-12-12 21:48:58 +00002820 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002821 // X % 0 == undef, we don't need to preserve faults!
2822 if (RHS->equalsInt(0))
2823 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2824
Chris Lattnera2881962003-02-18 19:28:33 +00002825 if (RHS->equalsInt(1)) // X % 1 == 0
2826 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2827
Chris Lattner97943922006-02-28 05:49:21 +00002828 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2829 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2830 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2831 return R;
2832 } else if (isa<PHINode>(Op0I)) {
2833 if (Instruction *NV = FoldOpIntoPhi(I))
2834 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002835 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002836
2837 // See if we can fold away this rem instruction.
2838 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2839 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2840 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2841 KnownZero, KnownOne))
2842 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002843 }
Chris Lattnera2881962003-02-18 19:28:33 +00002844 }
2845
Reid Spencer0a783f72006-11-02 01:53:59 +00002846 return 0;
2847}
2848
2849Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2851
2852 if (Instruction *common = commonIRemTransforms(I))
2853 return common;
2854
2855 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2856 // X urem C^2 -> X and C
2857 // Check to see if this is an unsigned remainder with an exact power of 2,
2858 // if so, convert to a bitwise and.
2859 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002860 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002861 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002862 }
2863
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002864 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002865 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2866 if (RHSI->getOpcode() == Instruction::Shl &&
2867 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002868 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002869 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002870 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002871 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002872 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002873 }
2874 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002875 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002876
Reid Spencer0a783f72006-11-02 01:53:59 +00002877 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2878 // where C1&C2 are powers of two.
2879 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2880 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2881 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2882 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002883 if ((STO->getValue().isPowerOf2()) &&
2884 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002885 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002886 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002887 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002888 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002889 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002890 }
2891 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002892 }
2893
Chris Lattner3f5b8772002-05-06 16:14:14 +00002894 return 0;
2895}
2896
Reid Spencer0a783f72006-11-02 01:53:59 +00002897Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2898 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2899
Dan Gohmancff55092007-11-05 23:16:33 +00002900 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002901 if (Instruction *common = commonIRemTransforms(I))
2902 return common;
2903
2904 if (Value *RHSNeg = dyn_castNegVal(Op1))
2905 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002906 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002907 // X % -Y -> X % Y
2908 AddUsesToWorkList(I);
2909 I.setOperand(1, RHSNeg);
2910 return &I;
2911 }
2912
Dan Gohmancff55092007-11-05 23:16:33 +00002913 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002914 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002915 if (I.getType()->isInteger()) {
2916 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2917 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2918 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002919 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002920 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002921 }
2922
2923 return 0;
2924}
2925
2926Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002927 return commonRemTransforms(I);
2928}
2929
Chris Lattner8b170942002-08-09 23:47:40 +00002930// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002931static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002932 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002933 if (!isSigned)
2934 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2935 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002936}
2937
2938// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002939static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002940 if (!isSigned)
2941 return C->getValue() == 1; // unsigned
2942
2943 // Calculate 1111111111000000000000
2944 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2945 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002946}
2947
Chris Lattner457dd822004-06-09 07:59:58 +00002948// isOneBitSet - Return true if there is exactly one bit set in the specified
2949// constant.
2950static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002951 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002952}
2953
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002954// isHighOnes - Return true if the constant is of the form 1+0+.
2955// This is the same as lowones(~X).
2956static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002957 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002958}
2959
Reid Spencere4d87aa2006-12-23 06:05:41 +00002960/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002961/// are carefully arranged to allow folding of expressions such as:
2962///
2963/// (A < B) | (A > B) --> (A != B)
2964///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002965/// Note that this is only valid if the first and second predicates have the
2966/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002967///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002968/// Three bits are used to represent the condition, as follows:
2969/// 0 A > B
2970/// 1 A == B
2971/// 2 A < B
2972///
2973/// <=> Value Definition
2974/// 000 0 Always false
2975/// 001 1 A > B
2976/// 010 2 A == B
2977/// 011 3 A >= B
2978/// 100 4 A < B
2979/// 101 5 A != B
2980/// 110 6 A <= B
2981/// 111 7 Always true
2982///
2983static unsigned getICmpCode(const ICmpInst *ICI) {
2984 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002985 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002986 case ICmpInst::ICMP_UGT: return 1; // 001
2987 case ICmpInst::ICMP_SGT: return 1; // 001
2988 case ICmpInst::ICMP_EQ: return 2; // 010
2989 case ICmpInst::ICMP_UGE: return 3; // 011
2990 case ICmpInst::ICMP_SGE: return 3; // 011
2991 case ICmpInst::ICMP_ULT: return 4; // 100
2992 case ICmpInst::ICMP_SLT: return 4; // 100
2993 case ICmpInst::ICMP_NE: return 5; // 101
2994 case ICmpInst::ICMP_ULE: return 6; // 110
2995 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002996 // True -> 7
2997 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002998 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002999 return 0;
3000 }
3001}
3002
Reid Spencere4d87aa2006-12-23 06:05:41 +00003003/// getICmpValue - This is the complement of getICmpCode, which turns an
3004/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003005/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003006/// of predicate to use in new icmp instructions.
3007static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3008 switch (code) {
3009 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003010 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003011 case 1:
3012 if (sign)
3013 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3014 else
3015 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3016 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3017 case 3:
3018 if (sign)
3019 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3020 else
3021 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3022 case 4:
3023 if (sign)
3024 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3025 else
3026 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3027 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3028 case 6:
3029 if (sign)
3030 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3031 else
3032 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003033 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003034 }
3035}
3036
Reid Spencere4d87aa2006-12-23 06:05:41 +00003037static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3038 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3039 (ICmpInst::isSignedPredicate(p1) &&
3040 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3041 (ICmpInst::isSignedPredicate(p2) &&
3042 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3043}
3044
3045namespace {
3046// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3047struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003048 InstCombiner &IC;
3049 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003050 ICmpInst::Predicate pred;
3051 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3052 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3053 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003054 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003055 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3056 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003057 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3058 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003059 return false;
3060 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003061 Instruction *apply(Instruction &Log) const {
3062 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3063 if (ICI->getOperand(0) != LHS) {
3064 assert(ICI->getOperand(1) == LHS);
3065 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003066 }
3067
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003068 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003069 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003070 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003071 unsigned Code;
3072 switch (Log.getOpcode()) {
3073 case Instruction::And: Code = LHSCode & RHSCode; break;
3074 case Instruction::Or: Code = LHSCode | RHSCode; break;
3075 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003076 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003077 }
3078
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003079 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3080 ICmpInst::isSignedPredicate(ICI->getPredicate());
3081
3082 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003083 if (Instruction *I = dyn_cast<Instruction>(RV))
3084 return I;
3085 // Otherwise, it's a constant boolean value...
3086 return IC.ReplaceInstUsesWith(Log, RV);
3087 }
3088};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003089} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003090
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003091// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3092// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003093// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003094Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003095 ConstantInt *OpRHS,
3096 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003097 BinaryOperator &TheAnd) {
3098 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003099 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003100 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003101 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003102
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003103 switch (Op->getOpcode()) {
3104 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003105 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003106 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003107 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003108 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003109 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003110 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003111 }
3112 break;
3113 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003114 if (Together == AndRHS) // (X | C) & C --> C
3115 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003116
Chris Lattner6e7ba452005-01-01 16:22:27 +00003117 if (Op->hasOneUse() && Together != OpRHS) {
3118 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003119 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003120 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003121 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003122 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003123 }
3124 break;
3125 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003126 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003127 // Adding a one to a single bit bit-field should be turned into an XOR
3128 // of the bit. First thing to check is to see if this AND is with a
3129 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003130 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003131
3132 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003133 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003134 // Ok, at this point, we know that we are masking the result of the
3135 // ADD down to exactly one bit. If the constant we are adding has
3136 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003137 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003138
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003139 // Check to see if any bits below the one bit set in AndRHSV are set.
3140 if ((AddRHS & (AndRHSV-1)) == 0) {
3141 // If not, the only thing that can effect the output of the AND is
3142 // the bit specified by AndRHSV. If that bit is set, the effect of
3143 // the XOR is to toggle the bit. If it is clear, then the ADD has
3144 // no effect.
3145 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3146 TheAnd.setOperand(0, X);
3147 return &TheAnd;
3148 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003149 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003150 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003151 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003152 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003153 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003154 }
3155 }
3156 }
3157 }
3158 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003159
3160 case Instruction::Shl: {
3161 // We know that the AND will not produce any of the bits shifted in, so if
3162 // the anded constant includes them, clear them now!
3163 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003164 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003165 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003166 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3167 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003168
Zhou Sheng290bec52007-03-29 08:15:12 +00003169 if (CI->getValue() == ShlMask) {
3170 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003171 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3172 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003173 TheAnd.setOperand(1, CI);
3174 return &TheAnd;
3175 }
3176 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003177 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003178 case Instruction::LShr:
3179 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003180 // We know that the AND will not produce any of the bits shifted in, so if
3181 // the anded constant includes them, clear them now! This only applies to
3182 // unsigned shifts, because a signed shr may bring in set bits!
3183 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003184 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003185 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003186 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3187 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003188
Zhou Sheng290bec52007-03-29 08:15:12 +00003189 if (CI->getValue() == ShrMask) {
3190 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003191 return ReplaceInstUsesWith(TheAnd, Op);
3192 } else if (CI != AndRHS) {
3193 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3194 return &TheAnd;
3195 }
3196 break;
3197 }
3198 case Instruction::AShr:
3199 // Signed shr.
3200 // See if this is shifting in some sign extension, then masking it out
3201 // with an and.
3202 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003203 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003204 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003205 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3206 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003207 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003208 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003209 // Make the argument unsigned.
3210 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003211 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003212 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003213 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003214 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003215 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003216 }
3217 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003218 }
3219 return 0;
3220}
3221
Chris Lattner8b170942002-08-09 23:47:40 +00003222
Chris Lattnera96879a2004-09-29 17:40:11 +00003223/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3224/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003225/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3226/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003227/// insert new instructions.
3228Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003229 bool isSigned, bool Inside,
3230 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003231 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003232 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003233 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003234
Chris Lattnera96879a2004-09-29 17:40:11 +00003235 if (Inside) {
3236 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003237 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003238
Reid Spencere4d87aa2006-12-23 06:05:41 +00003239 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003240 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003241 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003242 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3243 return new ICmpInst(pred, V, Hi);
3244 }
3245
3246 // Emit V-Lo <u Hi-Lo
3247 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003248 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003249 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003250 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3251 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003252 }
3253
3254 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003255 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003256
Reid Spencere4e40032007-03-21 23:19:50 +00003257 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003258 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003259 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003260 ICmpInst::Predicate pred = (isSigned ?
3261 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3262 return new ICmpInst(pred, V, Hi);
3263 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003264
Reid Spencere4e40032007-03-21 23:19:50 +00003265 // Emit V-Lo >u Hi-1-Lo
3266 // Note that Hi has already had one subtracted from it, above.
3267 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003268 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003269 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003270 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3271 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003272}
3273
Chris Lattner7203e152005-09-18 07:22:02 +00003274// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3275// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3276// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3277// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003278static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003279 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003280 uint32_t BitWidth = Val->getType()->getBitWidth();
3281 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003282
3283 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003284 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003285 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003286 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003287 return true;
3288}
3289
Chris Lattner7203e152005-09-18 07:22:02 +00003290/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3291/// where isSub determines whether the operator is a sub. If we can fold one of
3292/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003293///
3294/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3295/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3296/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3297///
3298/// return (A +/- B).
3299///
3300Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003301 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003302 Instruction &I) {
3303 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3304 if (!LHSI || LHSI->getNumOperands() != 2 ||
3305 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3306
3307 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3308
3309 switch (LHSI->getOpcode()) {
3310 default: return 0;
3311 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003312 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003313 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003314 if ((Mask->getValue().countLeadingZeros() +
3315 Mask->getValue().countPopulation()) ==
3316 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003317 break;
3318
3319 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3320 // part, we don't need any explicit masks to take them out of A. If that
3321 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003322 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003323 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003324 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003325 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003326 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003327 break;
3328 }
3329 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003330 return 0;
3331 case Instruction::Or:
3332 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003333 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003334 if ((Mask->getValue().countLeadingZeros() +
3335 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003336 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003337 break;
3338 return 0;
3339 }
3340
3341 Instruction *New;
3342 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003343 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003344 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003345 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003346 return InsertNewInstBefore(New, I);
3347}
3348
Chris Lattner7e708292002-06-25 16:13:24 +00003349Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003350 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003351 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003352
Chris Lattnere87597f2004-10-16 18:11:37 +00003353 if (isa<UndefValue>(Op1)) // X & undef -> 0
3354 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3355
Chris Lattner6e7ba452005-01-01 16:22:27 +00003356 // and X, X = X
3357 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003358 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003359
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003360 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003361 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003362 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003363 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3364 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3365 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003366 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003367 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003368 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003369 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003370 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003371 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003372 } else if (isa<ConstantAggregateZero>(Op1)) {
3373 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003374 }
3375 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003376
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003377 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003378 const APInt& AndRHSMask = AndRHS->getValue();
3379 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003380
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003381 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003382 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003383 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003384 Value *Op0LHS = Op0I->getOperand(0);
3385 Value *Op0RHS = Op0I->getOperand(1);
3386 switch (Op0I->getOpcode()) {
3387 case Instruction::Xor:
3388 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003389 // If the mask is only needed on one incoming arm, push it up.
3390 if (Op0I->hasOneUse()) {
3391 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3392 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003393 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003394 Op0RHS->getName()+".masked");
3395 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003396 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003397 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003398 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003399 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003400 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3401 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003402 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003403 Op0LHS->getName()+".masked");
3404 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003405 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003406 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3407 }
3408 }
3409
Chris Lattner6e7ba452005-01-01 16:22:27 +00003410 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003411 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003412 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3413 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3414 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3415 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003416 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003417 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003418 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003419 break;
3420
3421 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003422 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3423 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3424 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3425 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003426 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003427 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003428 }
3429
Chris Lattner58403262003-07-23 19:25:52 +00003430 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003431 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003432 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003433 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003434 // If this is an integer truncation or change from signed-to-unsigned, and
3435 // if the source is an and/or with immediate, transform it. This
3436 // frequently occurs for bitfield accesses.
3437 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003438 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003439 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003440 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003441 if (CastOp->getOpcode() == Instruction::And) {
3442 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003443 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3444 // This will fold the two constants together, which may allow
3445 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003446 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003447 CastOp->getOperand(0), I.getType(),
3448 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003449 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003450 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003451 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003452 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003453 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003454 } else if (CastOp->getOpcode() == Instruction::Or) {
3455 // Change: and (cast (or X, C1) to T), C2
3456 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003457 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003458 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3459 return ReplaceInstUsesWith(I, AndRHS);
3460 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003461 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003462 }
Chris Lattner06782f82003-07-23 19:36:21 +00003463 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003464
3465 // Try to fold constant and into select arguments.
3466 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003467 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003468 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003469 if (isa<PHINode>(Op0))
3470 if (Instruction *NV = FoldOpIntoPhi(I))
3471 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003472 }
3473
Chris Lattner8d969642003-03-10 23:06:50 +00003474 Value *Op0NotVal = dyn_castNotVal(Op0);
3475 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003476
Chris Lattner5b62aa72004-06-18 06:07:51 +00003477 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3478 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3479
Misha Brukmancb6267b2004-07-30 12:50:08 +00003480 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003481 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003482 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003483 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003484 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003485 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003486 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003487
3488 {
Chris Lattner003b6202007-06-15 05:58:24 +00003489 Value *A = 0, *B = 0, *C = 0, *D = 0;
3490 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003491 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3492 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003493
3494 // (A|B) & ~(A&B) -> A^B
3495 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3496 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003497 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003498 }
3499 }
3500
3501 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003502 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3503 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003504
3505 // ~(A&B) & (A|B) -> A^B
3506 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3507 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003508 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003509 }
3510 }
Chris Lattner64daab52006-04-01 08:03:55 +00003511
3512 if (Op0->hasOneUse() &&
3513 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3514 if (A == Op1) { // (A^B)&A -> A&(A^B)
3515 I.swapOperands(); // Simplify below
3516 std::swap(Op0, Op1);
3517 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3518 cast<BinaryOperator>(Op0)->swapOperands();
3519 I.swapOperands(); // Simplify below
3520 std::swap(Op0, Op1);
3521 }
3522 }
3523 if (Op1->hasOneUse() &&
3524 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3525 if (B == Op0) { // B&(A^B) -> B&(B^A)
3526 cast<BinaryOperator>(Op1)->swapOperands();
3527 std::swap(A, B);
3528 }
3529 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003530 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003531 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003532 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003533 }
3534 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003535 }
3536
Reid Spencere4d87aa2006-12-23 06:05:41 +00003537 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3538 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3539 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003540 return R;
3541
Chris Lattner955f3312004-09-28 21:48:02 +00003542 Value *LHSVal, *RHSVal;
3543 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003544 ICmpInst::Predicate LHSCC, RHSCC;
3545 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3546 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3547 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3548 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3549 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3550 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3551 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003552 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3553
3554 // Don't try to fold ICMP_SLT + ICMP_ULT.
3555 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3556 ICmpInst::isSignedPredicate(LHSCC) ==
3557 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003558 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003559 ICmpInst::Predicate GT;
3560 if (ICmpInst::isSignedPredicate(LHSCC) ||
3561 (ICmpInst::isEquality(LHSCC) &&
3562 ICmpInst::isSignedPredicate(RHSCC)))
3563 GT = ICmpInst::ICMP_SGT;
3564 else
3565 GT = ICmpInst::ICMP_UGT;
3566
Reid Spencere4d87aa2006-12-23 06:05:41 +00003567 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3568 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003569 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003570 std::swap(LHS, RHS);
3571 std::swap(LHSCst, RHSCst);
3572 std::swap(LHSCC, RHSCC);
3573 }
3574
Reid Spencere4d87aa2006-12-23 06:05:41 +00003575 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003576 // comparing a value against two constants and and'ing the result
3577 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003578 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3579 // (from the FoldICmpLogical check above), that the two constants
3580 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003581 assert(LHSCst != RHSCst && "Compares not folded above?");
3582
3583 switch (LHSCC) {
3584 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003585 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003586 switch (RHSCC) {
3587 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003588 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3589 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3590 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003591 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003592 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3593 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3594 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003595 return ReplaceInstUsesWith(I, LHS);
3596 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003597 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003598 switch (RHSCC) {
3599 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003600 case ICmpInst::ICMP_ULT:
3601 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3602 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3603 break; // (X != 13 & X u< 15) -> no change
3604 case ICmpInst::ICMP_SLT:
3605 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3606 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3607 break; // (X != 13 & X s< 15) -> no change
3608 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3609 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3610 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003611 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003612 case ICmpInst::ICMP_NE:
3613 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003614 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003615 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003616 LHSVal->getName()+".off");
3617 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003618 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3619 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003620 }
3621 break; // (X != 13 & X != 15) -> no change
3622 }
3623 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003624 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003625 switch (RHSCC) {
3626 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003627 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3628 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003629 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003630 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3631 break;
3632 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3633 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003634 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3636 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003637 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003638 break;
3639 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003640 switch (RHSCC) {
3641 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3643 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003644 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003645 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3646 break;
3647 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3648 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003649 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3651 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003652 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 break;
3654 case ICmpInst::ICMP_UGT:
3655 switch (RHSCC) {
3656 default: assert(0 && "Unknown integer condition code!");
3657 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3658 return ReplaceInstUsesWith(I, LHS);
3659 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3660 return ReplaceInstUsesWith(I, RHS);
3661 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3662 break;
3663 case ICmpInst::ICMP_NE:
3664 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3665 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3666 break; // (X u> 13 & X != 15) -> no change
3667 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3668 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3669 true, I);
3670 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3671 break;
3672 }
3673 break;
3674 case ICmpInst::ICMP_SGT:
3675 switch (RHSCC) {
3676 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003677 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3679 return ReplaceInstUsesWith(I, RHS);
3680 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3681 break;
3682 case ICmpInst::ICMP_NE:
3683 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3684 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3685 break; // (X s> 13 & X != 15) -> no change
3686 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3687 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3688 true, I);
3689 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3690 break;
3691 }
3692 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003693 }
3694 }
3695 }
3696
Chris Lattner6fc205f2006-05-05 06:39:07 +00003697 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003698 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3699 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3700 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3701 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003702 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003703 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3705 I.getType(), TD) &&
3706 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3707 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003708 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003709 Op1C->getOperand(0),
3710 I.getName());
3711 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003712 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003713 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003714 }
Chris Lattnere511b742006-11-14 07:46:50 +00003715
3716 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003717 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3718 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3719 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003720 SI0->getOperand(1) == SI1->getOperand(1) &&
3721 (SI0->hasOneUse() || SI1->hasOneUse())) {
3722 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003723 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003724 SI1->getOperand(0),
3725 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003726 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003727 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003728 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003729 }
3730
Chris Lattner99c65742007-10-24 05:38:08 +00003731 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3732 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3733 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3734 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3735 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3736 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3737 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3738 // If either of the constants are nans, then the whole thing returns
3739 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003740 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003741 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3742 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3743 RHS->getOperand(0));
3744 }
3745 }
3746 }
3747
Chris Lattner7e708292002-06-25 16:13:24 +00003748 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003749}
3750
Chris Lattnerafe91a52006-06-15 19:07:26 +00003751/// CollectBSwapParts - Look to see if the specified value defines a single byte
3752/// in the result. If it does, and if the specified byte hasn't been filled in
3753/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003754static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003755 Instruction *I = dyn_cast<Instruction>(V);
3756 if (I == 0) return true;
3757
3758 // If this is an or instruction, it is an inner node of the bswap.
3759 if (I->getOpcode() == Instruction::Or)
3760 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3761 CollectBSwapParts(I->getOperand(1), ByteValues);
3762
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003763 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003764 // If this is a shift by a constant int, and it is "24", then its operand
3765 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003766 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003767 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003768 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003769 8*(ByteValues.size()-1))
3770 return true;
3771
3772 unsigned DestNo;
3773 if (I->getOpcode() == Instruction::Shl) {
3774 // X << 24 defines the top byte with the lowest of the input bytes.
3775 DestNo = ByteValues.size()-1;
3776 } else {
3777 // X >>u 24 defines the low byte with the highest of the input bytes.
3778 DestNo = 0;
3779 }
3780
3781 // If the destination byte value is already defined, the values are or'd
3782 // together, which isn't a bswap (unless it's an or of the same bits).
3783 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3784 return true;
3785 ByteValues[DestNo] = I->getOperand(0);
3786 return false;
3787 }
3788
3789 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3790 // don't have this.
3791 Value *Shift = 0, *ShiftLHS = 0;
3792 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3793 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3794 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3795 return true;
3796 Instruction *SI = cast<Instruction>(Shift);
3797
3798 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003799 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3800 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003801 return true;
3802
3803 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3804 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003805 if (AndAmt->getValue().getActiveBits() > 64)
3806 return true;
3807 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003808 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003809 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003810 break;
3811 // Unknown mask for bswap.
3812 if (DestByte == ByteValues.size()) return true;
3813
Reid Spencerb83eb642006-10-20 07:07:24 +00003814 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003815 unsigned SrcByte;
3816 if (SI->getOpcode() == Instruction::Shl)
3817 SrcByte = DestByte - ShiftBytes;
3818 else
3819 SrcByte = DestByte + ShiftBytes;
3820
3821 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3822 if (SrcByte != ByteValues.size()-DestByte-1)
3823 return true;
3824
3825 // If the destination byte value is already defined, the values are or'd
3826 // together, which isn't a bswap (unless it's an or of the same bits).
3827 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3828 return true;
3829 ByteValues[DestByte] = SI->getOperand(0);
3830 return false;
3831}
3832
3833/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3834/// If so, insert the new bswap intrinsic and return it.
3835Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003836 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3837 if (!ITy || ITy->getBitWidth() % 16)
3838 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003839
3840 /// ByteValues - For each byte of the result, we keep track of which value
3841 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003842 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003843 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003844
3845 // Try to find all the pieces corresponding to the bswap.
3846 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3847 CollectBSwapParts(I.getOperand(1), ByteValues))
3848 return 0;
3849
3850 // Check to see if all of the bytes come from the same value.
3851 Value *V = ByteValues[0];
3852 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3853
3854 // Check to make sure that all of the bytes come from the same value.
3855 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3856 if (ByteValues[i] != V)
3857 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003858 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003859 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003860 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003861 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003862}
3863
3864
Chris Lattner7e708292002-06-25 16:13:24 +00003865Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003866 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003868
Chris Lattner42593e62007-03-24 23:56:43 +00003869 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003870 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003871
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003872 // or X, X = X
3873 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003874 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003875
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003876 // See if we can simplify any instructions used by the instruction whose sole
3877 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003878 if (!isa<VectorType>(I.getType())) {
3879 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3880 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3881 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3882 KnownZero, KnownOne))
3883 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003884 } else if (isa<ConstantAggregateZero>(Op1)) {
3885 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3886 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3887 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3888 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003889 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003890
3891
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003892
Chris Lattner3f5b8772002-05-06 16:14:14 +00003893 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003894 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003895 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003896 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3897 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003898 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003899 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003900 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003902 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003903 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003904
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003905 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3906 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003907 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003908 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003909 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003910 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003911 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003912 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003913
3914 // Try to fold constant and into select arguments.
3915 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003916 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003917 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003918 if (isa<PHINode>(Op0))
3919 if (Instruction *NV = FoldOpIntoPhi(I))
3920 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003921 }
3922
Chris Lattner4f637d42006-01-06 17:59:59 +00003923 Value *A = 0, *B = 0;
3924 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003925
3926 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3927 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3928 return ReplaceInstUsesWith(I, Op1);
3929 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3930 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3931 return ReplaceInstUsesWith(I, Op0);
3932
Chris Lattner6423d4c2006-07-10 20:25:24 +00003933 // (A | B) | C and A | (B | C) -> bswap if possible.
3934 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003935 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003936 match(Op1, m_Or(m_Value(), m_Value())) ||
3937 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3938 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003939 if (Instruction *BSwap = MatchBSwap(I))
3940 return BSwap;
3941 }
3942
Chris Lattner6e4c6492005-05-09 04:58:36 +00003943 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3944 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003945 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003946 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003947 InsertNewInstBefore(NOr, I);
3948 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003949 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003950 }
3951
3952 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3953 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003954 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003955 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003956 InsertNewInstBefore(NOr, I);
3957 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003958 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003959 }
3960
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003961 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003962 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003963 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3964 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003965 Value *V1 = 0, *V2 = 0, *V3 = 0;
3966 C1 = dyn_cast<ConstantInt>(C);
3967 C2 = dyn_cast<ConstantInt>(D);
3968 if (C1 && C2) { // (A & C1)|(B & C2)
3969 // If we have: ((V + N) & C1) | (V & C2)
3970 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3971 // replace with V+N.
3972 if (C1->getValue() == ~C2->getValue()) {
3973 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3974 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3975 // Add commutes, try both ways.
3976 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3977 return ReplaceInstUsesWith(I, A);
3978 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3979 return ReplaceInstUsesWith(I, A);
3980 }
3981 // Or commutes, try both ways.
3982 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3983 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3984 // Add commutes, try both ways.
3985 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3986 return ReplaceInstUsesWith(I, B);
3987 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3988 return ReplaceInstUsesWith(I, B);
3989 }
3990 }
Chris Lattner044e5332007-04-08 08:01:49 +00003991 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003992 }
3993
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003994 // Check to see if we have any common things being and'ed. If so, find the
3995 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003996 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3997 if (A == B) // (A & C)|(A & D) == A & (C|D)
3998 V1 = A, V2 = C, V3 = D;
3999 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4000 V1 = A, V2 = B, V3 = C;
4001 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4002 V1 = C, V2 = A, V3 = D;
4003 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4004 V1 = C, V2 = A, V3 = B;
4005
4006 if (V1) {
4007 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004008 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4009 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004010 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004011 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004012 }
Chris Lattnere511b742006-11-14 07:46:50 +00004013
4014 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004015 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4016 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4017 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004018 SI0->getOperand(1) == SI1->getOperand(1) &&
4019 (SI0->hasOneUse() || SI1->hasOneUse())) {
4020 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004021 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004022 SI1->getOperand(0),
4023 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004024 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004025 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004026 }
4027 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004028
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004029 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4030 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004031 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004032 } else {
4033 A = 0;
4034 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004035 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004036 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4037 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004038 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004039
Misha Brukmancb6267b2004-07-30 12:50:08 +00004040 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004041 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004042 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004043 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004044 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004045 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004046 }
Chris Lattnera2881962003-02-18 19:28:33 +00004047
Reid Spencere4d87aa2006-12-23 06:05:41 +00004048 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4049 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4050 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004051 return R;
4052
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004053 Value *LHSVal, *RHSVal;
4054 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004055 ICmpInst::Predicate LHSCC, RHSCC;
4056 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4057 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4058 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4059 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4060 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4061 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4062 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004063 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4064 // We can't fold (ugt x, C) | (sgt x, C2).
4065 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004066 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004067 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004068 bool NeedsSwap;
4069 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004070 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004071 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004072 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004073
4074 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004075 std::swap(LHS, RHS);
4076 std::swap(LHSCst, RHSCst);
4077 std::swap(LHSCC, RHSCC);
4078 }
4079
Reid Spencere4d87aa2006-12-23 06:05:41 +00004080 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004081 // comparing a value against two constants and or'ing the result
4082 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004083 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4084 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004085 // equal.
4086 assert(LHSCst != RHSCst && "Compares not folded above?");
4087
4088 switch (LHSCC) {
4089 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004090 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004091 switch (RHSCC) {
4092 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004093 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004094 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4095 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004096 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004097 LHSVal->getName()+".off");
4098 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004099 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004100 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004101 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004102 break; // (X == 13 | X == 15) -> no change
4103 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4104 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004105 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004106 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4107 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4108 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004109 return ReplaceInstUsesWith(I, RHS);
4110 }
4111 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004112 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004113 switch (RHSCC) {
4114 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004115 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4116 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4117 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004118 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004119 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4120 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4121 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004122 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004123 }
4124 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004125 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004126 switch (RHSCC) {
4127 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004128 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004129 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004130 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004131 // If RHSCst is [us]MAXINT, it is always false. Not handling
4132 // this can cause overflow.
4133 if (RHSCst->isMaxValue(false))
4134 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004135 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4136 false, I);
4137 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4138 break;
4139 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4140 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004141 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004142 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4143 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004144 }
4145 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004146 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004147 switch (RHSCC) {
4148 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004149 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4150 break;
4151 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004152 // If RHSCst is [us]MAXINT, it is always false. Not handling
4153 // this can cause overflow.
4154 if (RHSCst->isMaxValue(true))
4155 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004156 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4157 false, I);
4158 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4159 break;
4160 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4161 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4162 return ReplaceInstUsesWith(I, RHS);
4163 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4164 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004165 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004166 break;
4167 case ICmpInst::ICMP_UGT:
4168 switch (RHSCC) {
4169 default: assert(0 && "Unknown integer condition code!");
4170 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4171 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4172 return ReplaceInstUsesWith(I, LHS);
4173 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4174 break;
4175 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4176 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004177 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004178 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4179 break;
4180 }
4181 break;
4182 case ICmpInst::ICMP_SGT:
4183 switch (RHSCC) {
4184 default: assert(0 && "Unknown integer condition code!");
4185 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4186 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4187 return ReplaceInstUsesWith(I, LHS);
4188 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4189 break;
4190 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4191 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004192 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004193 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4194 break;
4195 }
4196 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004197 }
4198 }
4199 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004200
4201 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004202 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004203 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004204 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004205 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4206 !isa<ICmpInst>(Op1C->getOperand(0))) {
4207 const Type *SrcTy = Op0C->getOperand(0)->getType();
4208 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4209 // Only do this if the casts both really cause code to be
4210 // generated.
4211 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4212 I.getType(), TD) &&
4213 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4214 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004215 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004216 Op1C->getOperand(0),
4217 I.getName());
4218 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004219 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004220 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004221 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004222 }
Chris Lattner99c65742007-10-24 05:38:08 +00004223 }
4224
4225
4226 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4227 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4228 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4229 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004230 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4231 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004232 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4233 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4234 // If either of the constants are nans, then the whole thing returns
4235 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004236 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004237 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4238
4239 // Otherwise, no need to compare the two constants, compare the
4240 // rest.
4241 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4242 RHS->getOperand(0));
4243 }
4244 }
4245 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004246
Chris Lattner7e708292002-06-25 16:13:24 +00004247 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004248}
4249
Dan Gohman844731a2008-05-13 00:00:25 +00004250namespace {
4251
Chris Lattnerc317d392004-02-16 01:20:27 +00004252// XorSelf - Implements: X ^ X --> 0
4253struct XorSelf {
4254 Value *RHS;
4255 XorSelf(Value *rhs) : RHS(rhs) {}
4256 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4257 Instruction *apply(BinaryOperator &Xor) const {
4258 return &Xor;
4259 }
4260};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004261
Dan Gohman844731a2008-05-13 00:00:25 +00004262}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004263
Chris Lattner7e708292002-06-25 16:13:24 +00004264Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004265 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004267
Evan Chengd34af782008-03-25 20:07:13 +00004268 if (isa<UndefValue>(Op1)) {
4269 if (isa<UndefValue>(Op0))
4270 // Handle undef ^ undef -> 0 special case. This is a common
4271 // idiom (misuse).
4272 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004273 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004274 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004275
Chris Lattnerc317d392004-02-16 01:20:27 +00004276 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4277 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004278 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004279 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004280 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004281
4282 // See if we can simplify any instructions used by the instruction whose sole
4283 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004284 if (!isa<VectorType>(I.getType())) {
4285 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4286 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4287 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4288 KnownZero, KnownOne))
4289 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004290 } else if (isa<ConstantAggregateZero>(Op1)) {
4291 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004292 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004293
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004294 // Is this a ~ operation?
4295 if (Value *NotOp = dyn_castNotVal(&I)) {
4296 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4297 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4298 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4299 if (Op0I->getOpcode() == Instruction::And ||
4300 Op0I->getOpcode() == Instruction::Or) {
4301 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4302 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4303 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004304 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004305 Op0I->getOperand(1)->getName()+".not");
4306 InsertNewInstBefore(NotY, I);
4307 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004308 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004309 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004310 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004311 }
4312 }
4313 }
4314 }
4315
4316
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004317 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004318 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4319 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4320 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004321 return new ICmpInst(ICI->getInversePredicate(),
4322 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004323
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004324 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4325 return new FCmpInst(FCI->getInversePredicate(),
4326 FCI->getOperand(0), FCI->getOperand(1));
4327 }
4328
Nick Lewycky517e1f52008-05-31 19:01:33 +00004329 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4330 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4331 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4332 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4333 Instruction::CastOps Opcode = Op0C->getOpcode();
4334 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4335 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4336 Op0C->getDestTy())) {
4337 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4338 CI->getOpcode(), CI->getInversePredicate(),
4339 CI->getOperand(0), CI->getOperand(1)), I);
4340 NewCI->takeName(CI);
4341 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4342 }
4343 }
4344 }
4345 }
4346 }
4347
Reid Spencere4d87aa2006-12-23 06:05:41 +00004348 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004349 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004350 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4351 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004352 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4353 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004354 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004355 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004356 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004357
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004358 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004359 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004360 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004361 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004362 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004363 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004364 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004365 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004366 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004367 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004368 // (X + C) ^ signbit -> (X + C + signbit)
4369 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004370 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004371
Chris Lattner7c4049c2004-01-12 19:35:11 +00004372 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004373 } else if (Op0I->getOpcode() == Instruction::Or) {
4374 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004375 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004376 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4377 // Anything in both C1 and C2 is known to be zero, remove it from
4378 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004379 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004380 NewRHS = ConstantExpr::getAnd(NewRHS,
4381 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004382 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004383 I.setOperand(0, Op0I->getOperand(0));
4384 I.setOperand(1, NewRHS);
4385 return &I;
4386 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004387 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004388 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004389 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004390
4391 // Try to fold constant and into select arguments.
4392 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004393 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004394 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004395 if (isa<PHINode>(Op0))
4396 if (Instruction *NV = FoldOpIntoPhi(I))
4397 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004398 }
4399
Chris Lattner8d969642003-03-10 23:06:50 +00004400 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004401 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004402 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004403
Chris Lattner8d969642003-03-10 23:06:50 +00004404 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004405 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004406 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004407
Chris Lattner318bf792007-03-18 22:51:34 +00004408
4409 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4410 if (Op1I) {
4411 Value *A, *B;
4412 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4413 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004414 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004415 I.swapOperands();
4416 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004417 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004418 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004419 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004420 }
Chris Lattner318bf792007-03-18 22:51:34 +00004421 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4422 if (Op0 == A) // A^(A^B) == B
4423 return ReplaceInstUsesWith(I, B);
4424 else if (Op0 == B) // A^(B^A) == B
4425 return ReplaceInstUsesWith(I, A);
4426 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004427 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004428 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004429 std::swap(A, B);
4430 }
Chris Lattner318bf792007-03-18 22:51:34 +00004431 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004432 I.swapOperands(); // Simplified below.
4433 std::swap(Op0, Op1);
4434 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004435 }
Chris Lattner318bf792007-03-18 22:51:34 +00004436 }
4437
4438 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4439 if (Op0I) {
4440 Value *A, *B;
4441 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4442 if (A == Op1) // (B|A)^B == (A|B)^B
4443 std::swap(A, B);
4444 if (B == Op1) { // (A|B)^B == A & ~B
4445 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004446 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4447 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004448 }
Chris Lattner318bf792007-03-18 22:51:34 +00004449 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4450 if (Op1 == A) // (A^B)^A == B
4451 return ReplaceInstUsesWith(I, B);
4452 else if (Op1 == B) // (B^A)^A == B
4453 return ReplaceInstUsesWith(I, A);
4454 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4455 if (A == Op1) // (A&B)^A -> (B&A)^A
4456 std::swap(A, B);
4457 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004458 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004459 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004460 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4461 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004462 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004463 }
Chris Lattner318bf792007-03-18 22:51:34 +00004464 }
4465
4466 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4467 if (Op0I && Op1I && Op0I->isShift() &&
4468 Op0I->getOpcode() == Op1I->getOpcode() &&
4469 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4470 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4471 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004472 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004473 Op1I->getOperand(0),
4474 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004475 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004476 Op1I->getOperand(1));
4477 }
4478
4479 if (Op0I && Op1I) {
4480 Value *A, *B, *C, *D;
4481 // (A & B)^(A | B) -> A ^ B
4482 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4483 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4484 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004485 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004486 }
4487 // (A | B)^(A & B) -> A ^ B
4488 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4489 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4490 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004491 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004492 }
4493
4494 // (A & B)^(C & D)
4495 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4496 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4497 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4498 // (X & Y)^(X & Y) -> (Y^Z) & X
4499 Value *X = 0, *Y = 0, *Z = 0;
4500 if (A == C)
4501 X = A, Y = B, Z = D;
4502 else if (A == D)
4503 X = A, Y = B, Z = C;
4504 else if (B == C)
4505 X = B, Y = A, Z = D;
4506 else if (B == D)
4507 X = B, Y = A, Z = C;
4508
4509 if (X) {
4510 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004511 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4512 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004513 }
4514 }
4515 }
4516
Reid Spencere4d87aa2006-12-23 06:05:41 +00004517 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4518 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4519 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004520 return R;
4521
Chris Lattner6fc205f2006-05-05 06:39:07 +00004522 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004523 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004524 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004525 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4526 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004527 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004528 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004529 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4530 I.getType(), TD) &&
4531 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4532 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004533 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004534 Op1C->getOperand(0),
4535 I.getName());
4536 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004537 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004538 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004539 }
Chris Lattner99c65742007-10-24 05:38:08 +00004540 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004541
Chris Lattner7e708292002-06-25 16:13:24 +00004542 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004543}
4544
Chris Lattnera96879a2004-09-29 17:40:11 +00004545/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4546/// overflowed for this type.
4547static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004548 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004549 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004550
Reid Spencere4e40032007-03-21 23:19:50 +00004551 if (IsSigned)
4552 if (In2->getValue().isNegative())
4553 return Result->getValue().sgt(In1->getValue());
4554 else
4555 return Result->getValue().slt(In1->getValue());
4556 else
4557 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004558}
4559
Chris Lattner574da9b2005-01-13 20:14:25 +00004560/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4561/// code necessary to compute the offset from the base pointer (without adding
4562/// in the base pointer). Return the result as a signed integer of intptr size.
4563static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4564 TargetData &TD = IC.getTargetData();
4565 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004566 const Type *IntPtrTy = TD.getIntPtrType();
4567 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004568
4569 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004570 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004571 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004572
Gabor Greif177dd3f2008-06-12 21:37:33 +00004573 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4574 ++i, ++GTI) {
4575 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004576 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004577 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4578 if (OpC->isZero()) continue;
4579
4580 // Handle a struct index, which adds its field offset to the pointer.
4581 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4582 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4583
4584 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4585 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004586 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004587 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004588 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004589 ConstantInt::get(IntPtrTy, Size),
4590 GEP->getName()+".offs"), I);
4591 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004592 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004593
4594 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4595 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4596 Scale = ConstantExpr::getMul(OC, Scale);
4597 if (Constant *RC = dyn_cast<Constant>(Result))
4598 Result = ConstantExpr::getAdd(RC, Scale);
4599 else {
4600 // Emit an add instruction.
4601 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004602 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004603 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004604 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004605 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004606 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004607 // Convert to correct type.
4608 if (Op->getType() != IntPtrTy) {
4609 if (Constant *OpC = dyn_cast<Constant>(Op))
4610 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4611 else
4612 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4613 Op->getName()+".c"), I);
4614 }
4615 if (Size != 1) {
4616 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4617 if (Constant *OpC = dyn_cast<Constant>(Op))
4618 Op = ConstantExpr::getMul(OpC, Scale);
4619 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004620 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004621 GEP->getName()+".idx"), I);
4622 }
4623
4624 // Emit an add instruction.
4625 if (isa<Constant>(Op) && isa<Constant>(Result))
4626 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4627 cast<Constant>(Result));
4628 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004629 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004630 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004631 }
4632 return Result;
4633}
4634
Chris Lattner10c0d912008-04-22 02:53:33 +00004635
4636/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4637/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4638/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4639/// complex, and scales are involved. The above expression would also be legal
4640/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4641/// later form is less amenable to optimization though, and we are allowed to
4642/// generate the first by knowing that pointer arithmetic doesn't overflow.
4643///
4644/// If we can't emit an optimized form for this expression, this returns null.
4645///
4646static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4647 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004648 TargetData &TD = IC.getTargetData();
4649 gep_type_iterator GTI = gep_type_begin(GEP);
4650
4651 // Check to see if this gep only has a single variable index. If so, and if
4652 // any constant indices are a multiple of its scale, then we can compute this
4653 // in terms of the scale of the variable index. For example, if the GEP
4654 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4655 // because the expression will cross zero at the same point.
4656 unsigned i, e = GEP->getNumOperands();
4657 int64_t Offset = 0;
4658 for (i = 1; i != e; ++i, ++GTI) {
4659 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4660 // Compute the aggregate offset of constant indices.
4661 if (CI->isZero()) continue;
4662
4663 // Handle a struct index, which adds its field offset to the pointer.
4664 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4665 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4666 } else {
4667 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4668 Offset += Size*CI->getSExtValue();
4669 }
4670 } else {
4671 // Found our variable index.
4672 break;
4673 }
4674 }
4675
4676 // If there are no variable indices, we must have a constant offset, just
4677 // evaluate it the general way.
4678 if (i == e) return 0;
4679
4680 Value *VariableIdx = GEP->getOperand(i);
4681 // Determine the scale factor of the variable element. For example, this is
4682 // 4 if the variable index is into an array of i32.
4683 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4684
4685 // Verify that there are no other variable indices. If so, emit the hard way.
4686 for (++i, ++GTI; i != e; ++i, ++GTI) {
4687 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4688 if (!CI) return 0;
4689
4690 // Compute the aggregate offset of constant indices.
4691 if (CI->isZero()) continue;
4692
4693 // Handle a struct index, which adds its field offset to the pointer.
4694 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4695 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4696 } else {
4697 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4698 Offset += Size*CI->getSExtValue();
4699 }
4700 }
4701
4702 // Okay, we know we have a single variable index, which must be a
4703 // pointer/array/vector index. If there is no offset, life is simple, return
4704 // the index.
4705 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4706 if (Offset == 0) {
4707 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4708 // we don't need to bother extending: the extension won't affect where the
4709 // computation crosses zero.
4710 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4711 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4712 VariableIdx->getNameStart(), &I);
4713 return VariableIdx;
4714 }
4715
4716 // Otherwise, there is an index. The computation we will do will be modulo
4717 // the pointer size, so get it.
4718 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4719
4720 Offset &= PtrSizeMask;
4721 VariableScale &= PtrSizeMask;
4722
4723 // To do this transformation, any constant index must be a multiple of the
4724 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4725 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4726 // multiple of the variable scale.
4727 int64_t NewOffs = Offset / (int64_t)VariableScale;
4728 if (Offset != NewOffs*(int64_t)VariableScale)
4729 return 0;
4730
4731 // Okay, we can do this evaluation. Start by converting the index to intptr.
4732 const Type *IntPtrTy = TD.getIntPtrType();
4733 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004734 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004735 true /*SExt*/,
4736 VariableIdx->getNameStart(), &I);
4737 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004738 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004739}
4740
4741
Reid Spencere4d87aa2006-12-23 06:05:41 +00004742/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004743/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004744Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4745 ICmpInst::Predicate Cond,
4746 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004747 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004748
Chris Lattner10c0d912008-04-22 02:53:33 +00004749 // Look through bitcasts.
4750 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4751 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004752
Chris Lattner574da9b2005-01-13 20:14:25 +00004753 Value *PtrBase = GEPLHS->getOperand(0);
4754 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004755 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004756 // This transformation (ignoring the base and scales) is valid because we
4757 // know pointers can't overflow. See if we can output an optimized form.
4758 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4759
4760 // If not, synthesize the offset the hard way.
4761 if (Offset == 0)
4762 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004763 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4764 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004765 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004766 // If the base pointers are different, but the indices are the same, just
4767 // compare the base pointer.
4768 if (PtrBase != GEPRHS->getOperand(0)) {
4769 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004770 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004771 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004772 if (IndicesTheSame)
4773 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4774 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4775 IndicesTheSame = false;
4776 break;
4777 }
4778
4779 // If all indices are the same, just compare the base pointers.
4780 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004781 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4782 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004783
4784 // Otherwise, the base pointers are different and the indices are
4785 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004786 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004787 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004788
Chris Lattnere9d782b2005-01-13 22:25:21 +00004789 // If one of the GEPs has all zero indices, recurse.
4790 bool AllZeros = true;
4791 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4792 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4793 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4794 AllZeros = false;
4795 break;
4796 }
4797 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004798 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4799 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004800
4801 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004802 AllZeros = true;
4803 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4804 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4805 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4806 AllZeros = false;
4807 break;
4808 }
4809 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004810 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004811
Chris Lattner4401c9c2005-01-14 00:20:05 +00004812 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4813 // If the GEPs only differ by one index, compare it.
4814 unsigned NumDifferences = 0; // Keep track of # differences.
4815 unsigned DiffOperand = 0; // The operand that differs.
4816 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4817 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004818 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4819 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004820 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004821 NumDifferences = 2;
4822 break;
4823 } else {
4824 if (NumDifferences++) break;
4825 DiffOperand = i;
4826 }
4827 }
4828
4829 if (NumDifferences == 0) // SAME GEP?
4830 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004831 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004832 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004833
Chris Lattner4401c9c2005-01-14 00:20:05 +00004834 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004835 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4836 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004837 // Make sure we do a signed comparison here.
4838 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004839 }
4840 }
4841
Reid Spencere4d87aa2006-12-23 06:05:41 +00004842 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004843 // the result to fold to a constant!
4844 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4845 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4846 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4847 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4848 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004849 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004850 }
4851 }
4852 return 0;
4853}
4854
Chris Lattnera5406232008-05-19 20:18:56 +00004855/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4856///
4857Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4858 Instruction *LHSI,
4859 Constant *RHSC) {
4860 if (!isa<ConstantFP>(RHSC)) return 0;
4861 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4862
4863 // Get the width of the mantissa. We don't want to hack on conversions that
4864 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004865 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004866 if (MantissaWidth == -1) return 0; // Unknown.
4867
4868 // Check to see that the input is converted from an integer type that is small
4869 // enough that preserves all bits. TODO: check here for "known" sign bits.
4870 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4871 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4872
4873 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4874 if (isa<UIToFPInst>(LHSI))
4875 ++InputSize;
4876
4877 // If the conversion would lose info, don't hack on this.
4878 if ((int)InputSize > MantissaWidth)
4879 return 0;
4880
4881 // Otherwise, we can potentially simplify the comparison. We know that it
4882 // will always come through as an integer value and we know the constant is
4883 // not a NAN (it would have been previously simplified).
4884 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4885
4886 ICmpInst::Predicate Pred;
4887 switch (I.getPredicate()) {
4888 default: assert(0 && "Unexpected predicate!");
4889 case FCmpInst::FCMP_UEQ:
4890 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4891 case FCmpInst::FCMP_UGT:
4892 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4893 case FCmpInst::FCMP_UGE:
4894 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4895 case FCmpInst::FCMP_ULT:
4896 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4897 case FCmpInst::FCMP_ULE:
4898 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4899 case FCmpInst::FCMP_UNE:
4900 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4901 case FCmpInst::FCMP_ORD:
4902 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4903 case FCmpInst::FCMP_UNO:
4904 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4905 }
4906
4907 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4908
4909 // Now we know that the APFloat is a normal number, zero or inf.
4910
Chris Lattner85162782008-05-20 03:50:52 +00004911 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004912 // comparing an i8 to 300.0.
4913 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4914
4915 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4916 // and large values.
4917 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4918 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4919 APFloat::rmNearestTiesToEven);
4920 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004921 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4922 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004923 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4924 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4925 }
4926
4927 // See if the RHS value is < SignedMin.
4928 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4929 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4930 APFloat::rmNearestTiesToEven);
4931 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004932 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4933 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00004934 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4935 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4936 }
4937
4938 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4939 // it may still be fractional. See if it is fractional by casting the FP
4940 // value to the integer value and back, checking for equality. Don't do this
4941 // for zero, because -0.0 is not fractional.
4942 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4943 if (!RHS.isZero() &&
4944 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4945 // If we had a comparison against a fractional value, we have to adjust
4946 // the compare predicate and sometimes the value. RHSC is rounded towards
4947 // zero at this point.
4948 switch (Pred) {
4949 default: assert(0 && "Unexpected integer comparison!");
4950 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4951 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4952 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4953 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4954 case ICmpInst::ICMP_SLE:
4955 // (float)int <= 4.4 --> int <= 4
4956 // (float)int <= -4.4 --> int < -4
4957 if (RHS.isNegative())
4958 Pred = ICmpInst::ICMP_SLT;
4959 break;
4960 case ICmpInst::ICMP_SLT:
4961 // (float)int < -4.4 --> int < -4
4962 // (float)int < 4.4 --> int <= 4
4963 if (!RHS.isNegative())
4964 Pred = ICmpInst::ICMP_SLE;
4965 break;
4966 case ICmpInst::ICMP_SGT:
4967 // (float)int > 4.4 --> int > 4
4968 // (float)int > -4.4 --> int >= -4
4969 if (RHS.isNegative())
4970 Pred = ICmpInst::ICMP_SGE;
4971 break;
4972 case ICmpInst::ICMP_SGE:
4973 // (float)int >= -4.4 --> int >= -4
4974 // (float)int >= 4.4 --> int > 4
4975 if (!RHS.isNegative())
4976 Pred = ICmpInst::ICMP_SGT;
4977 break;
4978 }
4979 }
4980
4981 // Lower this FP comparison into an appropriate integer version of the
4982 // comparison.
4983 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4984}
4985
Reid Spencere4d87aa2006-12-23 06:05:41 +00004986Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4987 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004988 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004989
Chris Lattner58e97462007-01-14 19:42:17 +00004990 // Fold trivial predicates.
4991 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4992 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4993 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4994 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4995
4996 // Simplify 'fcmp pred X, X'
4997 if (Op0 == Op1) {
4998 switch (I.getPredicate()) {
4999 default: assert(0 && "Unknown predicate!");
5000 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5001 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5002 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5003 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5004 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5005 case FCmpInst::FCMP_OLT: // True if ordered and less than
5006 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5007 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5008
5009 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5010 case FCmpInst::FCMP_ULT: // True if unordered or less than
5011 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5012 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5013 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5014 I.setPredicate(FCmpInst::FCMP_UNO);
5015 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5016 return &I;
5017
5018 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5019 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5020 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5021 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5022 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5023 I.setPredicate(FCmpInst::FCMP_ORD);
5024 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5025 return &I;
5026 }
5027 }
5028
Reid Spencere4d87aa2006-12-23 06:05:41 +00005029 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005030 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005031
Reid Spencere4d87aa2006-12-23 06:05:41 +00005032 // Handle fcmp with constant RHS
5033 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005034 // If the constant is a nan, see if we can fold the comparison based on it.
5035 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5036 if (CFP->getValueAPF().isNaN()) {
5037 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5038 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005039 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5040 "Comparison must be either ordered or unordered!");
5041 // True if unordered.
5042 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005043 }
5044 }
5045
Reid Spencere4d87aa2006-12-23 06:05:41 +00005046 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5047 switch (LHSI->getOpcode()) {
5048 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005049 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5050 // block. If in the same block, we're encouraging jump threading. If
5051 // not, we are just pessimizing the code by making an i1 phi.
5052 if (LHSI->getParent() == I.getParent())
5053 if (Instruction *NV = FoldOpIntoPhi(I))
5054 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005055 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005056 case Instruction::SIToFP:
5057 case Instruction::UIToFP:
5058 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5059 return NV;
5060 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005061 case Instruction::Select:
5062 // If either operand of the select is a constant, we can fold the
5063 // comparison into the select arms, which will cause one to be
5064 // constant folded and the select turned into a bitwise or.
5065 Value *Op1 = 0, *Op2 = 0;
5066 if (LHSI->hasOneUse()) {
5067 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5068 // Fold the known value into the constant operand.
5069 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5070 // Insert a new FCmp of the other select operand.
5071 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5072 LHSI->getOperand(2), RHSC,
5073 I.getName()), I);
5074 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5075 // Fold the known value into the constant operand.
5076 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5077 // Insert a new FCmp of the other select operand.
5078 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5079 LHSI->getOperand(1), RHSC,
5080 I.getName()), I);
5081 }
5082 }
5083
5084 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005085 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005086 break;
5087 }
5088 }
5089
5090 return Changed ? &I : 0;
5091}
5092
5093Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5094 bool Changed = SimplifyCompare(I);
5095 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5096 const Type *Ty = Op0->getType();
5097
5098 // icmp X, X
5099 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005100 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005101 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005102
5103 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005104 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005105
Reid Spencere4d87aa2006-12-23 06:05:41 +00005106 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005107 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005108 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5109 isa<ConstantPointerNull>(Op0)) &&
5110 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005111 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005112 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005113 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005114
Reid Spencere4d87aa2006-12-23 06:05:41 +00005115 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005116 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117 switch (I.getPredicate()) {
5118 default: assert(0 && "Invalid icmp instruction!");
5119 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005120 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005121 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005122 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005123 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005124 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005125 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005126
Reid Spencere4d87aa2006-12-23 06:05:41 +00005127 case ICmpInst::ICMP_UGT:
5128 case ICmpInst::ICMP_SGT:
5129 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005130 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005131 case ICmpInst::ICMP_ULT:
5132 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005134 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005135 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005136 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005137 case ICmpInst::ICMP_UGE:
5138 case ICmpInst::ICMP_SGE:
5139 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005140 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005141 case ICmpInst::ICMP_ULE:
5142 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005143 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005144 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005145 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005146 }
5147 }
Chris Lattner8b170942002-08-09 23:47:40 +00005148 }
5149
Chris Lattner2be51ae2004-06-09 04:24:29 +00005150 // See if we are doing a comparison between a constant and an instruction that
5151 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005152 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005153 Value *A, *B;
5154
Chris Lattnerb6566012008-01-05 01:18:20 +00005155 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5156 if (I.isEquality() && CI->isNullValue() &&
5157 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5158 // (icmp cond A B) if cond is equality
5159 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005160 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005161
Reid Spencere4d87aa2006-12-23 06:05:41 +00005162 switch (I.getPredicate()) {
5163 default: break;
5164 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5165 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005166 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005167 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5168 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5169 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5170 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005171 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5172 if (CI->isMinValue(true))
5173 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5174 ConstantInt::getAllOnesValue(Op0->getType()));
5175
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005177
Reid Spencere4d87aa2006-12-23 06:05:41 +00005178 case ICmpInst::ICMP_SLT:
5179 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005180 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5182 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5183 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5184 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5185 break;
5186
5187 case ICmpInst::ICMP_UGT:
5188 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005189 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005190 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5191 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5192 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5193 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005194
5195 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5196 if (CI->isMaxValue(true))
5197 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5198 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005199 break;
5200
5201 case ICmpInst::ICMP_SGT:
5202 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005203 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005204 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5205 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5206 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5207 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5208 break;
5209
5210 case ICmpInst::ICMP_ULE:
5211 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005212 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5214 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5215 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5216 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5217 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005218
Reid Spencere4d87aa2006-12-23 06:05:41 +00005219 case ICmpInst::ICMP_SLE:
5220 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005221 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005222 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5223 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5224 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5225 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5226 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005227
Reid Spencere4d87aa2006-12-23 06:05:41 +00005228 case ICmpInst::ICMP_UGE:
5229 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005230 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005231 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5232 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5233 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5234 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5235 break;
5236
5237 case ICmpInst::ICMP_SGE:
5238 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005239 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005240 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5241 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5242 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5243 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5244 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005245 }
5246
Reid Spencere4d87aa2006-12-23 06:05:41 +00005247 // If we still have a icmp le or icmp ge instruction, turn it into the
5248 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005249 // already been handled above, this requires little checking.
5250 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005251 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005252 default: break;
5253 case ICmpInst::ICMP_ULE:
5254 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5255 case ICmpInst::ICMP_SLE:
5256 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5257 case ICmpInst::ICMP_UGE:
5258 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5259 case ICmpInst::ICMP_SGE:
5260 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005261 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005262
5263 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005264 // in the input. If this comparison is a normal comparison, it demands all
5265 // bits, if it is a sign bit comparison, it only demands the sign bit.
5266
5267 bool UnusedBit;
5268 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5269
Reid Spencer0460fb32007-03-22 20:36:03 +00005270 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5271 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005272 if (SimplifyDemandedBits(Op0,
5273 isSignBit ? APInt::getSignBit(BitWidth)
5274 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005275 KnownZero, KnownOne, 0))
5276 return &I;
5277
5278 // Given the known and unknown bits, compute a range that the LHS could be
5279 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005280 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005281 // Compute the Min, Max and RHS values based on the known bits. For the
5282 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005283 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5284 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005285 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005286 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5287 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005288 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005289 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5290 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005291 }
5292 switch (I.getPredicate()) { // LE/GE have been folded already.
5293 default: assert(0 && "Unknown icmp opcode!");
5294 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005295 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005296 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005297 break;
5298 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005299 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005300 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005301 break;
5302 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005303 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005304 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005305 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005306 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005307 break;
5308 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005309 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005310 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005311 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005312 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005313 break;
5314 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005315 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005316 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005317 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005318 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005319 break;
5320 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005321 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005322 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005323 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005324 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005325 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005326 }
5327 }
5328
Reid Spencere4d87aa2006-12-23 06:05:41 +00005329 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005330 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005331 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005332 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005333 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5334 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005335 }
5336
Chris Lattner01deb9d2007-04-03 17:43:25 +00005337 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005338 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5339 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5340 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005341 case Instruction::GetElementPtr:
5342 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005343 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005344 bool isAllZeros = true;
5345 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5346 if (!isa<Constant>(LHSI->getOperand(i)) ||
5347 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5348 isAllZeros = false;
5349 break;
5350 }
5351 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005352 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005353 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5354 }
5355 break;
5356
Chris Lattner6970b662005-04-23 15:31:55 +00005357 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005358 // Only fold icmp into the PHI if the phi and fcmp are in the same
5359 // block. If in the same block, we're encouraging jump threading. If
5360 // not, we are just pessimizing the code by making an i1 phi.
5361 if (LHSI->getParent() == I.getParent())
5362 if (Instruction *NV = FoldOpIntoPhi(I))
5363 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005364 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005365 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005366 // If either operand of the select is a constant, we can fold the
5367 // comparison into the select arms, which will cause one to be
5368 // constant folded and the select turned into a bitwise or.
5369 Value *Op1 = 0, *Op2 = 0;
5370 if (LHSI->hasOneUse()) {
5371 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5372 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005373 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5374 // Insert a new ICmp of the other select operand.
5375 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5376 LHSI->getOperand(2), RHSC,
5377 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005378 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5379 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005380 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5381 // Insert a new ICmp of the other select operand.
5382 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5383 LHSI->getOperand(1), RHSC,
5384 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005385 }
5386 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005387
Chris Lattner6970b662005-04-23 15:31:55 +00005388 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005389 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005390 break;
5391 }
Chris Lattner4802d902007-04-06 18:57:34 +00005392 case Instruction::Malloc:
5393 // If we have (malloc != null), and if the malloc has a single use, we
5394 // can assume it is successful and remove the malloc.
5395 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5396 AddToWorkList(LHSI);
5397 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005398 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005399 }
5400 break;
5401 }
Chris Lattner6970b662005-04-23 15:31:55 +00005402 }
5403
Reid Spencere4d87aa2006-12-23 06:05:41 +00005404 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005405 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005406 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005407 return NI;
5408 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005409 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5410 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005411 return NI;
5412
Reid Spencere4d87aa2006-12-23 06:05:41 +00005413 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005414 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5415 // now.
5416 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5417 if (isa<PointerType>(Op0->getType()) &&
5418 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005419 // We keep moving the cast from the left operand over to the right
5420 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005421 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005422
Chris Lattner57d86372007-01-06 01:45:59 +00005423 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5424 // so eliminate it as well.
5425 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5426 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005427
Chris Lattnerde90b762003-11-03 04:25:02 +00005428 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005429 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005430 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005431 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005432 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005433 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005434 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005435 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005436 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005437 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005438 }
Chris Lattner57d86372007-01-06 01:45:59 +00005439 }
5440
5441 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005442 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005443 // This comes up when you have code like
5444 // int X = A < B;
5445 // if (X) ...
5446 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005447 // with a constant or another cast from the same type.
5448 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005449 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005450 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005451 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005452
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005453 // ~x < ~y --> y < x
5454 { Value *A, *B;
5455 if (match(Op0, m_Not(m_Value(A))) &&
5456 match(Op1, m_Not(m_Value(B))))
5457 return new ICmpInst(I.getPredicate(), B, A);
5458 }
5459
Chris Lattner65b72ba2006-09-18 04:22:48 +00005460 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005461 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005462
5463 // -x == -y --> x == y
5464 if (match(Op0, m_Neg(m_Value(A))) &&
5465 match(Op1, m_Neg(m_Value(B))))
5466 return new ICmpInst(I.getPredicate(), A, B);
5467
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005468 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5469 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5470 Value *OtherVal = A == Op1 ? B : A;
5471 return new ICmpInst(I.getPredicate(), OtherVal,
5472 Constant::getNullValue(A->getType()));
5473 }
5474
5475 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5476 // A^c1 == C^c2 --> A == C^(c1^c2)
5477 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5478 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5479 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005480 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005481 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005482 return new ICmpInst(I.getPredicate(), A,
5483 InsertNewInstBefore(Xor, I));
5484 }
5485
5486 // A^B == A^D -> B == D
5487 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5488 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5489 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5490 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5491 }
5492 }
5493
5494 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5495 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005496 // A == (A^B) -> B == 0
5497 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005498 return new ICmpInst(I.getPredicate(), OtherVal,
5499 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005500 }
5501 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005502 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005503 return new ICmpInst(I.getPredicate(), B,
5504 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005505 }
5506 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005507 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005508 return new ICmpInst(I.getPredicate(), B,
5509 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005510 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005511
Chris Lattner9c2328e2006-11-14 06:06:06 +00005512 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5513 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5514 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5515 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5516 Value *X = 0, *Y = 0, *Z = 0;
5517
5518 if (A == C) {
5519 X = B; Y = D; Z = A;
5520 } else if (A == D) {
5521 X = B; Y = C; Z = A;
5522 } else if (B == C) {
5523 X = A; Y = D; Z = B;
5524 } else if (B == D) {
5525 X = A; Y = C; Z = B;
5526 }
5527
5528 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005529 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5530 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005531 I.setOperand(0, Op1);
5532 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5533 return &I;
5534 }
5535 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005536 }
Chris Lattner7e708292002-06-25 16:13:24 +00005537 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005538}
5539
Chris Lattner562ef782007-06-20 23:46:26 +00005540
5541/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5542/// and CmpRHS are both known to be integer constants.
5543Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5544 ConstantInt *DivRHS) {
5545 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5546 const APInt &CmpRHSV = CmpRHS->getValue();
5547
5548 // FIXME: If the operand types don't match the type of the divide
5549 // then don't attempt this transform. The code below doesn't have the
5550 // logic to deal with a signed divide and an unsigned compare (and
5551 // vice versa). This is because (x /s C1) <s C2 produces different
5552 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5553 // (x /u C1) <u C2. Simply casting the operands and result won't
5554 // work. :( The if statement below tests that condition and bails
5555 // if it finds it.
5556 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5557 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5558 return 0;
5559 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005560 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005561
5562 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5563 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5564 // C2 (CI). By solving for X we can turn this into a range check
5565 // instead of computing a divide.
5566 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5567
5568 // Determine if the product overflows by seeing if the product is
5569 // not equal to the divide. Make sure we do the same kind of divide
5570 // as in the LHS instruction that we're folding.
5571 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5572 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5573
5574 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005575 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005576
Chris Lattner1dbfd482007-06-21 18:11:19 +00005577 // Figure out the interval that is being checked. For example, a comparison
5578 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5579 // Compute this interval based on the constants involved and the signedness of
5580 // the compare/divide. This computes a half-open interval, keeping track of
5581 // whether either value in the interval overflows. After analysis each
5582 // overflow variable is set to 0 if it's corresponding bound variable is valid
5583 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5584 int LoOverflow = 0, HiOverflow = 0;
5585 ConstantInt *LoBound = 0, *HiBound = 0;
5586
5587
Chris Lattner562ef782007-06-20 23:46:26 +00005588 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005589 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005590 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005591 HiOverflow = LoOverflow = ProdOV;
5592 if (!HiOverflow)
5593 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005594 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005595 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005596 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005597 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5598 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005599 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005600 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5601 HiOverflow = LoOverflow = ProdOV;
5602 if (!HiOverflow)
5603 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005604 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005605 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005606 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5607 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005608 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005609 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005610 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005611 }
Dan Gohman76491272008-02-13 22:09:18 +00005612 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005613 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005614 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005615 LoBound = AddOne(DivRHS);
5616 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005617 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5618 HiOverflow = 1; // [INTMIN+1, overflow)
5619 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5620 }
Dan Gohman76491272008-02-13 22:09:18 +00005621 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005622 // e.g. X/-5 op 3 --> [-19, -14)
5623 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005624 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005625 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005626 HiBound = AddOne(Prod);
5627 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005628 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005629 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005630 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005631 HiBound = Subtract(Prod, DivRHS);
5632 }
5633
Chris Lattner1dbfd482007-06-21 18:11:19 +00005634 // Dividing by a negative swaps the condition. LT <-> GT
5635 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005636 }
5637
5638 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005639 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005640 default: assert(0 && "Unhandled icmp opcode!");
5641 case ICmpInst::ICMP_EQ:
5642 if (LoOverflow && HiOverflow)
5643 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5644 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005645 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005646 ICmpInst::ICMP_UGE, X, LoBound);
5647 else if (LoOverflow)
5648 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5649 ICmpInst::ICMP_ULT, X, HiBound);
5650 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005651 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005652 case ICmpInst::ICMP_NE:
5653 if (LoOverflow && HiOverflow)
5654 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5655 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005656 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005657 ICmpInst::ICMP_ULT, X, LoBound);
5658 else if (LoOverflow)
5659 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5660 ICmpInst::ICMP_UGE, X, HiBound);
5661 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005662 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005663 case ICmpInst::ICMP_ULT:
5664 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005665 if (LoOverflow == +1) // Low bound is greater than input range.
5666 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5667 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005668 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005669 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005670 case ICmpInst::ICMP_UGT:
5671 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005672 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005673 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005674 else if (HiOverflow == -1) // High bound less than input range.
5675 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5676 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005677 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5678 else
5679 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5680 }
5681}
5682
5683
Chris Lattner01deb9d2007-04-03 17:43:25 +00005684/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5685///
5686Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5687 Instruction *LHSI,
5688 ConstantInt *RHS) {
5689 const APInt &RHSV = RHS->getValue();
5690
5691 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005692 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005693 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5694 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5695 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005696 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5697 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005698 Value *CompareVal = LHSI->getOperand(0);
5699
5700 // If the sign bit of the XorCST is not set, there is no change to
5701 // the operation, just stop using the Xor.
5702 if (!XorCST->getValue().isNegative()) {
5703 ICI.setOperand(0, CompareVal);
5704 AddToWorkList(LHSI);
5705 return &ICI;
5706 }
5707
5708 // Was the old condition true if the operand is positive?
5709 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5710
5711 // If so, the new one isn't.
5712 isTrueIfPositive ^= true;
5713
5714 if (isTrueIfPositive)
5715 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5716 else
5717 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5718 }
5719 }
5720 break;
5721 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5722 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5723 LHSI->getOperand(0)->hasOneUse()) {
5724 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5725
5726 // If the LHS is an AND of a truncating cast, we can widen the
5727 // and/compare to be the input width without changing the value
5728 // produced, eliminating a cast.
5729 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5730 // We can do this transformation if either the AND constant does not
5731 // have its sign bit set or if it is an equality comparison.
5732 // Extending a relational comparison when we're checking the sign
5733 // bit would not work.
5734 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005735 (ICI.isEquality() ||
5736 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005737 uint32_t BitWidth =
5738 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5739 APInt NewCST = AndCST->getValue();
5740 NewCST.zext(BitWidth);
5741 APInt NewCI = RHSV;
5742 NewCI.zext(BitWidth);
5743 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005744 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005745 ConstantInt::get(NewCST),LHSI->getName());
5746 InsertNewInstBefore(NewAnd, ICI);
5747 return new ICmpInst(ICI.getPredicate(), NewAnd,
5748 ConstantInt::get(NewCI));
5749 }
5750 }
5751
5752 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5753 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5754 // happens a LOT in code produced by the C front-end, for bitfield
5755 // access.
5756 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5757 if (Shift && !Shift->isShift())
5758 Shift = 0;
5759
5760 ConstantInt *ShAmt;
5761 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5762 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5763 const Type *AndTy = AndCST->getType(); // Type of the and.
5764
5765 // We can fold this as long as we can't shift unknown bits
5766 // into the mask. This can only happen with signed shift
5767 // rights, as they sign-extend.
5768 if (ShAmt) {
5769 bool CanFold = Shift->isLogicalShift();
5770 if (!CanFold) {
5771 // To test for the bad case of the signed shr, see if any
5772 // of the bits shifted in could be tested after the mask.
5773 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5774 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5775
5776 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5777 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5778 AndCST->getValue()) == 0)
5779 CanFold = true;
5780 }
5781
5782 if (CanFold) {
5783 Constant *NewCst;
5784 if (Shift->getOpcode() == Instruction::Shl)
5785 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5786 else
5787 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5788
5789 // Check to see if we are shifting out any of the bits being
5790 // compared.
5791 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5792 // If we shifted bits out, the fold is not going to work out.
5793 // As a special case, check to see if this means that the
5794 // result is always true or false now.
5795 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5796 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5797 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5798 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5799 } else {
5800 ICI.setOperand(1, NewCst);
5801 Constant *NewAndCST;
5802 if (Shift->getOpcode() == Instruction::Shl)
5803 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5804 else
5805 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5806 LHSI->setOperand(1, NewAndCST);
5807 LHSI->setOperand(0, Shift->getOperand(0));
5808 AddToWorkList(Shift); // Shift is dead.
5809 AddUsesToWorkList(ICI);
5810 return &ICI;
5811 }
5812 }
5813 }
5814
5815 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5816 // preferable because it allows the C<<Y expression to be hoisted out
5817 // of a loop if Y is invariant and X is not.
5818 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5819 ICI.isEquality() && !Shift->isArithmeticShift() &&
5820 isa<Instruction>(Shift->getOperand(0))) {
5821 // Compute C << Y.
5822 Value *NS;
5823 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005824 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005825 Shift->getOperand(1), "tmp");
5826 } else {
5827 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005828 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005829 Shift->getOperand(1), "tmp");
5830 }
5831 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5832
5833 // Compute X & (C << Y).
5834 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005835 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005836 InsertNewInstBefore(NewAnd, ICI);
5837
5838 ICI.setOperand(0, NewAnd);
5839 return &ICI;
5840 }
5841 }
5842 break;
5843
Chris Lattnera0141b92007-07-15 20:42:37 +00005844 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5845 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5846 if (!ShAmt) break;
5847
5848 uint32_t TypeBits = RHSV.getBitWidth();
5849
5850 // Check that the shift amount is in range. If not, don't perform
5851 // undefined shifts. When the shift is visited it will be
5852 // simplified.
5853 if (ShAmt->uge(TypeBits))
5854 break;
5855
5856 if (ICI.isEquality()) {
5857 // If we are comparing against bits always shifted out, the
5858 // comparison cannot succeed.
5859 Constant *Comp =
5860 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5861 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5862 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5863 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5864 return ReplaceInstUsesWith(ICI, Cst);
5865 }
5866
5867 if (LHSI->hasOneUse()) {
5868 // Otherwise strength reduce the shift into an and.
5869 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5870 Constant *Mask =
5871 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005872
Chris Lattnera0141b92007-07-15 20:42:37 +00005873 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005874 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005875 Mask, LHSI->getName()+".mask");
5876 Value *And = InsertNewInstBefore(AndI, ICI);
5877 return new ICmpInst(ICI.getPredicate(), And,
5878 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005879 }
5880 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005881
5882 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5883 bool TrueIfSigned = false;
5884 if (LHSI->hasOneUse() &&
5885 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5886 // (X << 31) <s 0 --> (X&1) != 0
5887 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5888 (TypeBits-ShAmt->getZExtValue()-1));
5889 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005890 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005891 Mask, LHSI->getName()+".mask");
5892 Value *And = InsertNewInstBefore(AndI, ICI);
5893
5894 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5895 And, Constant::getNullValue(And->getType()));
5896 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005897 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005898 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005899
5900 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005901 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005902 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005903 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005904 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005905
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005906 // Check that the shift amount is in range. If not, don't perform
5907 // undefined shifts. When the shift is visited it will be
5908 // simplified.
5909 uint32_t TypeBits = RHSV.getBitWidth();
5910 if (ShAmt->uge(TypeBits))
5911 break;
5912
5913 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005914
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005915 // If we are comparing against bits always shifted out, the
5916 // comparison cannot succeed.
5917 APInt Comp = RHSV << ShAmtVal;
5918 if (LHSI->getOpcode() == Instruction::LShr)
5919 Comp = Comp.lshr(ShAmtVal);
5920 else
5921 Comp = Comp.ashr(ShAmtVal);
5922
5923 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5924 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5925 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5926 return ReplaceInstUsesWith(ICI, Cst);
5927 }
5928
5929 // Otherwise, check to see if the bits shifted out are known to be zero.
5930 // If so, we can compare against the unshifted value:
5931 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00005932 if (LHSI->hasOneUse() &&
5933 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005934 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5935 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5936 ConstantExpr::getShl(RHS, ShAmt));
5937 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005938
Evan Chengf30752c2008-04-23 00:38:06 +00005939 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005940 // Otherwise strength reduce the shift into an and.
5941 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5942 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005943
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005944 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005945 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005946 Mask, LHSI->getName()+".mask");
5947 Value *And = InsertNewInstBefore(AndI, ICI);
5948 return new ICmpInst(ICI.getPredicate(), And,
5949 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005950 }
5951 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005952 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005953
5954 case Instruction::SDiv:
5955 case Instruction::UDiv:
5956 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5957 // Fold this div into the comparison, producing a range check.
5958 // Determine, based on the divide type, what the range is being
5959 // checked. If there is an overflow on the low or high side, remember
5960 // it, otherwise compute the range [low, hi) bounding the new value.
5961 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005962 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5963 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5964 DivRHS))
5965 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005966 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005967
5968 case Instruction::Add:
5969 // Fold: icmp pred (add, X, C1), C2
5970
5971 if (!ICI.isEquality()) {
5972 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5973 if (!LHSC) break;
5974 const APInt &LHSV = LHSC->getValue();
5975
5976 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5977 .subtract(LHSV);
5978
5979 if (ICI.isSignedPredicate()) {
5980 if (CR.getLower().isSignBit()) {
5981 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5982 ConstantInt::get(CR.getUpper()));
5983 } else if (CR.getUpper().isSignBit()) {
5984 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5985 ConstantInt::get(CR.getLower()));
5986 }
5987 } else {
5988 if (CR.getLower().isMinValue()) {
5989 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5990 ConstantInt::get(CR.getUpper()));
5991 } else if (CR.getUpper().isMinValue()) {
5992 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5993 ConstantInt::get(CR.getLower()));
5994 }
5995 }
5996 }
5997 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005998 }
5999
6000 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6001 if (ICI.isEquality()) {
6002 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6003
6004 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6005 // the second operand is a constant, simplify a bit.
6006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6007 switch (BO->getOpcode()) {
6008 case Instruction::SRem:
6009 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6010 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6011 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6012 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6013 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006014 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006015 BO->getName());
6016 InsertNewInstBefore(NewRem, ICI);
6017 return new ICmpInst(ICI.getPredicate(), NewRem,
6018 Constant::getNullValue(BO->getType()));
6019 }
6020 }
6021 break;
6022 case Instruction::Add:
6023 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6024 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6025 if (BO->hasOneUse())
6026 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6027 Subtract(RHS, BOp1C));
6028 } else if (RHSV == 0) {
6029 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6030 // efficiently invertible, or if the add has just this one use.
6031 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6032
6033 if (Value *NegVal = dyn_castNegVal(BOp1))
6034 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6035 else if (Value *NegVal = dyn_castNegVal(BOp0))
6036 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6037 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006038 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006039 InsertNewInstBefore(Neg, ICI);
6040 Neg->takeName(BO);
6041 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6042 }
6043 }
6044 break;
6045 case Instruction::Xor:
6046 // For the xor case, we can xor two constants together, eliminating
6047 // the explicit xor.
6048 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6049 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6050 ConstantExpr::getXor(RHS, BOC));
6051
6052 // FALLTHROUGH
6053 case Instruction::Sub:
6054 // Replace (([sub|xor] A, B) != 0) with (A != B)
6055 if (RHSV == 0)
6056 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6057 BO->getOperand(1));
6058 break;
6059
6060 case Instruction::Or:
6061 // If bits are being or'd in that are not present in the constant we
6062 // are comparing against, then the comparison could never succeed!
6063 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6064 Constant *NotCI = ConstantExpr::getNot(RHS);
6065 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6066 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6067 isICMP_NE));
6068 }
6069 break;
6070
6071 case Instruction::And:
6072 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6073 // If bits are being compared against that are and'd out, then the
6074 // comparison can never succeed!
6075 if ((RHSV & ~BOC->getValue()) != 0)
6076 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6077 isICMP_NE));
6078
6079 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6080 if (RHS == BOC && RHSV.isPowerOf2())
6081 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6082 ICmpInst::ICMP_NE, LHSI,
6083 Constant::getNullValue(RHS->getType()));
6084
6085 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006086 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006087 Value *X = BO->getOperand(0);
6088 Constant *Zero = Constant::getNullValue(X->getType());
6089 ICmpInst::Predicate pred = isICMP_NE ?
6090 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6091 return new ICmpInst(pred, X, Zero);
6092 }
6093
6094 // ((X & ~7) == 0) --> X < 8
6095 if (RHSV == 0 && isHighOnes(BOC)) {
6096 Value *X = BO->getOperand(0);
6097 Constant *NegX = ConstantExpr::getNeg(BOC);
6098 ICmpInst::Predicate pred = isICMP_NE ?
6099 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6100 return new ICmpInst(pred, X, NegX);
6101 }
6102 }
6103 default: break;
6104 }
6105 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6106 // Handle icmp {eq|ne} <intrinsic>, intcst.
6107 if (II->getIntrinsicID() == Intrinsic::bswap) {
6108 AddToWorkList(II);
6109 ICI.setOperand(0, II->getOperand(1));
6110 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6111 return &ICI;
6112 }
6113 }
6114 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006115 // If the LHS is a cast from an integral value of the same size,
6116 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006117 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6118 Value *CastOp = Cast->getOperand(0);
6119 const Type *SrcTy = CastOp->getType();
6120 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6121 if (SrcTy->isInteger() &&
6122 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6123 // If this is an unsigned comparison, try to make the comparison use
6124 // smaller constant values.
6125 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6126 // X u< 128 => X s> -1
6127 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6128 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6129 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6130 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6131 // X u> 127 => X s< 0
6132 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6133 Constant::getNullValue(SrcTy));
6134 }
6135 }
6136 }
6137 }
6138 return 0;
6139}
6140
6141/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6142/// We only handle extending casts so far.
6143///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006144Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6145 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006146 Value *LHSCIOp = LHSCI->getOperand(0);
6147 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006148 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006149 Value *RHSCIOp;
6150
Chris Lattner8c756c12007-05-05 22:41:33 +00006151 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6152 // integer type is the same size as the pointer type.
6153 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6154 getTargetData().getPointerSizeInBits() ==
6155 cast<IntegerType>(DestTy)->getBitWidth()) {
6156 Value *RHSOp = 0;
6157 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006158 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006159 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6160 RHSOp = RHSC->getOperand(0);
6161 // If the pointer types don't match, insert a bitcast.
6162 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006163 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006164 }
6165
6166 if (RHSOp)
6167 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6168 }
6169
6170 // The code below only handles extension cast instructions, so far.
6171 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006172 if (LHSCI->getOpcode() != Instruction::ZExt &&
6173 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006174 return 0;
6175
Reid Spencere4d87aa2006-12-23 06:05:41 +00006176 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6177 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006178
Reid Spencere4d87aa2006-12-23 06:05:41 +00006179 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006180 // Not an extension from the same type?
6181 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006182 if (RHSCIOp->getType() != LHSCIOp->getType())
6183 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006184
Nick Lewycky4189a532008-01-28 03:48:02 +00006185 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006186 // and the other is a zext), then we can't handle this.
6187 if (CI->getOpcode() != LHSCI->getOpcode())
6188 return 0;
6189
Nick Lewycky4189a532008-01-28 03:48:02 +00006190 // Deal with equality cases early.
6191 if (ICI.isEquality())
6192 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6193
6194 // A signed comparison of sign extended values simplifies into a
6195 // signed comparison.
6196 if (isSignedCmp && isSignedExt)
6197 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6198
6199 // The other three cases all fold into an unsigned comparison.
6200 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006201 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006202
Reid Spencere4d87aa2006-12-23 06:05:41 +00006203 // If we aren't dealing with a constant on the RHS, exit early
6204 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6205 if (!CI)
6206 return 0;
6207
6208 // Compute the constant that would happen if we truncated to SrcTy then
6209 // reextended to DestTy.
6210 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6211 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6212
6213 // If the re-extended constant didn't change...
6214 if (Res2 == CI) {
6215 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6216 // For example, we might have:
6217 // %A = sext short %X to uint
6218 // %B = icmp ugt uint %A, 1330
6219 // It is incorrect to transform this into
6220 // %B = icmp ugt short %X, 1330
6221 // because %A may have negative value.
6222 //
6223 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6224 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006225 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006226 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6227 else
6228 return 0;
6229 }
6230
6231 // The re-extended constant changed so the constant cannot be represented
6232 // in the shorter type. Consequently, we cannot emit a simple comparison.
6233
6234 // First, handle some easy cases. We know the result cannot be equal at this
6235 // point so handle the ICI.isEquality() cases
6236 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006237 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006238 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006239 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006240
6241 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6242 // should have been folded away previously and not enter in here.
6243 Value *Result;
6244 if (isSignedCmp) {
6245 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006246 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006247 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006248 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006249 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006250 } else {
6251 // We're performing an unsigned comparison.
6252 if (isSignedExt) {
6253 // We're performing an unsigned comp with a sign extended value.
6254 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006255 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006256 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6257 NegOne, ICI.getName()), ICI);
6258 } else {
6259 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006260 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006261 }
6262 }
6263
6264 // Finally, return the value computed.
6265 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6266 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6267 return ReplaceInstUsesWith(ICI, Result);
6268 } else {
6269 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6270 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6271 "ICmp should be folded!");
6272 if (Constant *CI = dyn_cast<Constant>(Result))
6273 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6274 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006275 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006276 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006277}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006278
Reid Spencer832254e2007-02-02 02:16:23 +00006279Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6280 return commonShiftTransforms(I);
6281}
6282
6283Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6284 return commonShiftTransforms(I);
6285}
6286
6287Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006288 if (Instruction *R = commonShiftTransforms(I))
6289 return R;
6290
6291 Value *Op0 = I.getOperand(0);
6292
6293 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6294 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6295 if (CSI->isAllOnesValue())
6296 return ReplaceInstUsesWith(I, CSI);
6297
6298 // See if we can turn a signed shr into an unsigned shr.
6299 if (MaskedValueIsZero(Op0,
6300 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006301 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006302
6303 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006304}
6305
6306Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6307 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006309
6310 // shl X, 0 == X and shr X, 0 == X
6311 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006312 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006313 Op0 == Constant::getNullValue(Op0->getType()))
6314 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006315
Reid Spencere4d87aa2006-12-23 06:05:41 +00006316 if (isa<UndefValue>(Op0)) {
6317 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006318 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006319 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006320 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6321 }
6322 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6324 return ReplaceInstUsesWith(I, Op0);
6325 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006327 }
6328
Chris Lattner2eefe512004-04-09 19:05:30 +00006329 // Try to fold constant and into select arguments.
6330 if (isa<Constant>(Op0))
6331 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006332 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006333 return R;
6334
Reid Spencerb83eb642006-10-20 07:07:24 +00006335 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006336 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6337 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006338 return 0;
6339}
6340
Reid Spencerb83eb642006-10-20 07:07:24 +00006341Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006342 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006343 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006344
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006345 // See if we can simplify any instructions used by the instruction whose sole
6346 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006347 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6348 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6349 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006350 KnownZero, KnownOne))
6351 return &I;
6352
Chris Lattner4d5542c2006-01-06 07:12:35 +00006353 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6354 // of a signed value.
6355 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006356 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006357 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006358 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6359 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006360 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006361 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006362 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006363 }
6364
6365 // ((X*C1) << C2) == (X * (C1 << C2))
6366 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6367 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6368 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006369 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006370 ConstantExpr::getShl(BOOp, Op1));
6371
6372 // Try to fold constant and into select arguments.
6373 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6374 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6375 return R;
6376 if (isa<PHINode>(Op0))
6377 if (Instruction *NV = FoldOpIntoPhi(I))
6378 return NV;
6379
Chris Lattner8999dd32007-12-22 09:07:47 +00006380 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6381 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6382 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6383 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6384 // place. Don't try to do this transformation in this case. Also, we
6385 // require that the input operand is a shift-by-constant so that we have
6386 // confidence that the shifts will get folded together. We could do this
6387 // xform in more cases, but it is unlikely to be profitable.
6388 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6389 isa<ConstantInt>(TrOp->getOperand(1))) {
6390 // Okay, we'll do this xform. Make the shift of shift.
6391 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006392 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006393 I.getName());
6394 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6395
6396 // For logical shifts, the truncation has the effect of making the high
6397 // part of the register be zeros. Emulate this by inserting an AND to
6398 // clear the top bits as needed. This 'and' will usually be zapped by
6399 // other xforms later if dead.
6400 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6401 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6402 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6403
6404 // The mask we constructed says what the trunc would do if occurring
6405 // between the shifts. We want to know the effect *after* the second
6406 // shift. We know that it is a logical shift by a constant, so adjust the
6407 // mask as appropriate.
6408 if (I.getOpcode() == Instruction::Shl)
6409 MaskV <<= Op1->getZExtValue();
6410 else {
6411 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6412 MaskV = MaskV.lshr(Op1->getZExtValue());
6413 }
6414
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006415 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006416 TI->getName());
6417 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6418
6419 // Return the value truncated to the interesting size.
6420 return new TruncInst(And, I.getType());
6421 }
6422 }
6423
Chris Lattner4d5542c2006-01-06 07:12:35 +00006424 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006425 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6426 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6427 Value *V1, *V2;
6428 ConstantInt *CC;
6429 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006430 default: break;
6431 case Instruction::Add:
6432 case Instruction::And:
6433 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006434 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006435 // These operators commute.
6436 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006437 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6438 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006439 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006440 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006441 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006442 Op0BO->getName());
6443 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006444 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006445 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006446 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006447 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006448 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006449 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006450 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006451 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006452
Chris Lattner150f12a2005-09-18 06:30:59 +00006453 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006454 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006455 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006456 match(Op0BOOp1,
6457 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006458 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6459 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006460 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006461 Op0BO->getOperand(0), Op1,
6462 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006463 InsertNewInstBefore(YS, I); // (Y << C)
6464 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006465 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006466 V1->getName()+".mask");
6467 InsertNewInstBefore(XM, I); // X & (CC << C)
6468
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006469 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006470 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006471 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006472
Reid Spencera07cb7d2007-02-02 14:41:37 +00006473 // FALL THROUGH.
6474 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006475 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006476 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6477 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006478 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006479 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006480 Op0BO->getOperand(1), Op1,
6481 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006482 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006483 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006484 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006485 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006486 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006487 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006488 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006489 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006490 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006491
Chris Lattner13d4ab42006-05-31 21:14:00 +00006492 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006493 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6494 match(Op0BO->getOperand(0),
6495 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006496 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006497 cast<BinaryOperator>(Op0BO->getOperand(0))
6498 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006499 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006500 Op0BO->getOperand(1), Op1,
6501 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006502 InsertNewInstBefore(YS, I); // (Y << C)
6503 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006504 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006505 V1->getName()+".mask");
6506 InsertNewInstBefore(XM, I); // X & (CC << C)
6507
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006508 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006509 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006510
Chris Lattner11021cb2005-09-18 05:12:10 +00006511 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006512 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006513 }
6514
6515
6516 // If the operand is an bitwise operator with a constant RHS, and the
6517 // shift is the only use, we can pull it out of the shift.
6518 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6519 bool isValid = true; // Valid only for And, Or, Xor
6520 bool highBitSet = false; // Transform if high bit of constant set?
6521
6522 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006523 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006524 case Instruction::Add:
6525 isValid = isLeftShift;
6526 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006527 case Instruction::Or:
6528 case Instruction::Xor:
6529 highBitSet = false;
6530 break;
6531 case Instruction::And:
6532 highBitSet = true;
6533 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006534 }
6535
6536 // If this is a signed shift right, and the high bit is modified
6537 // by the logical operation, do not perform the transformation.
6538 // The highBitSet boolean indicates the value of the high bit of
6539 // the constant which would cause it to be modified for this
6540 // operation.
6541 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006542 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006543 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006544
6545 if (isValid) {
6546 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6547
6548 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006549 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006550 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006551 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006552
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006553 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006554 NewRHS);
6555 }
6556 }
6557 }
6558 }
6559
Chris Lattnerad0124c2006-01-06 07:52:12 +00006560 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006561 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6562 if (ShiftOp && !ShiftOp->isShift())
6563 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006564
Reid Spencerb83eb642006-10-20 07:07:24 +00006565 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006566 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006567 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6568 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006569 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6570 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6571 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006572
Zhou Sheng4351c642007-04-02 08:20:41 +00006573 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006574 if (AmtSum > TypeBits)
6575 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006576
6577 const IntegerType *Ty = cast<IntegerType>(I.getType());
6578
6579 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006580 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006581 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006582 ConstantInt::get(Ty, AmtSum));
6583 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6584 I.getOpcode() == Instruction::AShr) {
6585 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006586 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006587 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6588 I.getOpcode() == Instruction::LShr) {
6589 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6590 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006591 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006592 InsertNewInstBefore(Shift, I);
6593
Zhou Shenge9e03f62007-03-28 15:02:20 +00006594 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006595 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006596 }
6597
Chris Lattnerb87056f2007-02-05 00:57:54 +00006598 // Okay, if we get here, one shift must be left, and the other shift must be
6599 // right. See if the amounts are equal.
6600 if (ShiftAmt1 == ShiftAmt2) {
6601 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6602 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006603 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006604 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006605 }
6606 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6607 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006608 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006609 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006610 }
6611 // We can simplify ((X << C) >>s C) into a trunc + sext.
6612 // NOTE: we could do this for any C, but that would make 'unusual' integer
6613 // types. For now, just stick to ones well-supported by the code
6614 // generators.
6615 const Type *SExtType = 0;
6616 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006617 case 1 :
6618 case 8 :
6619 case 16 :
6620 case 32 :
6621 case 64 :
6622 case 128:
6623 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6624 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006625 default: break;
6626 }
6627 if (SExtType) {
6628 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6629 InsertNewInstBefore(NewTrunc, I);
6630 return new SExtInst(NewTrunc, Ty);
6631 }
6632 // Otherwise, we can't handle it yet.
6633 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006634 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006635
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006636 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006637 if (I.getOpcode() == Instruction::Shl) {
6638 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6639 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006640 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006641 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006642 InsertNewInstBefore(Shift, I);
6643
Reid Spencer55702aa2007-03-25 21:11:44 +00006644 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006645 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006646 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006647
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006648 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006649 if (I.getOpcode() == Instruction::LShr) {
6650 assert(ShiftOp->getOpcode() == Instruction::Shl);
6651 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006652 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006653 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006654
Reid Spencerd5e30f02007-03-26 17:18:58 +00006655 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006656 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006657 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006658
6659 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6660 } else {
6661 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006662 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006663
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006664 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006665 if (I.getOpcode() == Instruction::Shl) {
6666 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6667 ShiftOp->getOpcode() == Instruction::AShr);
6668 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006669 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006670 ConstantInt::get(Ty, ShiftDiff));
6671 InsertNewInstBefore(Shift, I);
6672
Reid Spencer55702aa2007-03-25 21:11:44 +00006673 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006674 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006675 }
6676
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006677 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006678 if (I.getOpcode() == Instruction::LShr) {
6679 assert(ShiftOp->getOpcode() == Instruction::Shl);
6680 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006681 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006682 InsertNewInstBefore(Shift, I);
6683
Reid Spencer68d27cf2007-03-26 23:45:51 +00006684 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006685 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006686 }
6687
6688 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006689 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006690 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006691 return 0;
6692}
6693
Chris Lattnera1be5662002-05-02 17:06:02 +00006694
Chris Lattnercfd65102005-10-29 04:36:15 +00006695/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6696/// expression. If so, decompose it, returning some value X, such that Val is
6697/// X*Scale+Offset.
6698///
6699static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006700 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006701 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006702 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006703 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006704 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006705 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006706 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6707 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6708 if (I->getOpcode() == Instruction::Shl) {
6709 // This is a value scaled by '1 << the shift amt'.
6710 Scale = 1U << RHS->getZExtValue();
6711 Offset = 0;
6712 return I->getOperand(0);
6713 } else if (I->getOpcode() == Instruction::Mul) {
6714 // This value is scaled by 'RHS'.
6715 Scale = RHS->getZExtValue();
6716 Offset = 0;
6717 return I->getOperand(0);
6718 } else if (I->getOpcode() == Instruction::Add) {
6719 // We have X+C. Check to see if we really have (X*C2)+C1,
6720 // where C1 is divisible by C2.
6721 unsigned SubScale;
6722 Value *SubVal =
6723 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6724 Offset += RHS->getZExtValue();
6725 Scale = SubScale;
6726 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006727 }
6728 }
6729 }
6730
6731 // Otherwise, we can't look past this.
6732 Scale = 1;
6733 Offset = 0;
6734 return Val;
6735}
6736
6737
Chris Lattnerb3f83972005-10-24 06:03:58 +00006738/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6739/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006740Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006741 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006742 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006743
Chris Lattnerb53c2382005-10-24 06:22:12 +00006744 // Remove any uses of AI that are dead.
6745 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006746
Chris Lattnerb53c2382005-10-24 06:22:12 +00006747 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6748 Instruction *User = cast<Instruction>(*UI++);
6749 if (isInstructionTriviallyDead(User)) {
6750 while (UI != E && *UI == User)
6751 ++UI; // If this instruction uses AI more than once, don't break UI.
6752
Chris Lattnerb53c2382005-10-24 06:22:12 +00006753 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006754 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006755 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006756 }
6757 }
6758
Chris Lattnerb3f83972005-10-24 06:03:58 +00006759 // Get the type really allocated and the type casted to.
6760 const Type *AllocElTy = AI.getAllocatedType();
6761 const Type *CastElTy = PTy->getElementType();
6762 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006763
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006764 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6765 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006766 if (CastElTyAlign < AllocElTyAlign) return 0;
6767
Chris Lattner39387a52005-10-24 06:35:18 +00006768 // If the allocation has multiple uses, only promote it if we are strictly
6769 // increasing the alignment of the resultant allocation. If we keep it the
6770 // same, we open the door to infinite loops of various kinds.
6771 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6772
Duncan Sands514ab342007-11-01 20:53:16 +00006773 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6774 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006775 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006776
Chris Lattner455fcc82005-10-29 03:19:53 +00006777 // See if we can satisfy the modulus by pulling a scale out of the array
6778 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006779 unsigned ArraySizeScale;
6780 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006781 Value *NumElements = // See if the array size is a decomposable linear expr.
6782 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6783
Chris Lattner455fcc82005-10-29 03:19:53 +00006784 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6785 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006786 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6787 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006788
Chris Lattner455fcc82005-10-29 03:19:53 +00006789 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6790 Value *Amt = 0;
6791 if (Scale == 1) {
6792 Amt = NumElements;
6793 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006794 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006795 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6796 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006797 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006798 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006799 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006800 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006801 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006802 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006803 }
6804
Jeff Cohen86796be2007-04-04 16:58:57 +00006805 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6806 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006807 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006808 Amt = InsertNewInstBefore(Tmp, AI);
6809 }
6810
Chris Lattnerb3f83972005-10-24 06:03:58 +00006811 AllocationInst *New;
6812 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006813 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006814 else
Chris Lattner6934a042007-02-11 01:23:03 +00006815 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006816 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006817 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006818
6819 // If the allocation has multiple uses, insert a cast and change all things
6820 // that used it to use the new cast. This will also hack on CI, but it will
6821 // die soon.
6822 if (!AI.hasOneUse()) {
6823 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006824 // New is the allocation instruction, pointer typed. AI is the original
6825 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6826 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006827 InsertNewInstBefore(NewCast, AI);
6828 AI.replaceAllUsesWith(NewCast);
6829 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006830 return ReplaceInstUsesWith(CI, New);
6831}
6832
Chris Lattner70074e02006-05-13 02:06:03 +00006833/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006834/// and return it as type Ty without inserting any new casts and without
6835/// changing the computed value. This is used by code that tries to decide
6836/// whether promoting or shrinking integer operations to wider or smaller types
6837/// will allow us to eliminate a truncate or extend.
6838///
6839/// This is a truncation operation if Ty is smaller than V->getType(), or an
6840/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006841bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6842 unsigned CastOpc,
6843 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006844 // We can always evaluate constants in another type.
6845 if (isa<ConstantInt>(V))
6846 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006847
6848 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006849 if (!I) return false;
6850
6851 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006852
Chris Lattner951626b2007-08-02 06:11:14 +00006853 // If this is an extension or truncate, we can often eliminate it.
6854 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6855 // If this is a cast from the destination type, we can trivially eliminate
6856 // it, and this will remove a cast overall.
6857 if (I->getOperand(0)->getType() == Ty) {
6858 // If the first operand is itself a cast, and is eliminable, do not count
6859 // this as an eliminable cast. We would prefer to eliminate those two
6860 // casts first.
6861 if (!isa<CastInst>(I->getOperand(0)))
6862 ++NumCastsRemoved;
6863 return true;
6864 }
6865 }
6866
6867 // We can't extend or shrink something that has multiple uses: doing so would
6868 // require duplicating the instruction in general, which isn't profitable.
6869 if (!I->hasOneUse()) return false;
6870
Chris Lattner70074e02006-05-13 02:06:03 +00006871 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006872 case Instruction::Add:
6873 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006874 case Instruction::And:
6875 case Instruction::Or:
6876 case Instruction::Xor:
6877 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006878 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6879 NumCastsRemoved) &&
6880 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6881 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006882
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006883 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006884 // A multiply can be truncated by truncating its operands.
6885 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6886 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6887 NumCastsRemoved) &&
6888 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6889 NumCastsRemoved);
6890
Chris Lattner46b96052006-11-29 07:18:39 +00006891 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006892 // If we are truncating the result of this SHL, and if it's a shift of a
6893 // constant amount, we can always perform a SHL in a smaller type.
6894 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006895 uint32_t BitWidth = Ty->getBitWidth();
6896 if (BitWidth < OrigTy->getBitWidth() &&
6897 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006898 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6899 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006900 }
6901 break;
6902 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006903 // If this is a truncate of a logical shr, we can truncate it to a smaller
6904 // lshr iff we know that the bits we would otherwise be shifting in are
6905 // already zeros.
6906 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006907 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6908 uint32_t BitWidth = Ty->getBitWidth();
6909 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006910 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006911 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6912 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006913 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6914 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006915 }
6916 }
Chris Lattner46b96052006-11-29 07:18:39 +00006917 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006918 case Instruction::ZExt:
6919 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006920 case Instruction::Trunc:
6921 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006922 // can safely replace it. Note that replacing it does not reduce the number
6923 // of casts in the input.
6924 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006925 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006926
Reid Spencer3da59db2006-11-27 01:05:10 +00006927 break;
6928 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006929 // TODO: Can handle more cases here.
6930 break;
6931 }
6932
6933 return false;
6934}
6935
6936/// EvaluateInDifferentType - Given an expression that
6937/// CanEvaluateInDifferentType returns true for, actually insert the code to
6938/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006939Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006940 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006941 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006942 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006943
6944 // Otherwise, it must be an instruction.
6945 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006946 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006947 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006948 case Instruction::Add:
6949 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006950 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006951 case Instruction::And:
6952 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006953 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006954 case Instruction::AShr:
6955 case Instruction::LShr:
6956 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006957 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006958 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006959 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00006960 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006961 break;
6962 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006963 case Instruction::Trunc:
6964 case Instruction::ZExt:
6965 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006966 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006967 // just return the source. There's no need to insert it because it is not
6968 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006969 if (I->getOperand(0)->getType() == Ty)
6970 return I->getOperand(0);
6971
Chris Lattner951626b2007-08-02 06:11:14 +00006972 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006973 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00006974 Ty, I->getName());
6975 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006976 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006977 // TODO: Can handle more cases here.
6978 assert(0 && "Unreachable!");
6979 break;
6980 }
6981
6982 return InsertNewInstBefore(Res, *I);
6983}
6984
Reid Spencer3da59db2006-11-27 01:05:10 +00006985/// @brief Implement the transforms common to all CastInst visitors.
6986Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006987 Value *Src = CI.getOperand(0);
6988
Dan Gohman23d9d272007-05-11 21:10:54 +00006989 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006990 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006991 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006992 if (Instruction::CastOps opc =
6993 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6994 // The first cast (CSrc) is eliminable so we need to fix up or replace
6995 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006996 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006997 }
6998 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006999
Reid Spencer3da59db2006-11-27 01:05:10 +00007000 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007001 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7002 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7003 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007004
7005 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007006 if (isa<PHINode>(Src))
7007 if (Instruction *NV = FoldOpIntoPhi(CI))
7008 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007009
Reid Spencer3da59db2006-11-27 01:05:10 +00007010 return 0;
7011}
7012
Chris Lattnerd3e28342007-04-27 17:44:50 +00007013/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7014Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7015 Value *Src = CI.getOperand(0);
7016
Chris Lattnerd3e28342007-04-27 17:44:50 +00007017 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007018 // If casting the result of a getelementptr instruction with no offset, turn
7019 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007020 if (GEP->hasAllZeroIndices()) {
7021 // Changing the cast operand is usually not a good idea but it is safe
7022 // here because the pointer operand is being replaced with another
7023 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007024 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007025 CI.setOperand(0, GEP->getOperand(0));
7026 return &CI;
7027 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007028
7029 // If the GEP has a single use, and the base pointer is a bitcast, and the
7030 // GEP computes a constant offset, see if we can convert these three
7031 // instructions into fewer. This typically happens with unions and other
7032 // non-type-safe code.
7033 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7034 if (GEP->hasAllConstantIndices()) {
7035 // We are guaranteed to get a constant from EmitGEPOffset.
7036 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7037 int64_t Offset = OffsetV->getSExtValue();
7038
7039 // Get the base pointer input of the bitcast, and the type it points to.
7040 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7041 const Type *GEPIdxTy =
7042 cast<PointerType>(OrigBase->getType())->getElementType();
7043 if (GEPIdxTy->isSized()) {
7044 SmallVector<Value*, 8> NewIndices;
7045
Chris Lattnerc42e2262007-05-05 01:59:31 +00007046 // Start with the index over the outer type. Note that the type size
7047 // might be zero (even if the offset isn't zero) if the indexed type
7048 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007049 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007050 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007051 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007052 FirstIdx = Offset/TySize;
7053 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007054
Chris Lattnerc42e2262007-05-05 01:59:31 +00007055 // Handle silly modulus not returning values values [0..TySize).
7056 if (Offset < 0) {
7057 --FirstIdx;
7058 Offset += TySize;
7059 assert(Offset >= 0);
7060 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007061 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007062 }
7063
7064 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007065
7066 // Index into the types. If we fail, set OrigBase to null.
7067 while (Offset) {
7068 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7069 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007070 if (Offset < (int64_t)SL->getSizeInBytes()) {
7071 unsigned Elt = SL->getElementContainingOffset(Offset);
7072 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007073
Chris Lattner6b6aef82007-05-15 00:16:00 +00007074 Offset -= SL->getElementOffset(Elt);
7075 GEPIdxTy = STy->getElementType(Elt);
7076 } else {
7077 // Otherwise, we can't index into this, bail out.
7078 Offset = 0;
7079 OrigBase = 0;
7080 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007081 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7082 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007083 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007084 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7085 Offset %= EltSize;
7086 } else {
7087 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7088 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007089 GEPIdxTy = STy->getElementType();
7090 } else {
7091 // Otherwise, we can't index into this, bail out.
7092 Offset = 0;
7093 OrigBase = 0;
7094 }
7095 }
7096 if (OrigBase) {
7097 // If we were able to index down into an element, create the GEP
7098 // and bitcast the result. This eliminates one bitcast, potentially
7099 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007100 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7101 NewIndices.begin(),
7102 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007103 InsertNewInstBefore(NGEP, CI);
7104 NGEP->takeName(GEP);
7105
Chris Lattner9bc14642007-04-28 00:57:34 +00007106 if (isa<BitCastInst>(CI))
7107 return new BitCastInst(NGEP, CI.getType());
7108 assert(isa<PtrToIntInst>(CI));
7109 return new PtrToIntInst(NGEP, CI.getType());
7110 }
7111 }
7112 }
7113 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007114 }
7115
7116 return commonCastTransforms(CI);
7117}
7118
7119
7120
Chris Lattnerc739cd62007-03-03 05:27:34 +00007121/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7122/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007123/// cases.
7124/// @brief Implement the transforms common to CastInst with integer operands
7125Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7126 if (Instruction *Result = commonCastTransforms(CI))
7127 return Result;
7128
7129 Value *Src = CI.getOperand(0);
7130 const Type *SrcTy = Src->getType();
7131 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007132 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7133 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007134
Reid Spencer3da59db2006-11-27 01:05:10 +00007135 // See if we can simplify any instructions used by the LHS whose sole
7136 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007137 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7138 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007139 KnownZero, KnownOne))
7140 return &CI;
7141
7142 // If the source isn't an instruction or has more than one use then we
7143 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007144 Instruction *SrcI = dyn_cast<Instruction>(Src);
7145 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007146 return 0;
7147
Chris Lattnerc739cd62007-03-03 05:27:34 +00007148 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007149 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007150 if (!isa<BitCastInst>(CI) &&
7151 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007152 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007153 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007154 // eliminates the cast, so it is always a win. If this is a zero-extension,
7155 // we need to do an AND to maintain the clear top-part of the computation,
7156 // so we require that the input have eliminated at least one cast. If this
7157 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007158 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007159 bool DoXForm;
7160 switch (CI.getOpcode()) {
7161 default:
7162 // All the others use floating point so we shouldn't actually
7163 // get here because of the check above.
7164 assert(0 && "Unknown cast type");
7165 case Instruction::Trunc:
7166 DoXForm = true;
7167 break;
7168 case Instruction::ZExt:
7169 DoXForm = NumCastsRemoved >= 1;
7170 break;
7171 case Instruction::SExt:
7172 DoXForm = NumCastsRemoved >= 2;
7173 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007174 }
7175
7176 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007177 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7178 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007179 assert(Res->getType() == DestTy);
7180 switch (CI.getOpcode()) {
7181 default: assert(0 && "Unknown cast type!");
7182 case Instruction::Trunc:
7183 case Instruction::BitCast:
7184 // Just replace this cast with the result.
7185 return ReplaceInstUsesWith(CI, Res);
7186 case Instruction::ZExt: {
7187 // We need to emit an AND to clear the high bits.
7188 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007189 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7190 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007191 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007192 }
7193 case Instruction::SExt:
7194 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007195 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007196 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7197 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007198 }
7199 }
7200 }
7201
7202 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7203 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7204
7205 switch (SrcI->getOpcode()) {
7206 case Instruction::Add:
7207 case Instruction::Mul:
7208 case Instruction::And:
7209 case Instruction::Or:
7210 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007211 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007212 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7213 // Don't insert two casts if they cannot be eliminated. We allow
7214 // two casts to be inserted if the sizes are the same. This could
7215 // only be converting signedness, which is a noop.
7216 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007217 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7218 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007219 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007220 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7221 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007222 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007223 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007224 }
7225 }
7226
7227 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7228 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7229 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007230 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007232 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007233 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007234 }
7235 break;
7236 case Instruction::SDiv:
7237 case Instruction::UDiv:
7238 case Instruction::SRem:
7239 case Instruction::URem:
7240 // If we are just changing the sign, rewrite.
7241 if (DestBitSize == SrcBitSize) {
7242 // Don't insert two casts if they cannot be eliminated. We allow
7243 // two casts to be inserted if the sizes are the same. This could
7244 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007245 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7246 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007247 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7248 Op0, DestTy, SrcI);
7249 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7250 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007251 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007252 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7253 }
7254 }
7255 break;
7256
7257 case Instruction::Shl:
7258 // Allow changing the sign of the source operand. Do not allow
7259 // changing the size of the shift, UNLESS the shift amount is a
7260 // constant. We must not change variable sized shifts to a smaller
7261 // size, because it is undefined to shift more bits out than exist
7262 // in the value.
7263 if (DestBitSize == SrcBitSize ||
7264 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007265 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7266 Instruction::BitCast : Instruction::Trunc);
7267 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007268 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007269 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007270 }
7271 break;
7272 case Instruction::AShr:
7273 // If this is a signed shr, and if all bits shifted in are about to be
7274 // truncated off, turn it into an unsigned shr to allow greater
7275 // simplifications.
7276 if (DestBitSize < SrcBitSize &&
7277 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007278 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007279 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7280 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007281 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007282 }
7283 }
7284 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007285 }
7286 return 0;
7287}
7288
Chris Lattner8a9f5712007-04-11 06:57:46 +00007289Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007290 if (Instruction *Result = commonIntCastTransforms(CI))
7291 return Result;
7292
7293 Value *Src = CI.getOperand(0);
7294 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007295 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7296 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007297
7298 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7299 switch (SrcI->getOpcode()) {
7300 default: break;
7301 case Instruction::LShr:
7302 // We can shrink lshr to something smaller if we know the bits shifted in
7303 // are already zeros.
7304 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007305 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007306
7307 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007308 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007309 Value* SrcIOp0 = SrcI->getOperand(0);
7310 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007311 if (ShAmt >= DestBitWidth) // All zeros.
7312 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7313
7314 // Okay, we can shrink this. Truncate the input, then return a new
7315 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007316 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7317 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7318 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007319 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007320 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007321 } else { // This is a variable shr.
7322
7323 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7324 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7325 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007326 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007327 Value *One = ConstantInt::get(SrcI->getType(), 1);
7328
Reid Spencer832254e2007-02-02 02:16:23 +00007329 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007330 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007331 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007332 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007333 SrcI->getOperand(0),
7334 "tmp"), CI);
7335 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007336 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007337 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007338 }
7339 break;
7340 }
7341 }
7342
7343 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007344}
7345
Evan Chengb98a10e2008-03-24 00:21:34 +00007346/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7347/// in order to eliminate the icmp.
7348Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7349 bool DoXform) {
7350 // If we are just checking for a icmp eq of a single bit and zext'ing it
7351 // to an integer, then shift the bit to the appropriate place and then
7352 // cast to integer to avoid the comparison.
7353 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7354 const APInt &Op1CV = Op1C->getValue();
7355
7356 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7357 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7358 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7359 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7360 if (!DoXform) return ICI;
7361
7362 Value *In = ICI->getOperand(0);
7363 Value *Sh = ConstantInt::get(In->getType(),
7364 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007365 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007366 In->getName()+".lobit"),
7367 CI);
7368 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007369 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007370 false/*ZExt*/, "tmp", &CI);
7371
7372 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7373 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007374 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007375 In->getName()+".not"),
7376 CI);
7377 }
7378
7379 return ReplaceInstUsesWith(CI, In);
7380 }
7381
7382
7383
7384 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7385 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7386 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7387 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7388 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7389 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7390 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7391 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7392 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7393 // This only works for EQ and NE
7394 ICI->isEquality()) {
7395 // If Op1C some other power of two, convert:
7396 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7397 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7398 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7399 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7400
7401 APInt KnownZeroMask(~KnownZero);
7402 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7403 if (!DoXform) return ICI;
7404
7405 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7406 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7407 // (X&4) == 2 --> false
7408 // (X&4) != 2 --> true
7409 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7410 Res = ConstantExpr::getZExt(Res, CI.getType());
7411 return ReplaceInstUsesWith(CI, Res);
7412 }
7413
7414 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7415 Value *In = ICI->getOperand(0);
7416 if (ShiftAmt) {
7417 // Perform a logical shr by shiftamt.
7418 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007419 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007420 ConstantInt::get(In->getType(), ShiftAmt),
7421 In->getName()+".lobit"), CI);
7422 }
7423
7424 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7425 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007426 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007427 InsertNewInstBefore(cast<Instruction>(In), CI);
7428 }
7429
7430 if (CI.getType() == In->getType())
7431 return ReplaceInstUsesWith(CI, In);
7432 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007433 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007434 }
7435 }
7436 }
7437
7438 return 0;
7439}
7440
Chris Lattner8a9f5712007-04-11 06:57:46 +00007441Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007442 // If one of the common conversion will work ..
7443 if (Instruction *Result = commonIntCastTransforms(CI))
7444 return Result;
7445
7446 Value *Src = CI.getOperand(0);
7447
7448 // If this is a cast of a cast
7449 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007450 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7451 // types and if the sizes are just right we can convert this into a logical
7452 // 'and' which will be much cheaper than the pair of casts.
7453 if (isa<TruncInst>(CSrc)) {
7454 // Get the sizes of the types involved
7455 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007456 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7457 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7458 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007459 // If we're actually extending zero bits and the trunc is a no-op
7460 if (MidSize < DstSize && SrcSize == DstSize) {
7461 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007462 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007463 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007464 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007465 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007466 // Unfortunately, if the type changed, we need to cast it back.
7467 if (And->getType() != CI.getType()) {
7468 And->setName(CSrc->getName()+".mask");
7469 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007470 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007471 }
7472 return And;
7473 }
7474 }
7475 }
7476
Evan Chengb98a10e2008-03-24 00:21:34 +00007477 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7478 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007479
Evan Chengb98a10e2008-03-24 00:21:34 +00007480 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7481 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7482 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7483 // of the (zext icmp) will be transformed.
7484 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7485 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7486 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7487 (transformZExtICmp(LHS, CI, false) ||
7488 transformZExtICmp(RHS, CI, false))) {
7489 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7490 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007491 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007492 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007493 }
7494
Reid Spencer3da59db2006-11-27 01:05:10 +00007495 return 0;
7496}
7497
Chris Lattner8a9f5712007-04-11 06:57:46 +00007498Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007499 if (Instruction *I = commonIntCastTransforms(CI))
7500 return I;
7501
Chris Lattner8a9f5712007-04-11 06:57:46 +00007502 Value *Src = CI.getOperand(0);
7503
7504 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7505 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7506 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7507 // If we are just checking for a icmp eq of a single bit and zext'ing it
7508 // to an integer, then shift the bit to the appropriate place and then
7509 // cast to integer to avoid the comparison.
7510 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7511 const APInt &Op1CV = Op1C->getValue();
7512
7513 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7514 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7515 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7516 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7517 Value *In = ICI->getOperand(0);
7518 Value *Sh = ConstantInt::get(In->getType(),
7519 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007520 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007521 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007522 CI);
7523 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007524 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007525 true/*SExt*/, "tmp", &CI);
7526
7527 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007528 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007529 In->getName()+".not"), CI);
7530
7531 return ReplaceInstUsesWith(CI, In);
7532 }
7533 }
7534 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007535
7536 // See if the value being truncated is already sign extended. If so, just
7537 // eliminate the trunc/sext pair.
7538 if (getOpcode(Src) == Instruction::Trunc) {
7539 Value *Op = cast<User>(Src)->getOperand(0);
7540 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7541 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7542 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7543 unsigned NumSignBits = ComputeNumSignBits(Op);
7544
7545 if (OpBits == DestBits) {
7546 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7547 // bits, it is already ready.
7548 if (NumSignBits > DestBits-MidBits)
7549 return ReplaceInstUsesWith(CI, Op);
7550 } else if (OpBits < DestBits) {
7551 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7552 // bits, just sext from i32.
7553 if (NumSignBits > OpBits-MidBits)
7554 return new SExtInst(Op, CI.getType(), "tmp");
7555 } else {
7556 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7557 // bits, just truncate to i32.
7558 if (NumSignBits > OpBits-MidBits)
7559 return new TruncInst(Op, CI.getType(), "tmp");
7560 }
7561 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007562
Chris Lattnerba417832007-04-11 06:12:58 +00007563 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007564}
7565
Chris Lattnerb7530652008-01-27 05:29:54 +00007566/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7567/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007568static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007569 APFloat F = CFP->getValueAPF();
7570 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007571 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007572 return 0;
7573}
7574
7575/// LookThroughFPExtensions - If this is an fp extension instruction, look
7576/// through it until we get the source value.
7577static Value *LookThroughFPExtensions(Value *V) {
7578 if (Instruction *I = dyn_cast<Instruction>(V))
7579 if (I->getOpcode() == Instruction::FPExt)
7580 return LookThroughFPExtensions(I->getOperand(0));
7581
7582 // If this value is a constant, return the constant in the smallest FP type
7583 // that can accurately represent it. This allows us to turn
7584 // (float)((double)X+2.0) into x+2.0f.
7585 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7586 if (CFP->getType() == Type::PPC_FP128Ty)
7587 return V; // No constant folding of this.
7588 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007589 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007590 return V;
7591 if (CFP->getType() == Type::DoubleTy)
7592 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007593 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007594 return V;
7595 // Don't try to shrink to various long double types.
7596 }
7597
7598 return V;
7599}
7600
7601Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7602 if (Instruction *I = commonCastTransforms(CI))
7603 return I;
7604
7605 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7606 // smaller than the destination type, we can eliminate the truncate by doing
7607 // the add as the smaller type. This applies to add/sub/mul/div as well as
7608 // many builtins (sqrt, etc).
7609 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7610 if (OpI && OpI->hasOneUse()) {
7611 switch (OpI->getOpcode()) {
7612 default: break;
7613 case Instruction::Add:
7614 case Instruction::Sub:
7615 case Instruction::Mul:
7616 case Instruction::FDiv:
7617 case Instruction::FRem:
7618 const Type *SrcTy = OpI->getType();
7619 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7620 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7621 if (LHSTrunc->getType() != SrcTy &&
7622 RHSTrunc->getType() != SrcTy) {
7623 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7624 // If the source types were both smaller than the destination type of
7625 // the cast, do this xform.
7626 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7627 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7628 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7629 CI.getType(), CI);
7630 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7631 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007632 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007633 }
7634 }
7635 break;
7636 }
7637 }
7638 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007639}
7640
7641Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7642 return commonCastTransforms(CI);
7643}
7644
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007645Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7646 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7647 // mantissa to accurately represent all values of X. For example, do not
7648 // do this with i64->float->i64.
7649 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7650 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7651 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007652 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007653 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7654
7655 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007656}
7657
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007658Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7659 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7660 // mantissa to accurately represent all values of X. For example, do not
7661 // do this with i64->float->i64.
7662 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7663 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7664 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007665 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007666 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7667
7668 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007669}
7670
7671Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7672 return commonCastTransforms(CI);
7673}
7674
7675Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7676 return commonCastTransforms(CI);
7677}
7678
7679Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007680 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007681}
7682
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007683Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7684 if (Instruction *I = commonCastTransforms(CI))
7685 return I;
7686
7687 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7688 if (!DestPointee->isSized()) return 0;
7689
7690 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7691 ConstantInt *Cst;
7692 Value *X;
7693 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7694 m_ConstantInt(Cst)))) {
7695 // If the source and destination operands have the same type, see if this
7696 // is a single-index GEP.
7697 if (X->getType() == CI.getType()) {
7698 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007699 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007700
7701 // Convert the constant to intptr type.
7702 APInt Offset = Cst->getValue();
7703 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7704
7705 // If Offset is evenly divisible by Size, we can do this xform.
7706 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7707 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007708 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007709 }
7710 }
7711 // TODO: Could handle other cases, e.g. where add is indexing into field of
7712 // struct etc.
7713 } else if (CI.getOperand(0)->hasOneUse() &&
7714 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7715 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7716 // "inttoptr+GEP" instead of "add+intptr".
7717
7718 // Get the size of the pointee type.
7719 uint64_t Size = TD->getABITypeSize(DestPointee);
7720
7721 // Convert the constant to intptr type.
7722 APInt Offset = Cst->getValue();
7723 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7724
7725 // If Offset is evenly divisible by Size, we can do this xform.
7726 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7727 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7728
7729 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7730 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007731 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007732 }
7733 }
7734 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007735}
7736
Chris Lattnerd3e28342007-04-27 17:44:50 +00007737Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007738 // If the operands are integer typed then apply the integer transforms,
7739 // otherwise just apply the common ones.
7740 Value *Src = CI.getOperand(0);
7741 const Type *SrcTy = Src->getType();
7742 const Type *DestTy = CI.getType();
7743
Chris Lattner42a75512007-01-15 02:27:26 +00007744 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007745 if (Instruction *Result = commonIntCastTransforms(CI))
7746 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007747 } else if (isa<PointerType>(SrcTy)) {
7748 if (Instruction *I = commonPointerCastTransforms(CI))
7749 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007750 } else {
7751 if (Instruction *Result = commonCastTransforms(CI))
7752 return Result;
7753 }
7754
7755
7756 // Get rid of casts from one type to the same type. These are useless and can
7757 // be replaced by the operand.
7758 if (DestTy == Src->getType())
7759 return ReplaceInstUsesWith(CI, Src);
7760
Reid Spencer3da59db2006-11-27 01:05:10 +00007761 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007762 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7763 const Type *DstElTy = DstPTy->getElementType();
7764 const Type *SrcElTy = SrcPTy->getElementType();
7765
Nate Begeman83ad90a2008-03-31 00:22:16 +00007766 // If the address spaces don't match, don't eliminate the bitcast, which is
7767 // required for changing types.
7768 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7769 return 0;
7770
Chris Lattnerd3e28342007-04-27 17:44:50 +00007771 // If we are casting a malloc or alloca to a pointer to a type of the same
7772 // size, rewrite the allocation instruction to allocate the "right" type.
7773 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7774 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7775 return V;
7776
Chris Lattnerd717c182007-05-05 22:32:24 +00007777 // If the source and destination are pointers, and this cast is equivalent
7778 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007779 // This can enhance SROA and other transforms that want type-safe pointers.
7780 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7781 unsigned NumZeros = 0;
7782 while (SrcElTy != DstElTy &&
7783 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7784 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7785 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7786 ++NumZeros;
7787 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007788
Chris Lattnerd3e28342007-04-27 17:44:50 +00007789 // If we found a path from the src to dest, create the getelementptr now.
7790 if (SrcElTy == DstElTy) {
7791 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007792 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7793 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007794 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007795 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007796
Reid Spencer3da59db2006-11-27 01:05:10 +00007797 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7798 if (SVI->hasOneUse()) {
7799 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7800 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007801 if (isa<VectorType>(DestTy) &&
7802 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007803 SVI->getType()->getNumElements()) {
7804 CastInst *Tmp;
7805 // If either of the operands is a cast from CI.getType(), then
7806 // evaluating the shuffle in the casted destination's type will allow
7807 // us to eliminate at least one cast.
7808 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7809 Tmp->getOperand(0)->getType() == DestTy) ||
7810 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7811 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007812 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7813 SVI->getOperand(0), DestTy, &CI);
7814 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7815 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007816 // Return a new shuffle vector. Use the same element ID's, as we
7817 // know the vector types match #elts.
7818 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007819 }
7820 }
7821 }
7822 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007823 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007824}
7825
Chris Lattnere576b912004-04-09 23:46:01 +00007826/// GetSelectFoldableOperands - We want to turn code that looks like this:
7827/// %C = or %A, %B
7828/// %D = select %cond, %C, %A
7829/// into:
7830/// %C = select %cond, %B, 0
7831/// %D = or %A, %C
7832///
7833/// Assuming that the specified instruction is an operand to the select, return
7834/// a bitmask indicating which operands of this instruction are foldable if they
7835/// equal the other incoming value of the select.
7836///
7837static unsigned GetSelectFoldableOperands(Instruction *I) {
7838 switch (I->getOpcode()) {
7839 case Instruction::Add:
7840 case Instruction::Mul:
7841 case Instruction::And:
7842 case Instruction::Or:
7843 case Instruction::Xor:
7844 return 3; // Can fold through either operand.
7845 case Instruction::Sub: // Can only fold on the amount subtracted.
7846 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007847 case Instruction::LShr:
7848 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007849 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007850 default:
7851 return 0; // Cannot fold
7852 }
7853}
7854
7855/// GetSelectFoldableConstant - For the same transformation as the previous
7856/// function, return the identity constant that goes into the select.
7857static Constant *GetSelectFoldableConstant(Instruction *I) {
7858 switch (I->getOpcode()) {
7859 default: assert(0 && "This cannot happen!"); abort();
7860 case Instruction::Add:
7861 case Instruction::Sub:
7862 case Instruction::Or:
7863 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007864 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007865 case Instruction::LShr:
7866 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007867 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007868 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007869 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007870 case Instruction::Mul:
7871 return ConstantInt::get(I->getType(), 1);
7872 }
7873}
7874
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007875/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7876/// have the same opcode and only one use each. Try to simplify this.
7877Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7878 Instruction *FI) {
7879 if (TI->getNumOperands() == 1) {
7880 // If this is a non-volatile load or a cast from the same type,
7881 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007882 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007883 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7884 return 0;
7885 } else {
7886 return 0; // unknown unary op.
7887 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007888
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007889 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007890 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7891 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007892 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007893 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00007894 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007895 }
7896
Reid Spencer832254e2007-02-02 02:16:23 +00007897 // Only handle binary operators here.
7898 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007899 return 0;
7900
7901 // Figure out if the operations have any operands in common.
7902 Value *MatchOp, *OtherOpT, *OtherOpF;
7903 bool MatchIsOpZero;
7904 if (TI->getOperand(0) == FI->getOperand(0)) {
7905 MatchOp = TI->getOperand(0);
7906 OtherOpT = TI->getOperand(1);
7907 OtherOpF = FI->getOperand(1);
7908 MatchIsOpZero = true;
7909 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7910 MatchOp = TI->getOperand(1);
7911 OtherOpT = TI->getOperand(0);
7912 OtherOpF = FI->getOperand(0);
7913 MatchIsOpZero = false;
7914 } else if (!TI->isCommutative()) {
7915 return 0;
7916 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7917 MatchOp = TI->getOperand(0);
7918 OtherOpT = TI->getOperand(1);
7919 OtherOpF = FI->getOperand(0);
7920 MatchIsOpZero = true;
7921 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7922 MatchOp = TI->getOperand(1);
7923 OtherOpT = TI->getOperand(0);
7924 OtherOpF = FI->getOperand(1);
7925 MatchIsOpZero = true;
7926 } else {
7927 return 0;
7928 }
7929
7930 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00007931 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7932 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007933 InsertNewInstBefore(NewSI, SI);
7934
7935 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7936 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007937 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007938 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007939 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007940 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007941 assert(0 && "Shouldn't get here");
7942 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007943}
7944
Chris Lattner3d69f462004-03-12 05:52:32 +00007945Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007946 Value *CondVal = SI.getCondition();
7947 Value *TrueVal = SI.getTrueValue();
7948 Value *FalseVal = SI.getFalseValue();
7949
7950 // select true, X, Y -> X
7951 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007952 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007953 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007954
7955 // select C, X, X -> X
7956 if (TrueVal == FalseVal)
7957 return ReplaceInstUsesWith(SI, TrueVal);
7958
Chris Lattnere87597f2004-10-16 18:11:37 +00007959 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7960 return ReplaceInstUsesWith(SI, FalseVal);
7961 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7962 return ReplaceInstUsesWith(SI, TrueVal);
7963 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7964 if (isa<Constant>(TrueVal))
7965 return ReplaceInstUsesWith(SI, TrueVal);
7966 else
7967 return ReplaceInstUsesWith(SI, FalseVal);
7968 }
7969
Reid Spencer4fe16d62007-01-11 18:21:29 +00007970 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007971 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007972 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007973 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007974 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007975 } else {
7976 // Change: A = select B, false, C --> A = and !B, C
7977 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007978 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00007979 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007980 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007981 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007982 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007983 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007984 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007985 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007986 } else {
7987 // Change: A = select B, C, true --> A = or !B, C
7988 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007989 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00007990 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007991 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007992 }
7993 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007994
7995 // select a, b, a -> a&b
7996 // select a, a, b -> a|b
7997 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007998 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00007999 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008000 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008001 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008002
Chris Lattner2eefe512004-04-09 19:05:30 +00008003 // Selecting between two integer constants?
8004 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8005 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008006 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008007 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008008 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008009 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008010 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008011 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008012 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008013 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008014 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008015 }
Chris Lattnerba417832007-04-11 06:12:58 +00008016
8017 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008018
Reid Spencere4d87aa2006-12-23 06:05:41 +00008019 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008020
Reid Spencere4d87aa2006-12-23 06:05:41 +00008021 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008022 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008023 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008024 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008025 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008026 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008027 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008028 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008029 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008030 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008031 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008032 InsertNewInstBefore(SRA, SI);
8033
Reid Spencer3da59db2006-11-27 01:05:10 +00008034 // Finally, convert to the type of the select RHS. We figure out
8035 // if this requires a SExt, Trunc or BitCast based on the sizes.
8036 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008037 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8038 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008039 if (SRASize < SISize)
8040 opc = Instruction::SExt;
8041 else if (SRASize > SISize)
8042 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008043 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008044 }
8045 }
8046
8047
8048 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008049 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008050 // non-constant value, eliminate this whole mess. This corresponds to
8051 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008052 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008053 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008054 cast<Constant>(IC->getOperand(1))->isNullValue())
8055 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8056 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008057 isa<ConstantInt>(ICA->getOperand(1)) &&
8058 (ICA->getOperand(1) == TrueValC ||
8059 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008060 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8061 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008062 // know whether we have a icmp_ne or icmp_eq and whether the
8063 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008064 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008065 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008066 Value *V = ICA;
8067 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008068 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008069 Instruction::Xor, V, ICA->getOperand(1)), SI);
8070 return ReplaceInstUsesWith(SI, V);
8071 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008072 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008073 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008074
8075 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008076 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8077 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008078 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008079 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8080 // This is not safe in general for floating point:
8081 // consider X== -0, Y== +0.
8082 // It becomes safe if either operand is a nonzero constant.
8083 ConstantFP *CFPt, *CFPf;
8084 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8085 !CFPt->getValueAPF().isZero()) ||
8086 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8087 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008088 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008089 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008090 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008091 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008092 return ReplaceInstUsesWith(SI, TrueVal);
8093 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8094
Reid Spencere4d87aa2006-12-23 06:05:41 +00008095 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008096 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008097 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8098 // This is not safe in general for floating point:
8099 // consider X== -0, Y== +0.
8100 // It becomes safe if either operand is a nonzero constant.
8101 ConstantFP *CFPt, *CFPf;
8102 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8103 !CFPt->getValueAPF().isZero()) ||
8104 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8105 !CFPf->getValueAPF().isZero()))
8106 return ReplaceInstUsesWith(SI, FalseVal);
8107 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008108 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008109 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8110 return ReplaceInstUsesWith(SI, TrueVal);
8111 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8112 }
8113 }
8114
8115 // See if we are selecting two values based on a comparison of the two values.
8116 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8117 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8118 // Transform (X == Y) ? X : Y -> Y
8119 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8120 return ReplaceInstUsesWith(SI, FalseVal);
8121 // Transform (X != Y) ? X : Y -> X
8122 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8123 return ReplaceInstUsesWith(SI, TrueVal);
8124 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8125
8126 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8127 // Transform (X == Y) ? Y : X -> X
8128 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8129 return ReplaceInstUsesWith(SI, FalseVal);
8130 // Transform (X != Y) ? Y : X -> Y
8131 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008132 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008133 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8134 }
8135 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008136
Chris Lattner87875da2005-01-13 22:52:24 +00008137 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8138 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8139 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008140 Instruction *AddOp = 0, *SubOp = 0;
8141
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008142 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8143 if (TI->getOpcode() == FI->getOpcode())
8144 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8145 return IV;
8146
8147 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8148 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008149 if (TI->getOpcode() == Instruction::Sub &&
8150 FI->getOpcode() == Instruction::Add) {
8151 AddOp = FI; SubOp = TI;
8152 } else if (FI->getOpcode() == Instruction::Sub &&
8153 TI->getOpcode() == Instruction::Add) {
8154 AddOp = TI; SubOp = FI;
8155 }
8156
8157 if (AddOp) {
8158 Value *OtherAddOp = 0;
8159 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8160 OtherAddOp = AddOp->getOperand(1);
8161 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8162 OtherAddOp = AddOp->getOperand(0);
8163 }
8164
8165 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008166 // So at this point we know we have (Y -> OtherAddOp):
8167 // select C, (add X, Y), (sub X, Z)
8168 Value *NegVal; // Compute -Z
8169 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8170 NegVal = ConstantExpr::getNeg(C);
8171 } else {
8172 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008173 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008174 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008175
8176 Value *NewTrueOp = OtherAddOp;
8177 Value *NewFalseOp = NegVal;
8178 if (AddOp != TI)
8179 std::swap(NewTrueOp, NewFalseOp);
8180 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008181 SelectInst::Create(CondVal, NewTrueOp,
8182 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008183
8184 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008185 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008186 }
8187 }
8188 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008189
Chris Lattnere576b912004-04-09 23:46:01 +00008190 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008191 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008192 // See the comment above GetSelectFoldableOperands for a description of the
8193 // transformation we are doing here.
8194 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8195 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8196 !isa<Constant>(FalseVal))
8197 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8198 unsigned OpToFold = 0;
8199 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8200 OpToFold = 1;
8201 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8202 OpToFold = 2;
8203 }
8204
8205 if (OpToFold) {
8206 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008207 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008208 SelectInst::Create(SI.getCondition(),
8209 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008210 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008211 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008213 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008214 else {
8215 assert(0 && "Unknown instruction!!");
8216 }
8217 }
8218 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008219
Chris Lattnere576b912004-04-09 23:46:01 +00008220 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8221 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8222 !isa<Constant>(TrueVal))
8223 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8224 unsigned OpToFold = 0;
8225 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8226 OpToFold = 1;
8227 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8228 OpToFold = 2;
8229 }
8230
8231 if (OpToFold) {
8232 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008233 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008234 SelectInst::Create(SI.getCondition(), C,
8235 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008236 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008237 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008239 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008240 else
Chris Lattnere576b912004-04-09 23:46:01 +00008241 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008242 }
8243 }
8244 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008245
8246 if (BinaryOperator::isNot(CondVal)) {
8247 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8248 SI.setOperand(1, FalseVal);
8249 SI.setOperand(2, TrueVal);
8250 return &SI;
8251 }
8252
Chris Lattner3d69f462004-03-12 05:52:32 +00008253 return 0;
8254}
8255
Dan Gohmaneee962e2008-04-10 18:43:06 +00008256/// EnforceKnownAlignment - If the specified pointer points to an object that
8257/// we control, modify the object's alignment to PrefAlign. This isn't
8258/// often possible though. If alignment is important, a more reliable approach
8259/// is to simply align all global variables and allocation instructions to
8260/// their preferred alignment from the beginning.
8261///
8262static unsigned EnforceKnownAlignment(Value *V,
8263 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008264
Dan Gohmaneee962e2008-04-10 18:43:06 +00008265 User *U = dyn_cast<User>(V);
8266 if (!U) return Align;
8267
8268 switch (getOpcode(U)) {
8269 default: break;
8270 case Instruction::BitCast:
8271 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8272 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008273 // If all indexes are zero, it is just the alignment of the base pointer.
8274 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008275 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008276 if (!isa<Constant>(*i) ||
8277 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008278 AllZeroOperands = false;
8279 break;
8280 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008281
8282 if (AllZeroOperands) {
8283 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008284 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008285 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008286 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008287 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008288 }
8289
8290 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8291 // If there is a large requested alignment and we can, bump up the alignment
8292 // of the global.
8293 if (!GV->isDeclaration()) {
8294 GV->setAlignment(PrefAlign);
8295 Align = PrefAlign;
8296 }
8297 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8298 // If there is a requested alignment and if this is an alloca, round up. We
8299 // don't do this for malloc, because some systems can't respect the request.
8300 if (isa<AllocaInst>(AI)) {
8301 AI->setAlignment(PrefAlign);
8302 Align = PrefAlign;
8303 }
8304 }
8305
8306 return Align;
8307}
8308
8309/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8310/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8311/// and it is more than the alignment of the ultimate object, see if we can
8312/// increase the alignment of the ultimate object, making this check succeed.
8313unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8314 unsigned PrefAlign) {
8315 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8316 sizeof(PrefAlign) * CHAR_BIT;
8317 APInt Mask = APInt::getAllOnesValue(BitWidth);
8318 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8319 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8320 unsigned TrailZ = KnownZero.countTrailingOnes();
8321 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8322
8323 if (PrefAlign > Align)
8324 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8325
8326 // We don't need to make any adjustment.
8327 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008328}
8329
Chris Lattnerf497b022008-01-13 23:50:23 +00008330Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008331 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8332 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008333 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8334 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8335
8336 if (CopyAlign < MinAlign) {
8337 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8338 return MI;
8339 }
8340
8341 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8342 // load/store.
8343 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8344 if (MemOpLength == 0) return 0;
8345
Chris Lattner37ac6082008-01-14 00:28:35 +00008346 // Source and destination pointer types are always "i8*" for intrinsic. See
8347 // if the size is something we can handle with a single primitive load/store.
8348 // A single load+store correctly handles overlapping memory in the memmove
8349 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008350 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008351 if (Size == 0) return MI; // Delete this mem transfer.
8352
8353 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008354 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008355
Chris Lattner37ac6082008-01-14 00:28:35 +00008356 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008357 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008358
8359 // Memcpy forces the use of i8* for the source and destination. That means
8360 // that if you're using memcpy to move one double around, you'll get a cast
8361 // from double* to i8*. We'd much rather use a double load+store rather than
8362 // an i64 load+store, here because this improves the odds that the source or
8363 // dest address will be promotable. See if we can find a better type than the
8364 // integer datatype.
8365 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8366 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8367 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8368 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8369 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008370 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008371 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8372 if (STy->getNumElements() == 1)
8373 SrcETy = STy->getElementType(0);
8374 else
8375 break;
8376 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8377 if (ATy->getNumElements() == 1)
8378 SrcETy = ATy->getElementType();
8379 else
8380 break;
8381 } else
8382 break;
8383 }
8384
Dan Gohman8f8e2692008-05-23 01:52:21 +00008385 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008386 NewPtrTy = PointerType::getUnqual(SrcETy);
8387 }
8388 }
8389
8390
Chris Lattnerf497b022008-01-13 23:50:23 +00008391 // If the memcpy/memmove provides better alignment info than we can
8392 // infer, use it.
8393 SrcAlign = std::max(SrcAlign, CopyAlign);
8394 DstAlign = std::max(DstAlign, CopyAlign);
8395
8396 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8397 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008398 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8399 InsertNewInstBefore(L, *MI);
8400 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8401
8402 // Set the size of the copy to 0, it will be deleted on the next iteration.
8403 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8404 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008405}
Chris Lattner3d69f462004-03-12 05:52:32 +00008406
Chris Lattner69ea9d22008-04-30 06:39:11 +00008407Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8408 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8409 if (MI->getAlignment()->getZExtValue() < Alignment) {
8410 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8411 return MI;
8412 }
8413
8414 // Extract the length and alignment and fill if they are constant.
8415 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8416 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8417 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8418 return 0;
8419 uint64_t Len = LenC->getZExtValue();
8420 Alignment = MI->getAlignment()->getZExtValue();
8421
8422 // If the length is zero, this is a no-op
8423 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8424
8425 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8426 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8427 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8428
8429 Value *Dest = MI->getDest();
8430 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8431
8432 // Alignment 0 is identity for alignment 1 for memset, but not store.
8433 if (Alignment == 0) Alignment = 1;
8434
8435 // Extract the fill value and store.
8436 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8437 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8438 Alignment), *MI);
8439
8440 // Set the size of the copy to 0, it will be deleted on the next iteration.
8441 MI->setLength(Constant::getNullValue(LenC->getType()));
8442 return MI;
8443 }
8444
8445 return 0;
8446}
8447
8448
Chris Lattner8b0ea312006-01-13 20:11:04 +00008449/// visitCallInst - CallInst simplification. This mostly only handles folding
8450/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8451/// the heavy lifting.
8452///
Chris Lattner9fe38862003-06-19 17:00:31 +00008453Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008454 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8455 if (!II) return visitCallSite(&CI);
8456
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008457 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8458 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008459 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008460 bool Changed = false;
8461
8462 // memmove/cpy/set of zero bytes is a noop.
8463 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8464 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8465
Chris Lattner35b9e482004-10-12 04:52:52 +00008466 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008467 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008468 // Replace the instruction with just byte operations. We would
8469 // transform other cases to loads/stores, but we don't know if
8470 // alignment is sufficient.
8471 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008472 }
8473
Chris Lattner35b9e482004-10-12 04:52:52 +00008474 // If we have a memmove and the source operation is a constant global,
8475 // then the source and dest pointers can't alias, so we can change this
8476 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008477 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008478 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8479 if (GVSrc->isConstant()) {
8480 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008481 Intrinsic::ID MemCpyID;
8482 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8483 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008484 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008485 MemCpyID = Intrinsic::memcpy_i64;
8486 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008487 Changed = true;
8488 }
Chris Lattnera935db82008-05-28 05:30:41 +00008489
8490 // memmove(x,x,size) -> noop.
8491 if (MMI->getSource() == MMI->getDest())
8492 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008493 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008494
Chris Lattner95a959d2006-03-06 20:18:44 +00008495 // If we can determine a pointer alignment that is bigger than currently
8496 // set, update the alignment.
8497 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008498 if (Instruction *I = SimplifyMemTransfer(MI))
8499 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008500 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8501 if (Instruction *I = SimplifyMemSet(MSI))
8502 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008503 }
8504
Chris Lattner8b0ea312006-01-13 20:11:04 +00008505 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008506 } else {
8507 switch (II->getIntrinsicID()) {
8508 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008509 case Intrinsic::ppc_altivec_lvx:
8510 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008511 case Intrinsic::x86_sse_loadu_ps:
8512 case Intrinsic::x86_sse2_loadu_pd:
8513 case Intrinsic::x86_sse2_loadu_dq:
8514 // Turn PPC lvx -> load if the pointer is known aligned.
8515 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008516 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008517 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8518 PointerType::getUnqual(II->getType()),
8519 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008520 return new LoadInst(Ptr);
8521 }
8522 break;
8523 case Intrinsic::ppc_altivec_stvx:
8524 case Intrinsic::ppc_altivec_stvxl:
8525 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008526 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008527 const Type *OpPtrTy =
8528 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008529 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008530 return new StoreInst(II->getOperand(1), Ptr);
8531 }
8532 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008533 case Intrinsic::x86_sse_storeu_ps:
8534 case Intrinsic::x86_sse2_storeu_pd:
8535 case Intrinsic::x86_sse2_storeu_dq:
8536 case Intrinsic::x86_sse2_storel_dq:
8537 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008538 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008539 const Type *OpPtrTy =
8540 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008541 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008542 return new StoreInst(II->getOperand(2), Ptr);
8543 }
8544 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008545
8546 case Intrinsic::x86_sse_cvttss2si: {
8547 // These intrinsics only demands the 0th element of its input vector. If
8548 // we can simplify the input based on that, do so now.
8549 uint64_t UndefElts;
8550 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8551 UndefElts)) {
8552 II->setOperand(1, V);
8553 return II;
8554 }
8555 break;
8556 }
8557
Chris Lattnere2ed0572006-04-06 19:19:17 +00008558 case Intrinsic::ppc_altivec_vperm:
8559 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008560 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008561 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8562
8563 // Check that all of the elements are integer constants or undefs.
8564 bool AllEltsOk = true;
8565 for (unsigned i = 0; i != 16; ++i) {
8566 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8567 !isa<UndefValue>(Mask->getOperand(i))) {
8568 AllEltsOk = false;
8569 break;
8570 }
8571 }
8572
8573 if (AllEltsOk) {
8574 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008575 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8576 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008577 Value *Result = UndefValue::get(Op0->getType());
8578
8579 // Only extract each element once.
8580 Value *ExtractedElts[32];
8581 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8582
8583 for (unsigned i = 0; i != 16; ++i) {
8584 if (isa<UndefValue>(Mask->getOperand(i)))
8585 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008586 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008587 Idx &= 31; // Match the hardware behavior.
8588
8589 if (ExtractedElts[Idx] == 0) {
8590 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008591 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008592 InsertNewInstBefore(Elt, CI);
8593 ExtractedElts[Idx] = Elt;
8594 }
8595
8596 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008597 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8598 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008599 InsertNewInstBefore(cast<Instruction>(Result), CI);
8600 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008601 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008602 }
8603 }
8604 break;
8605
Chris Lattnera728ddc2006-01-13 21:28:09 +00008606 case Intrinsic::stackrestore: {
8607 // If the save is right next to the restore, remove the restore. This can
8608 // happen when variable allocas are DCE'd.
8609 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8610 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8611 BasicBlock::iterator BI = SS;
8612 if (&*++BI == II)
8613 return EraseInstFromFunction(CI);
8614 }
8615 }
8616
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008617 // Scan down this block to see if there is another stack restore in the
8618 // same block without an intervening call/alloca.
8619 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008620 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008621 bool CannotRemove = false;
8622 for (++BI; &*BI != TI; ++BI) {
8623 if (isa<AllocaInst>(BI)) {
8624 CannotRemove = true;
8625 break;
8626 }
8627 if (isa<CallInst>(BI)) {
8628 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008629 CannotRemove = true;
8630 break;
8631 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008632 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008633 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008634 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008635 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008636
8637 // If the stack restore is in a return/unwind block and if there are no
8638 // allocas or calls between the restore and the return, nuke the restore.
8639 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8640 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008641 break;
8642 }
8643 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008644 }
8645
Chris Lattner8b0ea312006-01-13 20:11:04 +00008646 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008647}
8648
8649// InvokeInst simplification
8650//
8651Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008652 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008653}
8654
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008655/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8656/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008657static bool isSafeToEliminateVarargsCast(const CallSite CS,
8658 const CastInst * const CI,
8659 const TargetData * const TD,
8660 const int ix) {
8661 if (!CI->isLosslessCast())
8662 return false;
8663
8664 // The size of ByVal arguments is derived from the type, so we
8665 // can't change to a type with a different size. If the size were
8666 // passed explicitly we could avoid this check.
8667 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8668 return true;
8669
8670 const Type* SrcTy =
8671 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8672 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8673 if (!SrcTy->isSized() || !DstTy->isSized())
8674 return false;
8675 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8676 return false;
8677 return true;
8678}
8679
Chris Lattnera44d8a22003-10-07 22:32:43 +00008680// visitCallSite - Improvements for call and invoke instructions.
8681//
8682Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008683 bool Changed = false;
8684
8685 // If the callee is a constexpr cast of a function, attempt to move the cast
8686 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008687 if (transformConstExprCastCall(CS)) return 0;
8688
Chris Lattner6c266db2003-10-07 22:54:13 +00008689 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008690
Chris Lattner08b22ec2005-05-13 07:09:09 +00008691 if (Function *CalleeF = dyn_cast<Function>(Callee))
8692 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8693 Instruction *OldCall = CS.getInstruction();
8694 // If the call and callee calling conventions don't match, this call must
8695 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008696 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008697 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8698 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008699 if (!OldCall->use_empty())
8700 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8701 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8702 return EraseInstFromFunction(*OldCall);
8703 return 0;
8704 }
8705
Chris Lattner17be6352004-10-18 02:59:09 +00008706 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8707 // This instruction is not reachable, just remove it. We insert a store to
8708 // undef so that we know that this code is not reachable, despite the fact
8709 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008710 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008711 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008712 CS.getInstruction());
8713
8714 if (!CS.getInstruction()->use_empty())
8715 CS.getInstruction()->
8716 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8717
8718 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8719 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008720 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8721 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008722 }
Chris Lattner17be6352004-10-18 02:59:09 +00008723 return EraseInstFromFunction(*CS.getInstruction());
8724 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008725
Duncan Sandscdb6d922007-09-17 10:26:40 +00008726 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8727 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8728 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8729 return transformCallThroughTrampoline(CS);
8730
Chris Lattner6c266db2003-10-07 22:54:13 +00008731 const PointerType *PTy = cast<PointerType>(Callee->getType());
8732 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8733 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008734 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008735 // See if we can optimize any arguments passed through the varargs area of
8736 // the call.
8737 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008738 E = CS.arg_end(); I != E; ++I, ++ix) {
8739 CastInst *CI = dyn_cast<CastInst>(*I);
8740 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8741 *I = CI->getOperand(0);
8742 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008743 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008744 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008745 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008746
Duncan Sandsf0c33542007-12-19 21:13:37 +00008747 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008748 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008749 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008750 Changed = true;
8751 }
8752
Chris Lattner6c266db2003-10-07 22:54:13 +00008753 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008754}
8755
Chris Lattner9fe38862003-06-19 17:00:31 +00008756// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8757// attempt to move the cast to the arguments of the call/invoke.
8758//
8759bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8760 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8761 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008762 if (CE->getOpcode() != Instruction::BitCast ||
8763 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008764 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008765 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008766 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008767 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008768
8769 // Okay, this is a cast from a function to a different type. Unless doing so
8770 // would cause a type conversion of one of our arguments, change this call to
8771 // be a direct call with arguments casted to the appropriate types.
8772 //
8773 const FunctionType *FT = Callee->getFunctionType();
8774 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008775 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008776
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008777 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008778 return false; // TODO: Handle multiple return values.
8779
Chris Lattnerf78616b2004-01-14 06:06:08 +00008780 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008781 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008782 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008783 // Conversion is ok if changing from one pointer type to another or from
8784 // a pointer to an integer of the same size.
8785 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8786 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
Chris Lattnerec479922007-01-06 02:09:32 +00008787 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008788
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008789 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008790 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008791 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008792 return false; // Cannot transform this return value.
8793
Chris Lattner58d74912008-03-12 17:45:29 +00008794 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8795 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008796 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008797 return false; // Attribute not compatible with transformed value.
8798 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008799
Chris Lattnerf78616b2004-01-14 06:06:08 +00008800 // If the callsite is an invoke instruction, and the return value is used by
8801 // a PHI node in a successor, we cannot change the return type of the call
8802 // because there is no place to put the cast instruction (without breaking
8803 // the critical edge). Bail out in this case.
8804 if (!Caller->use_empty())
8805 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8806 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8807 UI != E; ++UI)
8808 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8809 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008810 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008811 return false;
8812 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008813
8814 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8815 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008816
Chris Lattner9fe38862003-06-19 17:00:31 +00008817 CallSite::arg_iterator AI = CS.arg_begin();
8818 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8819 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008820 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008821
8822 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008823 return false; // Cannot transform this parameter value.
8824
Chris Lattner58d74912008-03-12 17:45:29 +00008825 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8826 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008827
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008828 // Converting from one pointer type to another or between a pointer and an
8829 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008830 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008831 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8832 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008833 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008834 }
8835
8836 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008837 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008838 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008839
Chris Lattner58d74912008-03-12 17:45:29 +00008840 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8841 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008842 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008843 // won't be dropping them. Check that these extra arguments have attributes
8844 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008845 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8846 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008847 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008848 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008849 if (PAttrs & ParamAttr::VarArgsIncompatible)
8850 return false;
8851 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008852
Chris Lattner9fe38862003-06-19 17:00:31 +00008853 // Okay, we decided that this is a safe thing to do: go ahead and start
8854 // inserting cast instructions as necessary...
8855 std::vector<Value*> Args;
8856 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008857 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008858 attrVec.reserve(NumCommonArgs);
8859
8860 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008861 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008862
8863 // If the return value is not being used, the type may not be compatible
8864 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008865 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008866
8867 // Add the new return attributes.
8868 if (RAttrs)
8869 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008870
8871 AI = CS.arg_begin();
8872 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8873 const Type *ParamTy = FT->getParamType(i);
8874 if ((*AI)->getType() == ParamTy) {
8875 Args.push_back(*AI);
8876 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008877 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008878 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008879 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008880 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008881 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008882
8883 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008884 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008885 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008886 }
8887
8888 // If the function takes more arguments than the call was taking, add them
8889 // now...
8890 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8891 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8892
8893 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008894 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008895 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008896 cerr << "WARNING: While resolving call to function '"
8897 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008898 } else {
8899 // Add all of the arguments in their promoted form to the arg list...
8900 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8901 const Type *PTy = getPromotedType((*AI)->getType());
8902 if (PTy != (*AI)->getType()) {
8903 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008904 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8905 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008906 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008907 InsertNewInstBefore(Cast, *Caller);
8908 Args.push_back(Cast);
8909 } else {
8910 Args.push_back(*AI);
8911 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008912
Duncan Sandse1e520f2008-01-13 08:02:44 +00008913 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008914 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008915 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8916 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008917 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008918 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008919
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008920 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008921 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008922
Chris Lattner58d74912008-03-12 17:45:29 +00008923 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008924
Chris Lattner9fe38862003-06-19 17:00:31 +00008925 Instruction *NC;
8926 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008927 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008928 Args.begin(), Args.end(),
8929 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008930 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008931 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008932 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00008933 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8934 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008935 CallInst *CI = cast<CallInst>(Caller);
8936 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008937 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008938 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008939 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008940 }
8941
Chris Lattner6934a042007-02-11 01:23:03 +00008942 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008943 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008944 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008945 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008946 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008947 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008948 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008949
8950 // If this is an invoke instruction, we should insert it after the first
8951 // non-phi, instruction in the normal successor block.
8952 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00008953 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00008954 InsertNewInstBefore(NC, *I);
8955 } else {
8956 // Otherwise, it's a call, just insert cast right after the call instr
8957 InsertNewInstBefore(NC, *Caller);
8958 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008959 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008960 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008961 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008962 }
8963 }
8964
8965 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8966 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008967 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008968 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008969 return true;
8970}
8971
Duncan Sandscdb6d922007-09-17 10:26:40 +00008972// transformCallThroughTrampoline - Turn a call to a function created by the
8973// init_trampoline intrinsic into a direct call to the underlying function.
8974//
8975Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8976 Value *Callee = CS.getCalledValue();
8977 const PointerType *PTy = cast<PointerType>(Callee->getType());
8978 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008979 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008980
8981 // If the call already has the 'nest' attribute somewhere then give up -
8982 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008983 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008984 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008985
8986 IntrinsicInst *Tramp =
8987 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8988
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00008989 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008990 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8991 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8992
Chris Lattner58d74912008-03-12 17:45:29 +00008993 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8994 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008995 unsigned NestIdx = 1;
8996 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008997 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008998
8999 // Look for a parameter marked with the 'nest' attribute.
9000 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9001 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009002 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009003 // Record the parameter type and any other attributes.
9004 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009005 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009006 break;
9007 }
9008
9009 if (NestTy) {
9010 Instruction *Caller = CS.getInstruction();
9011 std::vector<Value*> NewArgs;
9012 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9013
Chris Lattner58d74912008-03-12 17:45:29 +00009014 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9015 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009016
Duncan Sandscdb6d922007-09-17 10:26:40 +00009017 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009018 // mean appending it. Likewise for attributes.
9019
9020 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009021 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9022 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009023
Duncan Sandscdb6d922007-09-17 10:26:40 +00009024 {
9025 unsigned Idx = 1;
9026 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9027 do {
9028 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009029 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009030 Value *NestVal = Tramp->getOperand(3);
9031 if (NestVal->getType() != NestTy)
9032 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9033 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009034 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009035 }
9036
9037 if (I == E)
9038 break;
9039
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009040 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009041 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009042 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009043 NewAttrs.push_back
9044 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009045
9046 ++Idx, ++I;
9047 } while (1);
9048 }
9049
9050 // The trampoline may have been bitcast to a bogus type (FTy).
9051 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009052 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009053
Duncan Sandscdb6d922007-09-17 10:26:40 +00009054 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009055 NewTypes.reserve(FTy->getNumParams()+1);
9056
Duncan Sandscdb6d922007-09-17 10:26:40 +00009057 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009058 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009059 {
9060 unsigned Idx = 1;
9061 FunctionType::param_iterator I = FTy->param_begin(),
9062 E = FTy->param_end();
9063
9064 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009065 if (Idx == NestIdx)
9066 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009067 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009068
9069 if (I == E)
9070 break;
9071
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009072 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009073 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009074
9075 ++Idx, ++I;
9076 } while (1);
9077 }
9078
9079 // Replace the trampoline call with a direct call. Let the generic
9080 // code sort out any function type mismatches.
9081 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009082 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009083 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9084 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009085 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009086
9087 Instruction *NewCaller;
9088 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009089 NewCaller = InvokeInst::Create(NewCallee,
9090 II->getNormalDest(), II->getUnwindDest(),
9091 NewArgs.begin(), NewArgs.end(),
9092 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009093 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009094 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009095 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009096 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9097 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009098 if (cast<CallInst>(Caller)->isTailCall())
9099 cast<CallInst>(NewCaller)->setTailCall();
9100 cast<CallInst>(NewCaller)->
9101 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009102 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009103 }
9104 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9105 Caller->replaceAllUsesWith(NewCaller);
9106 Caller->eraseFromParent();
9107 RemoveFromWorkList(Caller);
9108 return 0;
9109 }
9110 }
9111
9112 // Replace the trampoline call with a direct call. Since there is no 'nest'
9113 // parameter, there is no need to adjust the argument list. Let the generic
9114 // code sort out any function type mismatches.
9115 Constant *NewCallee =
9116 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9117 CS.setCalledFunction(NewCallee);
9118 return CS.getInstruction();
9119}
9120
Chris Lattner7da52b22006-11-01 04:51:18 +00009121/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9122/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9123/// and a single binop.
9124Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9125 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009126 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9127 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009128 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009129 Value *LHSVal = FirstInst->getOperand(0);
9130 Value *RHSVal = FirstInst->getOperand(1);
9131
9132 const Type *LHSType = LHSVal->getType();
9133 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009134
9135 // Scan to see if all operands are the same opcode, all have one use, and all
9136 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009137 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009138 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009139 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009140 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009141 // types or GEP's with different index types.
9142 I->getOperand(0)->getType() != LHSType ||
9143 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009144 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009145
9146 // If they are CmpInst instructions, check their predicates
9147 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9148 if (cast<CmpInst>(I)->getPredicate() !=
9149 cast<CmpInst>(FirstInst)->getPredicate())
9150 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009151
9152 // Keep track of which operand needs a phi node.
9153 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9154 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009155 }
9156
Chris Lattner53738a42006-11-08 19:42:28 +00009157 // Otherwise, this is safe to transform, determine if it is profitable.
9158
9159 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9160 // Indexes are often folded into load/store instructions, so we don't want to
9161 // hide them behind a phi.
9162 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9163 return 0;
9164
Chris Lattner7da52b22006-11-01 04:51:18 +00009165 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009166 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009167 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009168 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009169 NewLHS = PHINode::Create(LHSType,
9170 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009171 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9172 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009173 InsertNewInstBefore(NewLHS, PN);
9174 LHSVal = NewLHS;
9175 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009176
9177 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009178 NewRHS = PHINode::Create(RHSType,
9179 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009180 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9181 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009182 InsertNewInstBefore(NewRHS, PN);
9183 RHSVal = NewRHS;
9184 }
9185
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009186 // Add all operands to the new PHIs.
9187 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9188 if (NewLHS) {
9189 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9190 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9191 }
9192 if (NewRHS) {
9193 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9194 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9195 }
9196 }
9197
Chris Lattner7da52b22006-11-01 04:51:18 +00009198 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009199 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009200 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009201 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009202 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009203 else {
9204 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009205 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009206 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009207}
9208
Chris Lattner76c73142006-11-01 07:13:54 +00009209/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9210/// of the block that defines it. This means that it must be obvious the value
9211/// of the load is not changed from the point of the load to the end of the
9212/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009213///
9214/// Finally, it is safe, but not profitable, to sink a load targetting a
9215/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9216/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009217static bool isSafeToSinkLoad(LoadInst *L) {
9218 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9219
9220 for (++BBI; BBI != E; ++BBI)
9221 if (BBI->mayWriteToMemory())
9222 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009223
9224 // Check for non-address taken alloca. If not address-taken already, it isn't
9225 // profitable to do this xform.
9226 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9227 bool isAddressTaken = false;
9228 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9229 UI != E; ++UI) {
9230 if (isa<LoadInst>(UI)) continue;
9231 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9232 // If storing TO the alloca, then the address isn't taken.
9233 if (SI->getOperand(1) == AI) continue;
9234 }
9235 isAddressTaken = true;
9236 break;
9237 }
9238
9239 if (!isAddressTaken)
9240 return false;
9241 }
9242
Chris Lattner76c73142006-11-01 07:13:54 +00009243 return true;
9244}
9245
Chris Lattner9fe38862003-06-19 17:00:31 +00009246
Chris Lattnerbac32862004-11-14 19:13:23 +00009247// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9248// operator and they all are only used by the PHI, PHI together their
9249// inputs, and do the operation once, to the result of the PHI.
9250Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9251 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9252
9253 // Scan the instruction, looking for input operations that can be folded away.
9254 // If all input operands to the phi are the same instruction (e.g. a cast from
9255 // the same type or "+42") we can pull the operation through the PHI, reducing
9256 // code size and simplifying code.
9257 Constant *ConstantOp = 0;
9258 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009259 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009260 if (isa<CastInst>(FirstInst)) {
9261 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009262 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009263 // Can fold binop, compare or shift here if the RHS is a constant,
9264 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009265 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009266 if (ConstantOp == 0)
9267 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009268 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9269 isVolatile = LI->isVolatile();
9270 // We can't sink the load if the loaded value could be modified between the
9271 // load and the PHI.
9272 if (LI->getParent() != PN.getIncomingBlock(0) ||
9273 !isSafeToSinkLoad(LI))
9274 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009275 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009276 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009277 return FoldPHIArgBinOpIntoPHI(PN);
9278 // Can't handle general GEPs yet.
9279 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009280 } else {
9281 return 0; // Cannot fold this operation.
9282 }
9283
9284 // Check to see if all arguments are the same operation.
9285 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9286 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9287 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009288 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009289 return 0;
9290 if (CastSrcTy) {
9291 if (I->getOperand(0)->getType() != CastSrcTy)
9292 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009293 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009294 // We can't sink the load if the loaded value could be modified between
9295 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009296 if (LI->isVolatile() != isVolatile ||
9297 LI->getParent() != PN.getIncomingBlock(i) ||
9298 !isSafeToSinkLoad(LI))
9299 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009300
9301 // If the PHI is volatile and its block has multiple successors, sinking
9302 // it would remove a load of the volatile value from the path through the
9303 // other successor.
9304 if (isVolatile &&
9305 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9306 return 0;
9307
9308
Chris Lattnerbac32862004-11-14 19:13:23 +00009309 } else if (I->getOperand(1) != ConstantOp) {
9310 return 0;
9311 }
9312 }
9313
9314 // Okay, they are all the same operation. Create a new PHI node of the
9315 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009316 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9317 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009318 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009319
9320 Value *InVal = FirstInst->getOperand(0);
9321 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009322
9323 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009324 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9325 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9326 if (NewInVal != InVal)
9327 InVal = 0;
9328 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9329 }
9330
9331 Value *PhiVal;
9332 if (InVal) {
9333 // The new PHI unions all of the same values together. This is really
9334 // common, so we handle it intelligently here for compile-time speed.
9335 PhiVal = InVal;
9336 delete NewPN;
9337 } else {
9338 InsertNewInstBefore(NewPN, PN);
9339 PhiVal = NewPN;
9340 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009341
Chris Lattnerbac32862004-11-14 19:13:23 +00009342 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009343 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009344 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009345 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009346 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009347 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009348 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009349 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009350 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9351
9352 // If this was a volatile load that we are merging, make sure to loop through
9353 // and mark all the input loads as non-volatile. If we don't do this, we will
9354 // insert a new volatile load and the old ones will not be deletable.
9355 if (isVolatile)
9356 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9357 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9358
9359 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009360}
Chris Lattnera1be5662002-05-02 17:06:02 +00009361
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009362/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9363/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009364static bool DeadPHICycle(PHINode *PN,
9365 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009366 if (PN->use_empty()) return true;
9367 if (!PN->hasOneUse()) return false;
9368
9369 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009370 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009371 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009372
9373 // Don't scan crazily complex things.
9374 if (PotentiallyDeadPHIs.size() == 16)
9375 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009376
9377 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9378 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009379
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009380 return false;
9381}
9382
Chris Lattnercf5008a2007-11-06 21:52:06 +00009383/// PHIsEqualValue - Return true if this phi node is always equal to
9384/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9385/// z = some value; x = phi (y, z); y = phi (x, z)
9386static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9387 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9388 // See if we already saw this PHI node.
9389 if (!ValueEqualPHIs.insert(PN))
9390 return true;
9391
9392 // Don't scan crazily complex things.
9393 if (ValueEqualPHIs.size() == 16)
9394 return false;
9395
9396 // Scan the operands to see if they are either phi nodes or are equal to
9397 // the value.
9398 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9399 Value *Op = PN->getIncomingValue(i);
9400 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9401 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9402 return false;
9403 } else if (Op != NonPhiInVal)
9404 return false;
9405 }
9406
9407 return true;
9408}
9409
9410
Chris Lattner473945d2002-05-06 18:06:38 +00009411// PHINode simplification
9412//
Chris Lattner7e708292002-06-25 16:13:24 +00009413Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009414 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009415 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009416
Owen Anderson7e057142006-07-10 22:03:18 +00009417 if (Value *V = PN.hasConstantValue())
9418 return ReplaceInstUsesWith(PN, V);
9419
Owen Anderson7e057142006-07-10 22:03:18 +00009420 // If all PHI operands are the same operation, pull them through the PHI,
9421 // reducing code size.
9422 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9423 PN.getIncomingValue(0)->hasOneUse())
9424 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9425 return Result;
9426
9427 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9428 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9429 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009430 if (PN.hasOneUse()) {
9431 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9432 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009433 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009434 PotentiallyDeadPHIs.insert(&PN);
9435 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9436 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9437 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009438
9439 // If this phi has a single use, and if that use just computes a value for
9440 // the next iteration of a loop, delete the phi. This occurs with unused
9441 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9442 // common case here is good because the only other things that catch this
9443 // are induction variable analysis (sometimes) and ADCE, which is only run
9444 // late.
9445 if (PHIUser->hasOneUse() &&
9446 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9447 PHIUser->use_back() == &PN) {
9448 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9449 }
9450 }
Owen Anderson7e057142006-07-10 22:03:18 +00009451
Chris Lattnercf5008a2007-11-06 21:52:06 +00009452 // We sometimes end up with phi cycles that non-obviously end up being the
9453 // same value, for example:
9454 // z = some value; x = phi (y, z); y = phi (x, z)
9455 // where the phi nodes don't necessarily need to be in the same block. Do a
9456 // quick check to see if the PHI node only contains a single non-phi value, if
9457 // so, scan to see if the phi cycle is actually equal to that value.
9458 {
9459 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9460 // Scan for the first non-phi operand.
9461 while (InValNo != NumOperandVals &&
9462 isa<PHINode>(PN.getIncomingValue(InValNo)))
9463 ++InValNo;
9464
9465 if (InValNo != NumOperandVals) {
9466 Value *NonPhiInVal = PN.getOperand(InValNo);
9467
9468 // Scan the rest of the operands to see if there are any conflicts, if so
9469 // there is no need to recursively scan other phis.
9470 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9471 Value *OpVal = PN.getIncomingValue(InValNo);
9472 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9473 break;
9474 }
9475
9476 // If we scanned over all operands, then we have one unique value plus
9477 // phi values. Scan PHI nodes to see if they all merge in each other or
9478 // the value.
9479 if (InValNo == NumOperandVals) {
9480 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9481 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9482 return ReplaceInstUsesWith(PN, NonPhiInVal);
9483 }
9484 }
9485 }
Chris Lattner60921c92003-12-19 05:58:40 +00009486 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009487}
9488
Reid Spencer17212df2006-12-12 09:18:51 +00009489static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9490 Instruction *InsertPoint,
9491 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009492 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9493 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009494 // We must cast correctly to the pointer type. Ensure that we
9495 // sign extend the integer value if it is smaller as this is
9496 // used for address computation.
9497 Instruction::CastOps opcode =
9498 (VTySize < PtrSize ? Instruction::SExt :
9499 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9500 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009501}
9502
Chris Lattnera1be5662002-05-02 17:06:02 +00009503
Chris Lattner7e708292002-06-25 16:13:24 +00009504Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009505 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009506 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009507 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009508 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009509 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009510
Chris Lattnere87597f2004-10-16 18:11:37 +00009511 if (isa<UndefValue>(GEP.getOperand(0)))
9512 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9513
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009514 bool HasZeroPointerIndex = false;
9515 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9516 HasZeroPointerIndex = C->isNullValue();
9517
9518 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009519 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009520
Chris Lattner28977af2004-04-05 01:30:19 +00009521 // Eliminate unneeded casts for indices.
9522 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009523
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009524 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009525 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9526 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009527 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009528 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009529 if (CI->getOpcode() == Instruction::ZExt ||
9530 CI->getOpcode() == Instruction::SExt) {
9531 const Type *SrcTy = CI->getOperand(0)->getType();
9532 // We can eliminate a cast from i32 to i64 iff the target
9533 // is a 32-bit pointer target.
9534 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9535 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009536 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009537 }
9538 }
9539 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009540 // If we are using a wider index than needed for this platform, shrink it
9541 // to what we need. If the incoming value needs a cast instruction,
9542 // insert it. This explicit cast can make subsequent optimizations more
9543 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009544 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009545 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009546 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009547 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009548 MadeChange = true;
9549 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009550 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9551 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009552 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009553 MadeChange = true;
9554 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009555 }
Chris Lattner28977af2004-04-05 01:30:19 +00009556 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009557 }
Chris Lattner28977af2004-04-05 01:30:19 +00009558 if (MadeChange) return &GEP;
9559
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009560 // If this GEP instruction doesn't move the pointer, and if the input operand
9561 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9562 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009563 if (GEP.hasAllZeroIndices()) {
9564 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9565 // If the bitcast is of an allocation, and the allocation will be
9566 // converted to match the type of the cast, don't touch this.
9567 if (isa<AllocationInst>(BCI->getOperand(0))) {
9568 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009569 if (Instruction *I = visitBitCast(*BCI)) {
9570 if (I != BCI) {
9571 I->takeName(BCI);
9572 BCI->getParent()->getInstList().insert(BCI, I);
9573 ReplaceInstUsesWith(*BCI, I);
9574 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009575 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009576 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009577 }
9578 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9579 }
9580 }
9581
Chris Lattner90ac28c2002-08-02 19:29:35 +00009582 // Combine Indices - If the source pointer to this getelementptr instruction
9583 // is a getelementptr instruction, combine the indices of the two
9584 // getelementptr instructions into a single instruction.
9585 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009586 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009587 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009588 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009589
9590 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009591 // Note that if our source is a gep chain itself that we wait for that
9592 // chain to be resolved before we perform this transformation. This
9593 // avoids us creating a TON of code in some cases.
9594 //
9595 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9596 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9597 return 0; // Wait until our source is folded to completion.
9598
Chris Lattner72588fc2007-02-15 22:48:32 +00009599 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009600
9601 // Find out whether the last index in the source GEP is a sequential idx.
9602 bool EndsWithSequential = false;
9603 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9604 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009605 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009606
Chris Lattner90ac28c2002-08-02 19:29:35 +00009607 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009608 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009609 // Replace: gep (gep %P, long B), long A, ...
9610 // With: T = long A+B; gep %P, T, ...
9611 //
Chris Lattner620ce142004-05-07 22:09:22 +00009612 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009613 if (SO1 == Constant::getNullValue(SO1->getType())) {
9614 Sum = GO1;
9615 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9616 Sum = SO1;
9617 } else {
9618 // If they aren't the same type, convert both to an integer of the
9619 // target's pointer size.
9620 if (SO1->getType() != GO1->getType()) {
9621 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009622 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009623 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009624 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009625 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009626 unsigned PS = TD->getPointerSizeInBits();
9627 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009628 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009629 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009630
Duncan Sands514ab342007-11-01 20:53:16 +00009631 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009632 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009633 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009634 } else {
9635 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009636 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9637 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009638 }
9639 }
9640 }
Chris Lattner620ce142004-05-07 22:09:22 +00009641 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9642 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9643 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009644 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009645 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009646 }
Chris Lattner28977af2004-04-05 01:30:19 +00009647 }
Chris Lattner620ce142004-05-07 22:09:22 +00009648
9649 // Recycle the GEP we already have if possible.
9650 if (SrcGEPOperands.size() == 2) {
9651 GEP.setOperand(0, SrcGEPOperands[0]);
9652 GEP.setOperand(1, Sum);
9653 return &GEP;
9654 } else {
9655 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9656 SrcGEPOperands.end()-1);
9657 Indices.push_back(Sum);
9658 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9659 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009660 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009661 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009662 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009663 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009664 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9665 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009666 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9667 }
9668
9669 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009670 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9671 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009672
Chris Lattner620ce142004-05-07 22:09:22 +00009673 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009674 // GEP of global variable. If all of the indices for this GEP are
9675 // constants, we can promote this to a constexpr instead of an instruction.
9676
9677 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009678 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009679 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9680 for (; I != E && isa<Constant>(*I); ++I)
9681 Indices.push_back(cast<Constant>(*I));
9682
9683 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009684 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9685 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009686
9687 // Replace all uses of the GEP with the new constexpr...
9688 return ReplaceInstUsesWith(GEP, CE);
9689 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009690 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009691 if (!isa<PointerType>(X->getType())) {
9692 // Not interesting. Source pointer must be a cast from pointer.
9693 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009694 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9695 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009696 //
9697 // This occurs when the program declares an array extern like "int X[];"
9698 //
9699 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9700 const PointerType *XTy = cast<PointerType>(X->getType());
9701 if (const ArrayType *XATy =
9702 dyn_cast<ArrayType>(XTy->getElementType()))
9703 if (const ArrayType *CATy =
9704 dyn_cast<ArrayType>(CPTy->getElementType()))
9705 if (CATy->getElementType() == XATy->getElementType()) {
9706 // At this point, we know that the cast source type is a pointer
9707 // to an array of the same type as the destination pointer
9708 // array. Because the array type is never stepped over (there
9709 // is a leading zero) we can fold the cast into this GEP.
9710 GEP.setOperand(0, X);
9711 return &GEP;
9712 }
9713 } else if (GEP.getNumOperands() == 2) {
9714 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009715 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9716 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009717 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9718 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9719 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009720 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9721 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009722 Value *Idx[2];
9723 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9724 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009725 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009726 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009727 // V and GEP are both pointer types --> BitCast
9728 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009729 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009730
9731 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009732 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009733 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009734 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009735
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009736 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009737 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009738 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009739
9740 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9741 // allow either a mul, shift, or constant here.
9742 Value *NewIdx = 0;
9743 ConstantInt *Scale = 0;
9744 if (ArrayEltSize == 1) {
9745 NewIdx = GEP.getOperand(1);
9746 Scale = ConstantInt::get(NewIdx->getType(), 1);
9747 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009748 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009749 Scale = CI;
9750 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9751 if (Inst->getOpcode() == Instruction::Shl &&
9752 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009753 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9754 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9755 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009756 NewIdx = Inst->getOperand(0);
9757 } else if (Inst->getOpcode() == Instruction::Mul &&
9758 isa<ConstantInt>(Inst->getOperand(1))) {
9759 Scale = cast<ConstantInt>(Inst->getOperand(1));
9760 NewIdx = Inst->getOperand(0);
9761 }
9762 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009763
Chris Lattner7835cdd2005-09-13 18:36:04 +00009764 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009765 // out, perform the transformation. Note, we don't know whether Scale is
9766 // signed or not. We'll use unsigned version of division/modulo
9767 // operation after making sure Scale doesn't have the sign bit set.
9768 if (Scale && Scale->getSExtValue() >= 0LL &&
9769 Scale->getZExtValue() % ArrayEltSize == 0) {
9770 Scale = ConstantInt::get(Scale->getType(),
9771 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009772 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009773 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009774 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009775 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009776 NewIdx = InsertNewInstBefore(Sc, GEP);
9777 }
9778
9779 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009780 Value *Idx[2];
9781 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9782 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009783 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009784 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009785 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9786 // The NewGEP must be pointer typed, so must the old one -> BitCast
9787 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009788 }
9789 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009790 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009791 }
9792
Chris Lattner8a2a3112001-12-14 16:52:21 +00009793 return 0;
9794}
9795
Chris Lattner0864acf2002-11-04 16:18:53 +00009796Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9797 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009798 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009799 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9800 const Type *NewTy =
9801 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009802 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009803
9804 // Create and insert the replacement instruction...
9805 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009806 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009807 else {
9808 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009809 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009810 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009811
9812 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009813
Chris Lattner0864acf2002-11-04 16:18:53 +00009814 // Scan to the end of the allocation instructions, to skip over a block of
9815 // allocas if possible...
9816 //
9817 BasicBlock::iterator It = New;
9818 while (isa<AllocationInst>(*It)) ++It;
9819
9820 // Now that I is pointing to the first non-allocation-inst in the block,
9821 // insert our getelementptr instruction...
9822 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009823 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009824 Value *Idx[2];
9825 Idx[0] = NullIdx;
9826 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009827 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9828 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009829
9830 // Now make everything use the getelementptr instead of the original
9831 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009832 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009833 } else if (isa<UndefValue>(AI.getArraySize())) {
9834 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009835 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009836 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009837
9838 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9839 // Note that we only do this for alloca's, because malloc should allocate and
9840 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009841 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009842 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009843 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9844
Chris Lattner0864acf2002-11-04 16:18:53 +00009845 return 0;
9846}
9847
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009848Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9849 Value *Op = FI.getOperand(0);
9850
Chris Lattner17be6352004-10-18 02:59:09 +00009851 // free undef -> unreachable.
9852 if (isa<UndefValue>(Op)) {
9853 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009854 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009855 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009856 return EraseInstFromFunction(FI);
9857 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009858
Chris Lattner6160e852004-02-28 04:57:37 +00009859 // If we have 'free null' delete the instruction. This can happen in stl code
9860 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009861 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009862 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009863
9864 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9865 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9866 FI.setOperand(0, CI->getOperand(0));
9867 return &FI;
9868 }
9869
9870 // Change free (gep X, 0,0,0,0) into free(X)
9871 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9872 if (GEPI->hasAllZeroIndices()) {
9873 AddToWorkList(GEPI);
9874 FI.setOperand(0, GEPI->getOperand(0));
9875 return &FI;
9876 }
9877 }
9878
9879 // Change free(malloc) into nothing, if the malloc has a single use.
9880 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9881 if (MI->hasOneUse()) {
9882 EraseInstFromFunction(FI);
9883 return EraseInstFromFunction(*MI);
9884 }
Chris Lattner6160e852004-02-28 04:57:37 +00009885
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009886 return 0;
9887}
9888
9889
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009890/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009891static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009892 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009893 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009894 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009895
Devang Patel99db6ad2007-10-18 19:52:32 +00009896 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9897 // Instead of loading constant c string, use corresponding integer value
9898 // directly if string length is small enough.
9899 const std::string &Str = CE->getOperand(0)->getStringValue();
9900 if (!Str.empty()) {
9901 unsigned len = Str.length();
9902 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9903 unsigned numBits = Ty->getPrimitiveSizeInBits();
9904 // Replace LI with immediate integer store.
9905 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009906 APInt StrVal(numBits, 0);
9907 APInt SingleChar(numBits, 0);
9908 if (TD->isLittleEndian()) {
9909 for (signed i = len-1; i >= 0; i--) {
9910 SingleChar = (uint64_t) Str[i];
9911 StrVal = (StrVal << 8) | SingleChar;
9912 }
9913 } else {
9914 for (unsigned i = 0; i < len; i++) {
9915 SingleChar = (uint64_t) Str[i];
9916 StrVal = (StrVal << 8) | SingleChar;
9917 }
9918 // Append NULL at the end.
9919 SingleChar = 0;
9920 StrVal = (StrVal << 8) | SingleChar;
9921 }
9922 Value *NL = ConstantInt::get(StrVal);
9923 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009924 }
9925 }
9926 }
9927
Chris Lattnerb89e0712004-07-13 01:49:43 +00009928 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009929 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009930 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009931
Reid Spencer42230162007-01-22 05:51:25 +00009932 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009933 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009934 // If the source is an array, the code below will not succeed. Check to
9935 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9936 // constants.
9937 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9938 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9939 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009940 Value *Idxs[2];
9941 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9942 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009943 SrcTy = cast<PointerType>(CastOp->getType());
9944 SrcPTy = SrcTy->getElementType();
9945 }
9946
Reid Spencer42230162007-01-22 05:51:25 +00009947 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009948 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009949 // Do not allow turning this into a load of an integer, which is then
9950 // casted to a pointer, this pessimizes pointer analysis a lot.
9951 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009952 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9953 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009954
Chris Lattnerf9527852005-01-31 04:50:46 +00009955 // Okay, we are casting from one integer or pointer type to another of
9956 // the same size. Instead of casting the pointer before the load, cast
9957 // the result of the loaded value.
9958 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9959 CI->getName(),
9960 LI.isVolatile()),LI);
9961 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009962 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009963 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009964 }
9965 }
9966 return 0;
9967}
9968
Chris Lattnerc10aced2004-09-19 18:43:46 +00009969/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009970/// from this value cannot trap. If it is not obviously safe to load from the
9971/// specified pointer, we do a quick local scan of the basic block containing
9972/// ScanFrom, to determine if the address is already accessed.
9973static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009974 // If it is an alloca it is always safe to load from.
9975 if (isa<AllocaInst>(V)) return true;
9976
Duncan Sands46318cd2007-09-19 10:25:38 +00009977 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009978 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009979 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009980 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009981
9982 // Otherwise, be a little bit agressive by scanning the local block where we
9983 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009984 // from/to. If so, the previous load or store would have already trapped,
9985 // so there is no harm doing an extra load (also, CSE will later eliminate
9986 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009987 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9988
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009989 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009990 --BBI;
9991
9992 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9993 if (LI->getOperand(0) == V) return true;
9994 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9995 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009996
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009997 }
Chris Lattner8a375202004-09-19 19:18:10 +00009998 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009999}
10000
Chris Lattner8d2e8882007-08-11 18:48:48 +000010001/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10002/// until we find the underlying object a pointer is referring to or something
10003/// we don't understand. Note that the returned pointer may be offset from the
10004/// input, because we ignore GEP indices.
10005static Value *GetUnderlyingObject(Value *Ptr) {
10006 while (1) {
10007 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10008 if (CE->getOpcode() == Instruction::BitCast ||
10009 CE->getOpcode() == Instruction::GetElementPtr)
10010 Ptr = CE->getOperand(0);
10011 else
10012 return Ptr;
10013 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10014 Ptr = BCI->getOperand(0);
10015 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10016 Ptr = GEP->getOperand(0);
10017 } else {
10018 return Ptr;
10019 }
10020 }
10021}
10022
Chris Lattner833b8a42003-06-26 05:06:25 +000010023Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10024 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010025
Dan Gohman9941f742007-07-20 16:34:21 +000010026 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010027 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10028 if (KnownAlign >
10029 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10030 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010031 LI.setAlignment(KnownAlign);
10032
Chris Lattner37366c12005-05-01 04:24:53 +000010033 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010034 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010035 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010036 return Res;
10037
10038 // None of the following transforms are legal for volatile loads.
10039 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010040
Chris Lattner62f254d2005-09-12 22:00:15 +000010041 if (&LI.getParent()->front() != &LI) {
10042 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010043 // If the instruction immediately before this is a store to the same
10044 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010045 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10046 if (SI->getOperand(1) == LI.getOperand(0))
10047 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010048 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10049 if (LIB->getOperand(0) == LI.getOperand(0))
10050 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010051 }
Chris Lattner37366c12005-05-01 04:24:53 +000010052
Christopher Lambb15147e2007-12-29 07:56:53 +000010053 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10054 const Value *GEPI0 = GEPI->getOperand(0);
10055 // TODO: Consider a target hook for valid address spaces for this xform.
10056 if (isa<ConstantPointerNull>(GEPI0) &&
10057 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010058 // Insert a new store to null instruction before the load to indicate
10059 // that this code is not reachable. We do this instead of inserting
10060 // an unreachable instruction directly because we cannot modify the
10061 // CFG.
10062 new StoreInst(UndefValue::get(LI.getType()),
10063 Constant::getNullValue(Op->getType()), &LI);
10064 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10065 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010066 }
Chris Lattner37366c12005-05-01 04:24:53 +000010067
Chris Lattnere87597f2004-10-16 18:11:37 +000010068 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010069 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010070 // TODO: Consider a target hook for valid address spaces for this xform.
10071 if (isa<UndefValue>(C) || (C->isNullValue() &&
10072 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010073 // Insert a new store to null instruction before the load to indicate that
10074 // this code is not reachable. We do this instead of inserting an
10075 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010076 new StoreInst(UndefValue::get(LI.getType()),
10077 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010078 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010079 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010080
Chris Lattnere87597f2004-10-16 18:11:37 +000010081 // Instcombine load (constant global) into the value loaded.
10082 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010083 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010084 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010085
Chris Lattnere87597f2004-10-16 18:11:37 +000010086 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010087 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010088 if (CE->getOpcode() == Instruction::GetElementPtr) {
10089 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010090 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010091 if (Constant *V =
10092 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010093 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010094 if (CE->getOperand(0)->isNullValue()) {
10095 // Insert a new store to null instruction before the load to indicate
10096 // that this code is not reachable. We do this instead of inserting
10097 // an unreachable instruction directly because we cannot modify the
10098 // CFG.
10099 new StoreInst(UndefValue::get(LI.getType()),
10100 Constant::getNullValue(Op->getType()), &LI);
10101 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10102 }
10103
Reid Spencer3da59db2006-11-27 01:05:10 +000010104 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010105 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010106 return Res;
10107 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010108 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010109 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010110
10111 // If this load comes from anywhere in a constant global, and if the global
10112 // is all undef or zero, we know what it loads.
10113 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10114 if (GV->isConstant() && GV->hasInitializer()) {
10115 if (GV->getInitializer()->isNullValue())
10116 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10117 else if (isa<UndefValue>(GV->getInitializer()))
10118 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10119 }
10120 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010121
Chris Lattner37366c12005-05-01 04:24:53 +000010122 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010123 // Change select and PHI nodes to select values instead of addresses: this
10124 // helps alias analysis out a lot, allows many others simplifications, and
10125 // exposes redundancy in the code.
10126 //
10127 // Note that we cannot do the transformation unless we know that the
10128 // introduced loads cannot trap! Something like this is valid as long as
10129 // the condition is always false: load (select bool %C, int* null, int* %G),
10130 // but it would not be valid if we transformed it to load from null
10131 // unconditionally.
10132 //
10133 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10134 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010135 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10136 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010137 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010138 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010139 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010140 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010141 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010142 }
10143
Chris Lattner684fe212004-09-23 15:46:00 +000010144 // load (select (cond, null, P)) -> load P
10145 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10146 if (C->isNullValue()) {
10147 LI.setOperand(0, SI->getOperand(2));
10148 return &LI;
10149 }
10150
10151 // load (select (cond, P, null)) -> load P
10152 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10153 if (C->isNullValue()) {
10154 LI.setOperand(0, SI->getOperand(1));
10155 return &LI;
10156 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010157 }
10158 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010159 return 0;
10160}
10161
Reid Spencer55af2b52007-01-19 21:20:31 +000010162/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010163/// when possible.
10164static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10165 User *CI = cast<User>(SI.getOperand(1));
10166 Value *CastOp = CI->getOperand(0);
10167
10168 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10169 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10170 const Type *SrcPTy = SrcTy->getElementType();
10171
Reid Spencer42230162007-01-22 05:51:25 +000010172 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010173 // If the source is an array, the code below will not succeed. Check to
10174 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10175 // constants.
10176 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10177 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10178 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010179 Value* Idxs[2];
10180 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10181 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010182 SrcTy = cast<PointerType>(CastOp->getType());
10183 SrcPTy = SrcTy->getElementType();
10184 }
10185
Reid Spencer67f827c2007-01-20 23:35:48 +000010186 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10187 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10188 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010189
10190 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010191 // the same size. Instead of casting the pointer before
10192 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010193 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010194 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010195 Instruction::CastOps opcode = Instruction::BitCast;
10196 const Type* CastSrcTy = SIOp0->getType();
10197 const Type* CastDstTy = SrcPTy;
10198 if (isa<PointerType>(CastDstTy)) {
10199 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010200 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010201 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010202 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010203 opcode = Instruction::PtrToInt;
10204 }
10205 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010206 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010207 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010208 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010209 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010210 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010211 return new StoreInst(NewCast, CastOp);
10212 }
10213 }
10214 }
10215 return 0;
10216}
10217
Chris Lattner2f503e62005-01-31 05:36:43 +000010218Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10219 Value *Val = SI.getOperand(0);
10220 Value *Ptr = SI.getOperand(1);
10221
10222 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010223 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010224 ++NumCombined;
10225 return 0;
10226 }
Chris Lattner836692d2007-01-15 06:51:56 +000010227
10228 // If the RHS is an alloca with a single use, zapify the store, making the
10229 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010230 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010231 if (isa<AllocaInst>(Ptr)) {
10232 EraseInstFromFunction(SI);
10233 ++NumCombined;
10234 return 0;
10235 }
10236
10237 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10238 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10239 GEP->getOperand(0)->hasOneUse()) {
10240 EraseInstFromFunction(SI);
10241 ++NumCombined;
10242 return 0;
10243 }
10244 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010245
Dan Gohman9941f742007-07-20 16:34:21 +000010246 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010247 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10248 if (KnownAlign >
10249 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10250 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010251 SI.setAlignment(KnownAlign);
10252
Chris Lattner9ca96412006-02-08 03:25:32 +000010253 // Do really simple DSE, to catch cases where there are several consequtive
10254 // stores to the same location, separated by a few arithmetic operations. This
10255 // situation often occurs with bitfield accesses.
10256 BasicBlock::iterator BBI = &SI;
10257 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10258 --ScanInsts) {
10259 --BBI;
10260
10261 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10262 // Prev store isn't volatile, and stores to the same location?
10263 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10264 ++NumDeadStore;
10265 ++BBI;
10266 EraseInstFromFunction(*PrevSI);
10267 continue;
10268 }
10269 break;
10270 }
10271
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010272 // If this is a load, we have to stop. However, if the loaded value is from
10273 // the pointer we're loading and is producing the pointer we're storing,
10274 // then *this* store is dead (X = load P; store X -> P).
10275 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010276 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010277 EraseInstFromFunction(SI);
10278 ++NumCombined;
10279 return 0;
10280 }
10281 // Otherwise, this is a load from some other location. Stores before it
10282 // may not be dead.
10283 break;
10284 }
10285
Chris Lattner9ca96412006-02-08 03:25:32 +000010286 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010287 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010288 break;
10289 }
10290
10291
10292 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010293
10294 // store X, null -> turns into 'unreachable' in SimplifyCFG
10295 if (isa<ConstantPointerNull>(Ptr)) {
10296 if (!isa<UndefValue>(Val)) {
10297 SI.setOperand(0, UndefValue::get(Val->getType()));
10298 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010299 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010300 ++NumCombined;
10301 }
10302 return 0; // Do not modify these!
10303 }
10304
10305 // store undef, Ptr -> noop
10306 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010307 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010308 ++NumCombined;
10309 return 0;
10310 }
10311
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010312 // If the pointer destination is a cast, see if we can fold the cast into the
10313 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010314 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010315 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10316 return Res;
10317 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010318 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010319 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10320 return Res;
10321
Chris Lattner408902b2005-09-12 23:23:25 +000010322
10323 // If this store is the last instruction in the basic block, and if the block
10324 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010325 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010326 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010327 if (BI->isUnconditional())
10328 if (SimplifyStoreAtEndOfBlock(SI))
10329 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010330
Chris Lattner2f503e62005-01-31 05:36:43 +000010331 return 0;
10332}
10333
Chris Lattner3284d1f2007-04-15 00:07:55 +000010334/// SimplifyStoreAtEndOfBlock - Turn things like:
10335/// if () { *P = v1; } else { *P = v2 }
10336/// into a phi node with a store in the successor.
10337///
Chris Lattner31755a02007-04-15 01:02:18 +000010338/// Simplify things like:
10339/// *P = v1; if () { *P = v2; }
10340/// into a phi node with a store in the successor.
10341///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010342bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10343 BasicBlock *StoreBB = SI.getParent();
10344
10345 // Check to see if the successor block has exactly two incoming edges. If
10346 // so, see if the other predecessor contains a store to the same location.
10347 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010348 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010349
10350 // Determine whether Dest has exactly two predecessors and, if so, compute
10351 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010352 pred_iterator PI = pred_begin(DestBB);
10353 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010354 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010355 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010356 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010357 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010358 return false;
10359
10360 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010361 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010362 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010363 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010364 }
Chris Lattner31755a02007-04-15 01:02:18 +000010365 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010366 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000010367
10368 // Bail out if all the relevant blocks aren't distinct (this can happen,
10369 // for example, if SI is in an infinite loop)
10370 if (StoreBB == DestBB || OtherBB == DestBB)
10371 return false;
10372
Chris Lattner31755a02007-04-15 01:02:18 +000010373 // Verify that the other block ends in a branch and is not otherwise empty.
10374 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010375 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010376 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010377 return false;
10378
Chris Lattner31755a02007-04-15 01:02:18 +000010379 // If the other block ends in an unconditional branch, check for the 'if then
10380 // else' case. there is an instruction before the branch.
10381 StoreInst *OtherStore = 0;
10382 if (OtherBr->isUnconditional()) {
10383 // If this isn't a store, or isn't a store to the same location, bail out.
10384 --BBI;
10385 OtherStore = dyn_cast<StoreInst>(BBI);
10386 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10387 return false;
10388 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010389 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010390 // destinations is StoreBB, then we have the if/then case.
10391 if (OtherBr->getSuccessor(0) != StoreBB &&
10392 OtherBr->getSuccessor(1) != StoreBB)
10393 return false;
10394
10395 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010396 // if/then triangle. See if there is a store to the same ptr as SI that
10397 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010398 for (;; --BBI) {
10399 // Check to see if we find the matching store.
10400 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10401 if (OtherStore->getOperand(1) != SI.getOperand(1))
10402 return false;
10403 break;
10404 }
Eli Friedman6903a242008-06-13 22:02:12 +000010405 // If we find something that may be using or overwriting the stored
10406 // value, or if we run out of instructions, we can't do the xform.
10407 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000010408 BBI == OtherBB->begin())
10409 return false;
10410 }
10411
10412 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000010413 // make sure nothing reads or overwrites the stored value in
10414 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010415 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10416 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000010417 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000010418 return false;
10419 }
10420 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010421
Chris Lattner31755a02007-04-15 01:02:18 +000010422 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010423 Value *MergedVal = OtherStore->getOperand(0);
10424 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010425 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010426 PN->reserveOperandSpace(2);
10427 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010428 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10429 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010430 }
10431
10432 // Advance to a place where it is safe to insert the new store and
10433 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010434 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010435 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10436 OtherStore->isVolatile()), *BBI);
10437
10438 // Nuke the old stores.
10439 EraseInstFromFunction(SI);
10440 EraseInstFromFunction(*OtherStore);
10441 ++NumCombined;
10442 return true;
10443}
10444
Chris Lattner2f503e62005-01-31 05:36:43 +000010445
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010446Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10447 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010448 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010449 BasicBlock *TrueDest;
10450 BasicBlock *FalseDest;
10451 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10452 !isa<Constant>(X)) {
10453 // Swap Destinations and condition...
10454 BI.setCondition(X);
10455 BI.setSuccessor(0, FalseDest);
10456 BI.setSuccessor(1, TrueDest);
10457 return &BI;
10458 }
10459
Reid Spencere4d87aa2006-12-23 06:05:41 +000010460 // Cannonicalize fcmp_one -> fcmp_oeq
10461 FCmpInst::Predicate FPred; Value *Y;
10462 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10463 TrueDest, FalseDest)))
10464 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10465 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10466 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010467 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010468 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10469 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010470 // Swap Destinations and condition...
10471 BI.setCondition(NewSCC);
10472 BI.setSuccessor(0, FalseDest);
10473 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010474 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010475 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010476 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010477 return &BI;
10478 }
10479
10480 // Cannonicalize icmp_ne -> icmp_eq
10481 ICmpInst::Predicate IPred;
10482 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10483 TrueDest, FalseDest)))
10484 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10485 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10486 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10487 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010488 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010489 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10490 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010491 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010492 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010493 BI.setSuccessor(0, FalseDest);
10494 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010495 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010496 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010497 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010498 return &BI;
10499 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010500
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010501 return 0;
10502}
Chris Lattner0864acf2002-11-04 16:18:53 +000010503
Chris Lattner46238a62004-07-03 00:26:11 +000010504Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10505 Value *Cond = SI.getCondition();
10506 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10507 if (I->getOpcode() == Instruction::Add)
10508 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10509 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10510 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010511 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010512 AddRHS));
10513 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010514 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010515 return &SI;
10516 }
10517 }
10518 return 0;
10519}
10520
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010521Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10522 // See if we are trying to extract a known value. If so, use that instead.
Matthijs Kooijman710eb232008-06-16 12:57:37 +000010523 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +000010524 EV.idx_end(), &EV))
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010525 return ReplaceInstUsesWith(EV, Elt);
10526
10527 // No changes
10528 return 0;
10529}
10530
Chris Lattner220b0cf2006-03-05 00:22:33 +000010531/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10532/// is to leave as a vector operation.
10533static bool CheapToScalarize(Value *V, bool isConstant) {
10534 if (isa<ConstantAggregateZero>(V))
10535 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010536 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010537 if (isConstant) return true;
10538 // If all elts are the same, we can extract.
10539 Constant *Op0 = C->getOperand(0);
10540 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10541 if (C->getOperand(i) != Op0)
10542 return false;
10543 return true;
10544 }
10545 Instruction *I = dyn_cast<Instruction>(V);
10546 if (!I) return false;
10547
10548 // Insert element gets simplified to the inserted element or is deleted if
10549 // this is constant idx extract element and its a constant idx insertelt.
10550 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10551 isa<ConstantInt>(I->getOperand(2)))
10552 return true;
10553 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10554 return true;
10555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10556 if (BO->hasOneUse() &&
10557 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10558 CheapToScalarize(BO->getOperand(1), isConstant)))
10559 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010560 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10561 if (CI->hasOneUse() &&
10562 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10563 CheapToScalarize(CI->getOperand(1), isConstant)))
10564 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010565
10566 return false;
10567}
10568
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010569/// Read and decode a shufflevector mask.
10570///
10571/// It turns undef elements into values that are larger than the number of
10572/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010573static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10574 unsigned NElts = SVI->getType()->getNumElements();
10575 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10576 return std::vector<unsigned>(NElts, 0);
10577 if (isa<UndefValue>(SVI->getOperand(2)))
10578 return std::vector<unsigned>(NElts, 2*NElts);
10579
10580 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010581 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000010582 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10583 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000010584 Result.push_back(NElts*2); // undef -> 8
10585 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000010586 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010587 return Result;
10588}
10589
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010590/// FindScalarElement - Given a vector and an element number, see if the scalar
10591/// value is already around as a register, for example if it were inserted then
10592/// extracted from the vector.
10593static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010594 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10595 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010596 unsigned Width = PTy->getNumElements();
10597 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010598 return UndefValue::get(PTy->getElementType());
10599
10600 if (isa<UndefValue>(V))
10601 return UndefValue::get(PTy->getElementType());
10602 else if (isa<ConstantAggregateZero>(V))
10603 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010604 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010605 return CP->getOperand(EltNo);
10606 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10607 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010608 if (!isa<ConstantInt>(III->getOperand(2)))
10609 return 0;
10610 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010611
10612 // If this is an insert to the element we are looking for, return the
10613 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010614 if (EltNo == IIElt)
10615 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010616
10617 // Otherwise, the insertelement doesn't modify the value, recurse on its
10618 // vector input.
10619 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010620 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010621 unsigned InEl = getShuffleMask(SVI)[EltNo];
10622 if (InEl < Width)
10623 return FindScalarElement(SVI->getOperand(0), InEl);
10624 else if (InEl < Width*2)
10625 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10626 else
10627 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010628 }
10629
10630 // Otherwise, we don't know.
10631 return 0;
10632}
10633
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010634Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010635 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010636 if (isa<UndefValue>(EI.getOperand(0)))
10637 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10638
Dan Gohman07a96762007-07-16 14:29:03 +000010639 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010640 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10641 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10642
Reid Spencer9d6565a2007-02-15 02:26:10 +000010643 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010644 // If vector val is constant with all elements the same, replace EI with
10645 // that element. When the elements are not identical, we cannot replace yet
10646 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010647 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010648 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010649 if (C->getOperand(i) != op0) {
10650 op0 = 0;
10651 break;
10652 }
10653 if (op0)
10654 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010655 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010656
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010657 // If extracting a specified index from the vector, see if we can recursively
10658 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010659 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010660 unsigned IndexVal = IdxC->getZExtValue();
10661 unsigned VectorWidth =
10662 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10663
10664 // If this is extracting an invalid index, turn this into undef, to avoid
10665 // crashing the code below.
10666 if (IndexVal >= VectorWidth)
10667 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10668
Chris Lattner867b99f2006-10-05 06:55:50 +000010669 // This instruction only demands the single element from the input vector.
10670 // If the input vector has a single use, simplify it based on this use
10671 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010672 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010673 uint64_t UndefElts;
10674 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010675 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010676 UndefElts)) {
10677 EI.setOperand(0, V);
10678 return &EI;
10679 }
10680 }
10681
Reid Spencerb83eb642006-10-20 07:07:24 +000010682 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010683 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010684
10685 // If the this extractelement is directly using a bitcast from a vector of
10686 // the same number of elements, see if we can find the source element from
10687 // it. In this case, we will end up needing to bitcast the scalars.
10688 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10689 if (const VectorType *VT =
10690 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10691 if (VT->getNumElements() == VectorWidth)
10692 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10693 return new BitCastInst(Elt, EI.getType());
10694 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010695 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010696
Chris Lattner73fa49d2006-05-25 22:53:38 +000010697 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010698 if (I->hasOneUse()) {
10699 // Push extractelement into predecessor operation if legal and
10700 // profitable to do so
10701 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010702 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10703 if (CheapToScalarize(BO, isConstantElt)) {
10704 ExtractElementInst *newEI0 =
10705 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10706 EI.getName()+".lhs");
10707 ExtractElementInst *newEI1 =
10708 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10709 EI.getName()+".rhs");
10710 InsertNewInstBefore(newEI0, EI);
10711 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010712 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010713 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010714 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010715 unsigned AS =
10716 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010717 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10718 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010719 GetElementPtrInst *GEP =
10720 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010721 InsertNewInstBefore(GEP, EI);
10722 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010723 }
10724 }
10725 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10726 // Extracting the inserted element?
10727 if (IE->getOperand(2) == EI.getOperand(1))
10728 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10729 // If the inserted and extracted elements are constants, they must not
10730 // be the same value, extract from the pre-inserted value instead.
10731 if (isa<Constant>(IE->getOperand(2)) &&
10732 isa<Constant>(EI.getOperand(1))) {
10733 AddUsesToWorkList(EI);
10734 EI.setOperand(0, IE->getOperand(0));
10735 return &EI;
10736 }
10737 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10738 // If this is extracting an element from a shufflevector, figure out where
10739 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010740 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10741 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010742 Value *Src;
10743 if (SrcIdx < SVI->getType()->getNumElements())
10744 Src = SVI->getOperand(0);
10745 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10746 SrcIdx -= SVI->getType()->getNumElements();
10747 Src = SVI->getOperand(1);
10748 } else {
10749 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010750 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010751 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010752 }
10753 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010754 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010755 return 0;
10756}
10757
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010758/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10759/// elements from either LHS or RHS, return the shuffle mask and true.
10760/// Otherwise, return false.
10761static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10762 std::vector<Constant*> &Mask) {
10763 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10764 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010765 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010766
10767 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010768 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010769 return true;
10770 } else if (V == LHS) {
10771 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010772 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010773 return true;
10774 } else if (V == RHS) {
10775 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010776 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010777 return true;
10778 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10779 // If this is an insert of an extract from some other vector, include it.
10780 Value *VecOp = IEI->getOperand(0);
10781 Value *ScalarOp = IEI->getOperand(1);
10782 Value *IdxOp = IEI->getOperand(2);
10783
Chris Lattnerd929f062006-04-27 21:14:21 +000010784 if (!isa<ConstantInt>(IdxOp))
10785 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010786 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010787
10788 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10789 // Okay, we can handle this if the vector we are insertinting into is
10790 // transitively ok.
10791 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10792 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010793 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010794 return true;
10795 }
10796 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10797 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010798 EI->getOperand(0)->getType() == V->getType()) {
10799 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010800 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010801
10802 // This must be extracting from either LHS or RHS.
10803 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10804 // Okay, we can handle this if the vector we are insertinting into is
10805 // transitively ok.
10806 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10807 // If so, update the mask to reflect the inserted value.
10808 if (EI->getOperand(0) == LHS) {
10809 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010810 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010811 } else {
10812 assert(EI->getOperand(0) == RHS);
10813 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010814 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010815
10816 }
10817 return true;
10818 }
10819 }
10820 }
10821 }
10822 }
10823 // TODO: Handle shufflevector here!
10824
10825 return false;
10826}
10827
10828/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10829/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10830/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010831static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010832 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010833 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010834 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010835 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010836 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010837
10838 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010839 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010840 return V;
10841 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010842 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010843 return V;
10844 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10845 // If this is an insert of an extract from some other vector, include it.
10846 Value *VecOp = IEI->getOperand(0);
10847 Value *ScalarOp = IEI->getOperand(1);
10848 Value *IdxOp = IEI->getOperand(2);
10849
10850 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10851 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10852 EI->getOperand(0)->getType() == V->getType()) {
10853 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010854 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10855 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010856
10857 // Either the extracted from or inserted into vector must be RHSVec,
10858 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010859 if (EI->getOperand(0) == RHS || RHS == 0) {
10860 RHS = EI->getOperand(0);
10861 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010862 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010863 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010864 return V;
10865 }
10866
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010867 if (VecOp == RHS) {
10868 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010869 // Everything but the extracted element is replaced with the RHS.
10870 for (unsigned i = 0; i != NumElts; ++i) {
10871 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010872 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010873 }
10874 return V;
10875 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010876
10877 // If this insertelement is a chain that comes from exactly these two
10878 // vectors, return the vector and the effective shuffle.
10879 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10880 return EI->getOperand(0);
10881
Chris Lattnerefb47352006-04-15 01:39:45 +000010882 }
10883 }
10884 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010885 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010886
10887 // Otherwise, can't do anything fancy. Return an identity vector.
10888 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010889 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010890 return V;
10891}
10892
10893Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10894 Value *VecOp = IE.getOperand(0);
10895 Value *ScalarOp = IE.getOperand(1);
10896 Value *IdxOp = IE.getOperand(2);
10897
Chris Lattner599ded12007-04-09 01:11:16 +000010898 // Inserting an undef or into an undefined place, remove this.
10899 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10900 ReplaceInstUsesWith(IE, VecOp);
10901
Chris Lattnerefb47352006-04-15 01:39:45 +000010902 // If the inserted element was extracted from some other vector, and if the
10903 // indexes are constant, try to turn this into a shufflevector operation.
10904 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10905 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10906 EI->getOperand(0)->getType() == IE.getType()) {
10907 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010908 unsigned ExtractedIdx =
10909 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010910 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010911
10912 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10913 return ReplaceInstUsesWith(IE, VecOp);
10914
10915 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10916 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10917
10918 // If we are extracting a value from a vector, then inserting it right
10919 // back into the same place, just use the input vector.
10920 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10921 return ReplaceInstUsesWith(IE, VecOp);
10922
10923 // We could theoretically do this for ANY input. However, doing so could
10924 // turn chains of insertelement instructions into a chain of shufflevector
10925 // instructions, and right now we do not merge shufflevectors. As such,
10926 // only do this in a situation where it is clear that there is benefit.
10927 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10928 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10929 // the values of VecOp, except then one read from EIOp0.
10930 // Build a new shuffle mask.
10931 std::vector<Constant*> Mask;
10932 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010933 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010934 else {
10935 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010936 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010937 NumVectorElts));
10938 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010939 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010940 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010941 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010942 }
10943
10944 // If this insertelement isn't used by some other insertelement, turn it
10945 // (and any insertelements it points to), into one big shuffle.
10946 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10947 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010948 Value *RHS = 0;
10949 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10950 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10951 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010952 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010953 }
10954 }
10955 }
10956
10957 return 0;
10958}
10959
10960
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010961Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10962 Value *LHS = SVI.getOperand(0);
10963 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010964 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010965
10966 bool MadeChange = false;
10967
Chris Lattner867b99f2006-10-05 06:55:50 +000010968 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010969 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010970 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10971
Chris Lattnere4929dd2007-01-05 07:36:08 +000010972 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010973 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010974 if (isa<UndefValue>(SVI.getOperand(1))) {
10975 // Scan to see if there are any references to the RHS. If so, replace them
10976 // with undef element refs and set MadeChange to true.
10977 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10978 if (Mask[i] >= e && Mask[i] != 2*e) {
10979 Mask[i] = 2*e;
10980 MadeChange = true;
10981 }
10982 }
10983
10984 if (MadeChange) {
10985 // Remap any references to RHS to use LHS.
10986 std::vector<Constant*> Elts;
10987 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10988 if (Mask[i] == 2*e)
10989 Elts.push_back(UndefValue::get(Type::Int32Ty));
10990 else
10991 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10992 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010993 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010994 }
10995 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010996
Chris Lattner863bcff2006-05-25 23:48:38 +000010997 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10998 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10999 if (LHS == RHS || isa<UndefValue>(LHS)) {
11000 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011001 // shuffle(undef,undef,mask) -> undef.
11002 return ReplaceInstUsesWith(SVI, LHS);
11003 }
11004
Chris Lattner863bcff2006-05-25 23:48:38 +000011005 // Remap any references to RHS to use LHS.
11006 std::vector<Constant*> Elts;
11007 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011008 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011009 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011010 else {
11011 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11012 (Mask[i] < e && isa<UndefValue>(LHS)))
11013 Mask[i] = 2*e; // Turn into undef.
11014 else
11015 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011016 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011017 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011018 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011019 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011020 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011021 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011022 LHS = SVI.getOperand(0);
11023 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011024 MadeChange = true;
11025 }
11026
Chris Lattner7b2e27922006-05-26 00:29:06 +000011027 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011028 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011029
Chris Lattner863bcff2006-05-25 23:48:38 +000011030 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11031 if (Mask[i] >= e*2) continue; // Ignore undef values.
11032 // Is this an identity shuffle of the LHS value?
11033 isLHSID &= (Mask[i] == i);
11034
11035 // Is this an identity shuffle of the RHS value?
11036 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011037 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011038
Chris Lattner863bcff2006-05-25 23:48:38 +000011039 // Eliminate identity shuffles.
11040 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11041 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011042
Chris Lattner7b2e27922006-05-26 00:29:06 +000011043 // If the LHS is a shufflevector itself, see if we can combine it with this
11044 // one without producing an unusual shuffle. Here we are really conservative:
11045 // we are absolutely afraid of producing a shuffle mask not in the input
11046 // program, because the code gen may not be smart enough to turn a merged
11047 // shuffle into two specific shuffles: it may produce worse code. As such,
11048 // we only merge two shuffles if the result is one of the two input shuffle
11049 // masks. In this case, merging the shuffles just removes one instruction,
11050 // which we know is safe. This is good for things like turning:
11051 // (splat(splat)) -> splat.
11052 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11053 if (isa<UndefValue>(RHS)) {
11054 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11055
11056 std::vector<unsigned> NewMask;
11057 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11058 if (Mask[i] >= 2*e)
11059 NewMask.push_back(2*e);
11060 else
11061 NewMask.push_back(LHSMask[Mask[i]]);
11062
11063 // If the result mask is equal to the src shuffle or this shuffle mask, do
11064 // the replacement.
11065 if (NewMask == LHSMask || NewMask == Mask) {
11066 std::vector<Constant*> Elts;
11067 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11068 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011069 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011070 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011071 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011072 }
11073 }
11074 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11075 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011076 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011077 }
11078 }
11079 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011080
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011081 return MadeChange ? &SVI : 0;
11082}
11083
11084
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011085
Chris Lattnerea1c4542004-12-08 23:43:58 +000011086
11087/// TryToSinkInstruction - Try to move the specified instruction from its
11088/// current block into the beginning of DestBlock, which can only happen if it's
11089/// safe to move the instruction past all of the instructions between it and the
11090/// end of its block.
11091static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11092 assert(I->hasOneUse() && "Invariants didn't hold!");
11093
Chris Lattner108e9022005-10-27 17:13:11 +000011094 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011095 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11096 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011097
Chris Lattnerea1c4542004-12-08 23:43:58 +000011098 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011099 if (isa<AllocaInst>(I) && I->getParent() ==
11100 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011101 return false;
11102
Chris Lattner96a52a62004-12-09 07:14:34 +000011103 // We can only sink load instructions if there is nothing between the load and
11104 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011105 if (I->mayReadFromMemory()) {
11106 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011107 Scan != E; ++Scan)
11108 if (Scan->mayWriteToMemory())
11109 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011110 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011111
Dan Gohman02dea8b2008-05-23 21:05:58 +000011112 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011113
Chris Lattner4bc5f802005-08-08 19:11:57 +000011114 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011115 ++NumSunkInst;
11116 return true;
11117}
11118
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011119
11120/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11121/// all reachable code to the worklist.
11122///
11123/// This has a couple of tricks to make the code faster and more powerful. In
11124/// particular, we constant fold and DCE instructions as we go, to avoid adding
11125/// them to the worklist (this significantly speeds up instcombine on code where
11126/// many instructions are dead or constant). Additionally, if we find a branch
11127/// whose condition is a known constant, we only visit the reachable successors.
11128///
11129static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011130 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011131 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011132 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011133 std::vector<BasicBlock*> Worklist;
11134 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011135
Chris Lattner2c7718a2007-03-23 19:17:18 +000011136 while (!Worklist.empty()) {
11137 BB = Worklist.back();
11138 Worklist.pop_back();
11139
11140 // We have now visited this block! If we've already been here, ignore it.
11141 if (!Visited.insert(BB)) continue;
11142
11143 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11144 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011145
Chris Lattner2c7718a2007-03-23 19:17:18 +000011146 // DCE instruction if trivially dead.
11147 if (isInstructionTriviallyDead(Inst)) {
11148 ++NumDeadInst;
11149 DOUT << "IC: DCE: " << *Inst;
11150 Inst->eraseFromParent();
11151 continue;
11152 }
11153
11154 // ConstantProp instruction if trivially constant.
11155 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11156 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11157 Inst->replaceAllUsesWith(C);
11158 ++NumConstProp;
11159 Inst->eraseFromParent();
11160 continue;
11161 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011162
Chris Lattner2c7718a2007-03-23 19:17:18 +000011163 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011164 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011165
11166 // Recursively visit successors. If this is a branch or switch on a
11167 // constant, only visit the reachable successor.
11168 TerminatorInst *TI = BB->getTerminator();
11169 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11170 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11171 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011172 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011173 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011174 continue;
11175 }
11176 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11177 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11178 // See if this is an explicit destination.
11179 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11180 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011181 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011182 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011183 continue;
11184 }
11185
11186 // Otherwise it is the default destination.
11187 Worklist.push_back(SI->getSuccessor(0));
11188 continue;
11189 }
11190 }
11191
11192 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11193 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011194 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011195}
11196
Chris Lattnerec9c3582007-03-03 02:04:50 +000011197bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011198 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011199 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011200
11201 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11202 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011203
Chris Lattnerb3d59702005-07-07 20:40:38 +000011204 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011205 // Do a depth-first traversal of the function, populate the worklist with
11206 // the reachable instructions. Ignore blocks that are not reachable. Keep
11207 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011208 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011209 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011210
Chris Lattnerb3d59702005-07-07 20:40:38 +000011211 // Do a quick scan over the function. If we find any blocks that are
11212 // unreachable, remove any instructions inside of them. This prevents
11213 // the instcombine code from having to deal with some bad special cases.
11214 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11215 if (!Visited.count(BB)) {
11216 Instruction *Term = BB->getTerminator();
11217 while (Term != BB->begin()) { // Remove instrs bottom-up
11218 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011219
Bill Wendlingb7427032006-11-26 09:46:52 +000011220 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011221 ++NumDeadInst;
11222
11223 if (!I->use_empty())
11224 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11225 I->eraseFromParent();
11226 }
11227 }
11228 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011229
Chris Lattnerdbab3862007-03-02 21:28:56 +000011230 while (!Worklist.empty()) {
11231 Instruction *I = RemoveOneFromWorkList();
11232 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011233
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011234 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011235 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011236 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011237 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011238 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011239 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011240
Bill Wendlingb7427032006-11-26 09:46:52 +000011241 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011242
11243 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011244 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011245 continue;
11246 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011247
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011248 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011249 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011250 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011251
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011252 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011253 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011254 ReplaceInstUsesWith(*I, C);
11255
Chris Lattner62b14df2002-09-02 04:59:56 +000011256 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011257 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011258 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011259 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011260 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011261
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011262 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11263 // See if we can constant fold its operands.
11264 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11265 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11266 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11267 i->set(NewC);
11268 }
11269 }
11270 }
11271
Chris Lattnerea1c4542004-12-08 23:43:58 +000011272 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011273 // FIXME: Remove GetResultInst test when first class support for aggregates
11274 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011275 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011276 BasicBlock *BB = I->getParent();
11277 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11278 if (UserParent != BB) {
11279 bool UserIsSuccessor = false;
11280 // See if the user is one of our successors.
11281 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11282 if (*SI == UserParent) {
11283 UserIsSuccessor = true;
11284 break;
11285 }
11286
11287 // If the user is one of our immediate successors, and if that successor
11288 // only has us as a predecessors (we'd have to split the critical edge
11289 // otherwise), we can keep going.
11290 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11291 next(pred_begin(UserParent)) == pred_end(UserParent))
11292 // Okay, the CFG is simple enough, try to sink this instruction.
11293 Changed |= TryToSinkInstruction(I, UserParent);
11294 }
11295 }
11296
Chris Lattner8a2a3112001-12-14 16:52:21 +000011297 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011298#ifndef NDEBUG
11299 std::string OrigI;
11300#endif
11301 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011302 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011303 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011304 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011305 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011306 DOUT << "IC: Old = " << *I
11307 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011308
Chris Lattnerf523d062004-06-09 05:08:07 +000011309 // Everything uses the new instruction now.
11310 I->replaceAllUsesWith(Result);
11311
11312 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011313 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011314 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011315
Chris Lattner6934a042007-02-11 01:23:03 +000011316 // Move the name to the new instruction first.
11317 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011318
11319 // Insert the new instruction into the basic block...
11320 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011321 BasicBlock::iterator InsertPos = I;
11322
11323 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11324 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11325 ++InsertPos;
11326
11327 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011328
Chris Lattner00d51312004-05-01 23:27:23 +000011329 // Make sure that we reprocess all operands now that we reduced their
11330 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011331 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011332
Chris Lattnerf523d062004-06-09 05:08:07 +000011333 // Instructions can end up on the worklist more than once. Make sure
11334 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011335 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011336
11337 // Erase the old instruction.
11338 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011339 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011340#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011341 DOUT << "IC: Mod = " << OrigI
11342 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011343#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011344
Chris Lattner90ac28c2002-08-02 19:29:35 +000011345 // If the instruction was modified, it's possible that it is now dead.
11346 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011347 if (isInstructionTriviallyDead(I)) {
11348 // Make sure we process all operands now that we are reducing their
11349 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011350 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011351
Chris Lattner00d51312004-05-01 23:27:23 +000011352 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011353 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011354 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011355 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011356 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011357 AddToWorkList(I);
11358 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011359 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011360 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011361 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011362 }
11363 }
11364
Chris Lattnerec9c3582007-03-03 02:04:50 +000011365 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011366
11367 // Do an explicit clear, this shrinks the map if needed.
11368 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011369 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011370}
11371
Chris Lattnerec9c3582007-03-03 02:04:50 +000011372
11373bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011374 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11375
Chris Lattnerec9c3582007-03-03 02:04:50 +000011376 bool EverMadeChange = false;
11377
11378 // Iterate while there is work to do.
11379 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011380 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011381 EverMadeChange = true;
11382 return EverMadeChange;
11383}
11384
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011385FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011386 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011387}
Brian Gaeked0fde302003-11-11 22:41:34 +000011388