blob: 481f397a3f9c30ba7ea49861ee843eaf1f046d45 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000077 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000083 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 Instruction *commonRemTransforms(BinaryOperator &I);
176 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000177 Instruction *commonDivTransforms(BinaryOperator &I);
178 Instruction *commonIDivTransforms(BinaryOperator &I);
179 Instruction *visitUDiv(BinaryOperator &I);
180 Instruction *visitSDiv(BinaryOperator &I);
181 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000182 Instruction *visitAnd(BinaryOperator &I);
183 Instruction *visitOr (BinaryOperator &I);
184 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000185 Instruction *visitShl(BinaryOperator &I);
186 Instruction *visitAShr(BinaryOperator &I);
187 Instruction *visitLShr(BinaryOperator &I);
188 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000189 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000191 Instruction *visitFCmpInst(FCmpInst &I);
192 Instruction *visitICmpInst(ICmpInst &I);
193 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000194 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195 Instruction *LHS,
196 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000199
Reid Spencere4d87aa2006-12-23 06:05:41 +0000200 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000202 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000203 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000204 Instruction *commonCastTransforms(CastInst &CI);
205 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000206 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000210 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000211 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000217 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000218 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000219 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000221 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000222 Instruction *visitCallInst(CallInst &CI);
223 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000226 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000227 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000228 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000229 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000230 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000231 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000232 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000235 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000236
237 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000239
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000241 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000242 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000243 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000244 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000246 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000247
Chris Lattner28977af2004-04-05 01:30:19 +0000248 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000249 // InsertNewInstBefore - insert an instruction New before instruction Old
250 // in the program. Add the new instruction to the worklist.
251 //
Chris Lattner955f3312004-09-28 21:48:02 +0000252 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000253 assert(New && New->getParent() == 0 &&
254 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000255 BasicBlock *BB = Old.getParent();
256 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000257 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000258 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000259 }
260
Chris Lattner0c967662004-09-24 15:21:34 +0000261 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262 /// This also adds the cast to the worklist. Finally, this returns the
263 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000264 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000266 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000267
Chris Lattnere2ed0572006-04-06 19:19:17 +0000268 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000269 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000270
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000271 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000272 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000273 return C;
274 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000275
276 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278 }
279
Chris Lattner0c967662004-09-24 15:21:34 +0000280
Chris Lattner8b170942002-08-09 23:47:40 +0000281 // ReplaceInstUsesWith - This method is to be used when an instruction is
282 // found to be dead, replacable with another preexisting expression. Here
283 // we add all uses of I to the worklist, replace all uses of I with the new
284 // value, then return I, so that the inst combiner will know that I was
285 // modified.
286 //
287 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000288 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000289 if (&I != V) {
290 I.replaceAllUsesWith(V);
291 return &I;
292 } else {
293 // If we are replacing the instruction with itself, this must be in a
294 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000295 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000296 return &I;
297 }
Chris Lattner8b170942002-08-09 23:47:40 +0000298 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000299
Chris Lattner6dce1a72006-02-07 06:56:34 +0000300 // UpdateValueUsesWith - This method is to be used when an value is
301 // found to be replacable with another preexisting expression or was
302 // updated. Here we add all uses of I to the worklist, replace all uses of
303 // I with the new value (unless the instruction was just updated), then
304 // return true, so that the inst combiner will know that I was modified.
305 //
306 bool UpdateValueUsesWith(Value *Old, Value *New) {
307 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
308 if (Old != New)
309 Old->replaceAllUsesWith(New);
310 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000311 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000312 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000313 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000314 return true;
315 }
316
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000324 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000325 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000326 return 0; // Don't do anything with FI
327 }
Chris Lattner173234a2008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000342 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000343 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344 /// InsertBefore instruction. This is specialized a bit to avoid inserting
345 /// casts that are known to not do anything...
346 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000347 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000349 Instruction *InsertBefore);
350
Reid Spencere4d87aa2006-12-23 06:05:41 +0000351 /// SimplifyCommutative - This performs a few simplifications for
352 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000353 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000354
Reid Spencere4d87aa2006-12-23 06:05:41 +0000355 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356 /// most-complex to least-complex order.
357 bool SimplifyCompare(CmpInst &I);
358
Reid Spencer2ec619a2007-03-23 21:24:59 +0000359 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000361 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
362 APInt& KnownZero, APInt& KnownOne,
363 unsigned Depth = 0);
364
Chris Lattner867b99f2006-10-05 06:55:50 +0000365 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366 uint64_t &UndefElts, unsigned Depth = 0);
367
Chris Lattner4e998b22004-09-29 05:07:12 +0000368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
Chris Lattnerbac32862004-11-14 19:13:23 +0000373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378
379
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000382
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000386 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000388 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000391 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393
Reid Spencerc55b2432006-12-13 18:21:21 +0000394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397 unsigned CastOpc,
398 int &NumCastsRemoved);
399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000401
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000402 };
403}
404
Dan Gohman844731a2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Chris Lattner4f98c562003-03-10 21:43:22 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000411static unsigned getComplexity(Value *V) {
412 if (isa<Instruction>(V)) {
413 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000414 return 3;
415 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000416 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000417 if (isa<Argument>(V)) return 3;
418 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000419}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000420
Chris Lattnerc8802d22003-03-11 00:12:48 +0000421// isOnlyUse - Return true if this instruction will be deleted if we stop using
422// it.
423static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000424 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000425}
426
Chris Lattner4cb170c2004-02-23 06:38:22 +0000427// getPromotedType - Return the specified type promoted as it would be to pass
428// though a va_arg area...
429static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000430 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431 if (ITy->getBitWidth() < 32)
432 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000433 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000434 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000435}
436
Reid Spencer3da59db2006-11-27 01:05:10 +0000437/// getBitCastOperand - If the specified operand is a CastInst or a constant
438/// expression bitcast, return the operand value, otherwise return null.
439static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000441 return I->getOperand(0);
442 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000443 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000444 return CE->getOperand(0);
445 return 0;
446}
447
Reid Spencer3da59db2006-11-27 01:05:10 +0000448/// This function is a wrapper around CastInst::isEliminableCastPair. It
449/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000450static Instruction::CastOps
451isEliminableCastPair(
452 const CastInst *CI, ///< The first cast instruction
453 unsigned opcode, ///< The opcode of the second cast instruction
454 const Type *DstTy, ///< The target type for the second cast instruction
455 TargetData *TD ///< The target data for pointer size
456) {
457
458 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
459 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000460
Reid Spencer3da59db2006-11-27 01:05:10 +0000461 // Get the opcodes of the two Cast instructions
462 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000464
Reid Spencer3da59db2006-11-27 01:05:10 +0000465 return Instruction::CastOps(
466 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000468}
469
470/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471/// in any code being generated. It does not require codegen if V is simple
472/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000473static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
474 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000475 if (V->getType() == Ty || isa<Constant>(V)) return false;
476
Chris Lattner01575b72006-05-25 23:24:33 +0000477 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000478 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000479 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000480 return false;
481 return true;
482}
483
484/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485/// InsertBefore instruction. This is specialized a bit to avoid inserting
486/// casts that are known to not do anything...
487///
Reid Spencer17212df2006-12-12 09:18:51 +0000488Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000490 Instruction *InsertBefore) {
491 if (V->getType() == DestTy) return V;
492 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000493 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000494
Reid Spencer17212df2006-12-12 09:18:51 +0000495 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000496}
497
Chris Lattner4f98c562003-03-10 21:43:22 +0000498// SimplifyCommutative - This performs a few simplifications for commutative
499// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000500//
Chris Lattner4f98c562003-03-10 21:43:22 +0000501// 1. Order operands such that they are listed from right (least complex) to
502// left (most complex). This puts constants before unary operators before
503// binary operators.
504//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000505// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000507//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 bool Changed = false;
510 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000512
Chris Lattner4f98c562003-03-10 21:43:22 +0000513 if (!I.isAssociative()) return Changed;
514 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000518 Constant *Folded = ConstantExpr::get(I.getOpcode(),
519 cast<Constant>(I.getOperand(1)),
520 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 I.setOperand(0, Op->getOperand(0));
522 I.setOperand(1, Folded);
523 return true;
524 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526 isOnlyUse(Op) && isOnlyUse(Op1)) {
527 Constant *C1 = cast<Constant>(Op->getOperand(1));
528 Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000531 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000532 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000533 Op1->getOperand(0),
534 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000535 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 I.setOperand(0, New);
537 I.setOperand(1, Folded);
538 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000539 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000540 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000541 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000543
Reid Spencere4d87aa2006-12-23 06:05:41 +0000544/// SimplifyCompare - For a CmpInst this function just orders the operands
545/// so that theyare listed from right (least complex) to left (most complex).
546/// This puts constants before unary operators before binary operators.
547bool InstCombiner::SimplifyCompare(CmpInst &I) {
548 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549 return false;
550 I.swapOperands();
551 // Compare instructions are not associative so there's nothing else we can do.
552 return true;
553}
554
Chris Lattner8d969642003-03-10 23:06:50 +0000555// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000557//
Chris Lattner8d969642003-03-10 23:06:50 +0000558static inline Value *dyn_castNegVal(Value *V) {
559 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000560 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000561
Chris Lattner0ce85802004-12-14 20:08:06 +0000562 // Constants can be considered to be negated values if they can be folded.
563 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000565
566 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567 if (C->getType()->getElementType()->isInteger())
568 return ConstantExpr::getNeg(C);
569
Chris Lattner8d969642003-03-10 23:06:50 +0000570 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000571}
572
Chris Lattner8d969642003-03-10 23:06:50 +0000573static inline Value *dyn_castNotVal(Value *V) {
574 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000575 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000576
577 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000578 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000579 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000580 return 0;
581}
582
Chris Lattnerc8802d22003-03-11 00:12:48 +0000583// dyn_castFoldableMul - If this value is a multiply that can be folded into
584// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000585// non-constant operand of the multiply, and set CST to point to the multiplier.
586// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000587//
Chris Lattner50af16a2004-11-13 19:50:12 +0000588static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000589 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000590 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000592 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000593 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000594 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000595 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000597 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000598 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000599 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000600 return I->getOperand(0);
601 }
602 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000603 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000604}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000605
Chris Lattner574da9b2005-01-13 20:14:25 +0000606/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607/// expression, return it.
608static User *dyn_castGetElementPtr(Value *V) {
609 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611 if (CE->getOpcode() == Instruction::GetElementPtr)
612 return cast<User>(V);
613 return false;
614}
615
Dan Gohmaneee962e2008-04-10 18:43:06 +0000616/// getOpcode - If this is an Instruction or a ConstantExpr, return the
617/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000618static unsigned getOpcode(const Value *V) {
619 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000620 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000621 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000622 return CE->getOpcode();
623 // Use UserOp1 to mean there's no opcode.
624 return Instruction::UserOp1;
625}
626
Reid Spencer7177c3a2007-03-25 05:33:51 +0000627/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000628static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000629 APInt Val(C->getValue());
630 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000631}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000632/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000633static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000634 APInt Val(C->getValue());
635 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000636}
637/// Add - Add two ConstantInts together
638static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() + C2->getValue());
640}
641/// And - Bitwise AND two ConstantInts together
642static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() & C2->getValue());
644}
645/// Subtract - Subtract one ConstantInt from another
646static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() - C2->getValue());
648}
649/// Multiply - Multiply two ConstantInts together
650static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000652}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000653/// MultiplyOverflows - True if the multiply can not be expressed in an int
654/// this size.
655static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656 uint32_t W = C1->getBitWidth();
657 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658 if (sign) {
659 LHSExt.sext(W * 2);
660 RHSExt.sext(W * 2);
661 } else {
662 LHSExt.zext(W * 2);
663 RHSExt.zext(W * 2);
664 }
665
666 APInt MulExt = LHSExt * RHSExt;
667
668 if (sign) {
669 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671 return MulExt.slt(Min) || MulExt.sgt(Max);
672 } else
673 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674}
Chris Lattner955f3312004-09-28 21:48:02 +0000675
Reid Spencere7816b52007-03-08 01:52:58 +0000676
Chris Lattner255d8912006-02-11 09:31:47 +0000677/// ShrinkDemandedConstant - Check to see if the specified operand of the
678/// specified instruction is a constant integer. If so, check to see if there
679/// are any bits set in the constant that are not demanded. If so, shrink the
680/// constant and return true.
681static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000682 APInt Demanded) {
683 assert(I && "No instruction?");
684 assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686 // If the operand is not a constant integer, nothing to do.
687 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688 if (!OpC) return false;
689
690 // If there are no bits set that aren't demanded, nothing to do.
691 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692 if ((~Demanded & OpC->getValue()) == 0)
693 return false;
694
695 // This instruction is producing bits that are not demanded. Shrink the RHS.
696 Demanded &= OpC->getValue();
697 I->setOperand(OpNo, ConstantInt::get(Demanded));
698 return true;
699}
700
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000701// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
702// set of known zero and one bits, compute the maximum and minimum values that
703// could have the specified known zero and known one bits, returning them in
704// min/max.
705static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000706 const APInt& KnownZero,
707 const APInt& KnownOne,
708 APInt& Min, APInt& Max) {
709 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710 assert(KnownZero.getBitWidth() == BitWidth &&
711 KnownOne.getBitWidth() == BitWidth &&
712 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000714 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000715
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000716 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717 // bit if it is unknown.
718 Min = KnownOne;
719 Max = KnownOne|UnknownBits;
720
Zhou Sheng4acf1552007-03-28 05:15:57 +0000721 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000722 Min.set(BitWidth-1);
723 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000724 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725}
726
727// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728// a set of known zero and one bits, compute the maximum and minimum values that
729// could have the specified known zero and known one bits, returning them in
730// min/max.
731static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000732 const APInt &KnownZero,
733 const APInt &KnownOne,
734 APInt &Min, APInt &Max) {
735 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000736 assert(KnownZero.getBitWidth() == BitWidth &&
737 KnownOne.getBitWidth() == BitWidth &&
738 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000740 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741
742 // The minimum value is when the unknown bits are all zeros.
743 Min = KnownOne;
744 // The maximum value is when the unknown bits are all ones.
745 Max = KnownOne|UnknownBits;
746}
Chris Lattner255d8912006-02-11 09:31:47 +0000747
Reid Spencer8cb68342007-03-12 17:25:59 +0000748/// SimplifyDemandedBits - This function attempts to replace V with a simpler
749/// value based on the demanded bits. When this function is called, it is known
750/// that only the bits set in DemandedMask of the result of V are ever used
751/// downstream. Consequently, depending on the mask and V, it may be possible
752/// to replace V with a constant or one of its operands. In such cases, this
753/// function does the replacement and returns true. In all other cases, it
754/// returns false after analyzing the expression and setting KnownOne and known
755/// to be one in the expression. KnownZero contains all the bits that are known
756/// to be zero in the expression. These are provided to potentially allow the
757/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758/// the expression. KnownOne and KnownZero always follow the invariant that
759/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760/// the bits in KnownOne and KnownZero may only be accurate for those bits set
761/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762/// and KnownOne must all be the same.
763bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764 APInt& KnownZero, APInt& KnownOne,
765 unsigned Depth) {
766 assert(V != 0 && "Null pointer of Value???");
767 assert(Depth <= 6 && "Limit Search Depth");
768 uint32_t BitWidth = DemandedMask.getBitWidth();
769 const IntegerType *VTy = cast<IntegerType>(V->getType());
770 assert(VTy->getBitWidth() == BitWidth &&
771 KnownZero.getBitWidth() == BitWidth &&
772 KnownOne.getBitWidth() == BitWidth &&
773 "Value *V, DemandedMask, KnownZero and KnownOne \
774 must have same BitWidth");
775 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776 // We know all of the bits for a constant!
777 KnownOne = CI->getValue() & DemandedMask;
778 KnownZero = ~KnownOne & DemandedMask;
779 return false;
780 }
781
Zhou Sheng96704452007-03-14 03:21:24 +0000782 KnownZero.clear();
783 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000784 if (!V->hasOneUse()) { // Other users may use these bits.
785 if (Depth != 0) { // Not at the root.
786 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788 return false;
789 }
790 // If this is the root being simplified, allow it to have multiple uses,
791 // just set the DemandedMask to all bits.
792 DemandedMask = APInt::getAllOnesValue(BitWidth);
793 } else if (DemandedMask == 0) { // Not demanding any bits from V.
794 if (V != UndefValue::get(VTy))
795 return UpdateValueUsesWith(V, UndefValue::get(VTy));
796 return false;
797 } else if (Depth == 6) { // Limit search depth.
798 return false;
799 }
800
801 Instruction *I = dyn_cast<Instruction>(V);
802 if (!I) return false; // Only analyze instructions.
803
Reid Spencer8cb68342007-03-12 17:25:59 +0000804 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000807 default:
808 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000810 case Instruction::And:
811 // If either the LHS or the RHS are Zero, the result is zero.
812 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813 RHSKnownZero, RHSKnownOne, Depth+1))
814 return true;
815 assert((RHSKnownZero & RHSKnownOne) == 0 &&
816 "Bits known to be one AND zero?");
817
818 // If something is known zero on the RHS, the bits aren't demanded on the
819 // LHS.
820 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821 LHSKnownZero, LHSKnownOne, Depth+1))
822 return true;
823 assert((LHSKnownZero & LHSKnownOne) == 0 &&
824 "Bits known to be one AND zero?");
825
826 // If all of the demanded bits are known 1 on one side, return the other.
827 // These bits cannot contribute to the result of the 'and'.
828 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
829 (DemandedMask & ~LHSKnownZero))
830 return UpdateValueUsesWith(I, I->getOperand(0));
831 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
832 (DemandedMask & ~RHSKnownZero))
833 return UpdateValueUsesWith(I, I->getOperand(1));
834
835 // If all of the demanded bits in the inputs are known zeros, return zero.
836 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838
839 // If the RHS is a constant, see if we can simplify it.
840 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841 return UpdateValueUsesWith(I, I);
842
843 // Output known-1 bits are only known if set in both the LHS & RHS.
844 RHSKnownOne &= LHSKnownOne;
845 // Output known-0 are known to be clear if zero in either the LHS | RHS.
846 RHSKnownZero |= LHSKnownZero;
847 break;
848 case Instruction::Or:
849 // If either the LHS or the RHS are One, the result is One.
850 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1))
852 return true;
853 assert((RHSKnownZero & RHSKnownOne) == 0 &&
854 "Bits known to be one AND zero?");
855 // If something is known one on the RHS, the bits aren't demanded on the
856 // LHS.
857 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
858 LHSKnownZero, LHSKnownOne, Depth+1))
859 return true;
860 assert((LHSKnownZero & LHSKnownOne) == 0 &&
861 "Bits known to be one AND zero?");
862
863 // If all of the demanded bits are known zero on one side, return the other.
864 // These bits cannot contribute to the result of the 'or'.
865 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
866 (DemandedMask & ~LHSKnownOne))
867 return UpdateValueUsesWith(I, I->getOperand(0));
868 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
869 (DemandedMask & ~RHSKnownOne))
870 return UpdateValueUsesWith(I, I->getOperand(1));
871
872 // If all of the potentially set bits on one side are known to be set on
873 // the other side, just use the 'other' side.
874 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
875 (DemandedMask & (~RHSKnownZero)))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
878 (DemandedMask & (~LHSKnownZero)))
879 return UpdateValueUsesWith(I, I->getOperand(1));
880
881 // If the RHS is a constant, see if we can simplify it.
882 if (ShrinkDemandedConstant(I, 1, DemandedMask))
883 return UpdateValueUsesWith(I, I);
884
885 // Output known-0 bits are only known if clear in both the LHS & RHS.
886 RHSKnownZero &= LHSKnownZero;
887 // Output known-1 are known to be set if set in either the LHS | RHS.
888 RHSKnownOne |= LHSKnownOne;
889 break;
890 case Instruction::Xor: {
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 RHSKnownZero, RHSKnownOne, Depth+1))
893 return true;
894 assert((RHSKnownZero & RHSKnownOne) == 0 &&
895 "Bits known to be one AND zero?");
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
897 LHSKnownZero, LHSKnownOne, Depth+1))
898 return true;
899 assert((LHSKnownZero & LHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
901
902 // If all of the demanded bits are known zero on one side, return the other.
903 // These bits cannot contribute to the result of the 'xor'.
904 if ((DemandedMask & RHSKnownZero) == DemandedMask)
905 return UpdateValueUsesWith(I, I->getOperand(0));
906 if ((DemandedMask & LHSKnownZero) == DemandedMask)
907 return UpdateValueUsesWith(I, I->getOperand(1));
908
909 // Output known-0 bits are known if clear or set in both the LHS & RHS.
910 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
911 (RHSKnownOne & LHSKnownOne);
912 // Output known-1 are known to be set if set in only one of the LHS, RHS.
913 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
914 (RHSKnownOne & LHSKnownZero);
915
916 // If all of the demanded bits are known to be zero on one side or the
917 // other, turn this into an *inclusive* or.
918 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000921 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000922 I->getName());
923 InsertNewInstBefore(Or, *I);
924 return UpdateValueUsesWith(I, Or);
925 }
926
927 // If all of the demanded bits on one side are known, and all of the set
928 // bits on that side are also known to be set on the other side, turn this
929 // into an AND, as we know the bits will be cleared.
930 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
932 // all known
933 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000936 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 InsertNewInstBefore(And, *I);
938 return UpdateValueUsesWith(I, And);
939 }
940 }
941
942 // If the RHS is a constant, see if we can simplify it.
943 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944 if (ShrinkDemandedConstant(I, 1, DemandedMask))
945 return UpdateValueUsesWith(I, I);
946
947 RHSKnownZero = KnownZeroOut;
948 RHSKnownOne = KnownOneOut;
949 break;
950 }
951 case Instruction::Select:
952 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1))
954 return true;
955 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
956 LHSKnownZero, LHSKnownOne, Depth+1))
957 return true;
958 assert((RHSKnownZero & RHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960 assert((LHSKnownZero & LHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
962
963 // If the operands are constants, see if we can simplify them.
964 if (ShrinkDemandedConstant(I, 1, DemandedMask))
965 return UpdateValueUsesWith(I, I);
966 if (ShrinkDemandedConstant(I, 2, DemandedMask))
967 return UpdateValueUsesWith(I, I);
968
969 // Only known if known in both the LHS and RHS.
970 RHSKnownOne &= LHSKnownOne;
971 RHSKnownZero &= LHSKnownZero;
972 break;
973 case Instruction::Trunc: {
974 uint32_t truncBf =
975 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000976 DemandedMask.zext(truncBf);
977 RHSKnownZero.zext(truncBf);
978 RHSKnownOne.zext(truncBf);
979 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
980 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000981 return true;
982 DemandedMask.trunc(BitWidth);
983 RHSKnownZero.trunc(BitWidth);
984 RHSKnownOne.trunc(BitWidth);
985 assert((RHSKnownZero & RHSKnownOne) == 0 &&
986 "Bits known to be one AND zero?");
987 break;
988 }
989 case Instruction::BitCast:
990 if (!I->getOperand(0)->getType()->isInteger())
991 return false;
992
993 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994 RHSKnownZero, RHSKnownOne, Depth+1))
995 return true;
996 assert((RHSKnownZero & RHSKnownOne) == 0 &&
997 "Bits known to be one AND zero?");
998 break;
999 case Instruction::ZExt: {
1000 // Compute the bits in the result that are not present in the input.
1001 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001002 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001003
Zhou Shengd48653a2007-03-29 04:45:55 +00001004 DemandedMask.trunc(SrcBitWidth);
1005 RHSKnownZero.trunc(SrcBitWidth);
1006 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001009 return true;
1010 DemandedMask.zext(BitWidth);
1011 RHSKnownZero.zext(BitWidth);
1012 RHSKnownOne.zext(BitWidth);
1013 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1014 "Bits known to be one AND zero?");
1015 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001016 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017 break;
1018 }
1019 case Instruction::SExt: {
1020 // Compute the bits in the result that are not present in the input.
1021 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001022 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001023
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001025 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026
Zhou Sheng01542f32007-03-29 02:26:30 +00001027 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 // If any of the sign extended bits are demanded, we know that the sign
1029 // bit is demanded.
1030 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001031 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001032
Zhou Shengd48653a2007-03-29 04:45:55 +00001033 InputDemandedBits.trunc(SrcBitWidth);
1034 RHSKnownZero.trunc(SrcBitWidth);
1035 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001036 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001038 return true;
1039 InputDemandedBits.zext(BitWidth);
1040 RHSKnownZero.zext(BitWidth);
1041 RHSKnownOne.zext(BitWidth);
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1044
1045 // If the sign bit of the input is known set or clear, then we know the
1046 // top bits of the result.
1047
1048 // If the input sign bit is known zero, or if the NewBits are not demanded
1049 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001050 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001051 {
1052 // Convert to ZExt cast
1053 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001055 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001056 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 }
1058 break;
1059 }
1060 case Instruction::Add: {
1061 // Figure out what the input bits are. If the top bits of the and result
1062 // are not demanded, then the add doesn't demand them from its input
1063 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001064 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001065
1066 // If there is a constant on the RHS, there are a variety of xformations
1067 // we can do.
1068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069 // If null, this should be simplified elsewhere. Some of the xforms here
1070 // won't work if the RHS is zero.
1071 if (RHS->isZero())
1072 break;
1073
1074 // If the top bit of the output is demanded, demand everything from the
1075 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001076 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001077
1078 // Find information about known zero/one bits in the input.
1079 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1080 LHSKnownZero, LHSKnownOne, Depth+1))
1081 return true;
1082
1083 // If the RHS of the add has bits set that can't affect the input, reduce
1084 // the constant.
1085 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086 return UpdateValueUsesWith(I, I);
1087
1088 // Avoid excess work.
1089 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090 break;
1091
1092 // Turn it into OR if input bits are zero.
1093 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001095 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001096 I->getName());
1097 InsertNewInstBefore(Or, *I);
1098 return UpdateValueUsesWith(I, Or);
1099 }
1100
1101 // We can say something about the output known-zero and known-one bits,
1102 // depending on potential carries from the input constant and the
1103 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1104 // bits set and the RHS constant is 0x01001, then we know we have a known
1105 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106
1107 // To compute this, we first compute the potential carry bits. These are
1108 // the bits which may be modified. I'm not aware of a better way to do
1109 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001110 const APInt& RHSVal = RHS->getValue();
1111 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
1113 // Now that we know which bits have carries, compute the known-1/0 sets.
1114
1115 // Bits are known one if they are known zero in one operand and one in the
1116 // other, and there is no input carry.
1117 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1118 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119
1120 // Bits are known zero if they are known zero in both operands and there
1121 // is no input carry.
1122 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123 } else {
1124 // If the high-bits of this ADD are not demanded, then it does not demand
1125 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001126 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 // Right fill the mask of bits for this ADD to demand the most
1128 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001129 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131 LHSKnownZero, LHSKnownOne, Depth+1))
1132 return true;
1133 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134 LHSKnownZero, LHSKnownOne, Depth+1))
1135 return true;
1136 }
1137 }
1138 break;
1139 }
1140 case Instruction::Sub:
1141 // If the high-bits of this SUB are not demanded, then it does not demand
1142 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001144 // Right fill the mask of bits for this SUB to demand the most
1145 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001146 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001147 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149 LHSKnownZero, LHSKnownOne, Depth+1))
1150 return true;
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152 LHSKnownZero, LHSKnownOne, Depth+1))
1153 return true;
1154 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001155 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156 // the known zeros and ones.
1157 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001158 break;
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001161 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001162 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 RHSKnownZero, RHSKnownOne, Depth+1))
1165 return true;
1166 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1167 "Bits known to be one AND zero?");
1168 RHSKnownZero <<= ShiftAmt;
1169 RHSKnownOne <<= ShiftAmt;
1170 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001171 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001172 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 }
1174 break;
1175 case Instruction::LShr:
1176 // For a logical shift right
1177 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001178 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001179
Reid Spencer8cb68342007-03-12 17:25:59 +00001180 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001181 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001183 RHSKnownZero, RHSKnownOne, Depth+1))
1184 return true;
1185 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1186 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001189 if (ShiftAmt) {
1190 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001191 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001192 RHSKnownZero |= HighBits; // high bits known zero.
1193 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001194 }
1195 break;
1196 case Instruction::AShr:
1197 // If this is an arithmetic shift right and only the low-bit is set, we can
1198 // always convert this into a logical shr, even if the shift amount is
1199 // variable. The low bit of the shift cannot be an input sign bit unless
1200 // the shift amount is >= the size of the datatype, which is undefined.
1201 if (DemandedMask == 1) {
1202 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001203 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 I->getOperand(0), I->getOperand(1), I->getName());
1205 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206 return UpdateValueUsesWith(I, NewVal);
1207 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001208
1209 // If the sign bit is the only bit demanded by this ashr, then there is no
1210 // need to do it, the shift doesn't change the high bit.
1211 if (DemandedMask.isSignBit())
1212 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001213
1214 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001215 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001219 // If any of the "high bits" are demanded, we should set the sign bit as
1220 // demanded.
1221 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 RHSKnownZero, RHSKnownOne, Depth+1))
1226 return true;
1227 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1228 "Bits known to be one AND zero?");
1229 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233
1234 // Handle the sign bits.
1235 APInt SignBit(APInt::getSignBit(BitWidth));
1236 // Adjust to where it is now in the mask.
1237 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1238
1239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001241 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 (HighBits & ~DemandedMask) == HighBits) {
1243 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001244 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 I->getOperand(0), SA, I->getName());
1246 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247 return UpdateValueUsesWith(I, NewVal);
1248 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249 RHSKnownOne |= HighBits;
1250 }
1251 }
1252 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001253 case Instruction::SRem:
1254 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255 APInt RA = Rem->getValue();
1256 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001257 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001258 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260 LHSKnownZero, LHSKnownOne, Depth+1))
1261 return true;
1262
1263 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264 LHSKnownZero |= ~LowBits;
1265 else if (LHSKnownOne[BitWidth-1])
1266 LHSKnownOne |= ~LowBits;
1267
1268 KnownZero |= LHSKnownZero & DemandedMask;
1269 KnownOne |= LHSKnownOne & DemandedMask;
1270
1271 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1272 }
1273 }
1274 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001275 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001276 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001278 if (RA.isPowerOf2()) {
1279 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001280 APInt Mask2 = LowBits & DemandedMask;
1281 KnownZero |= ~LowBits & DemandedMask;
1282 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283 KnownZero, KnownOne, Depth+1))
1284 return true;
1285
1286 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001287 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001288 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001289 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001290
1291 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001293 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294 KnownZero2, KnownOne2, Depth+1))
1295 return true;
1296
Dan Gohman23e8b712008-04-28 17:02:21 +00001297 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001298 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001299 KnownZero2, KnownOne2, Depth+1))
1300 return true;
1301
1302 Leaders = std::max(Leaders,
1303 KnownZero2.countLeadingOnes());
1304 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001305 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001307 case Instruction::Call:
1308 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1309 switch (II->getIntrinsicID()) {
1310 default: break;
1311 case Intrinsic::bswap: {
1312 // If the only bits demanded come from one byte of the bswap result,
1313 // just shift the input byte into position to eliminate the bswap.
1314 unsigned NLZ = DemandedMask.countLeadingZeros();
1315 unsigned NTZ = DemandedMask.countTrailingZeros();
1316
1317 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1318 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1319 // have 14 leading zeros, round to 8.
1320 NLZ &= ~7;
1321 NTZ &= ~7;
1322 // If we need exactly one byte, we can do this transformation.
1323 if (BitWidth-NLZ-NTZ == 8) {
1324 unsigned ResultBit = NTZ;
1325 unsigned InputBit = BitWidth-NTZ-8;
1326
1327 // Replace this with either a left or right shift to get the byte into
1328 // the right place.
1329 Instruction *NewVal;
1330 if (InputBit > ResultBit)
1331 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1332 ConstantInt::get(I->getType(), InputBit-ResultBit));
1333 else
1334 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1335 ConstantInt::get(I->getType(), ResultBit-InputBit));
1336 NewVal->takeName(I);
1337 InsertNewInstBefore(NewVal, *I);
1338 return UpdateValueUsesWith(I, NewVal);
1339 }
1340
1341 // TODO: Could compute known zero/one bits based on the input.
1342 break;
1343 }
1344 }
1345 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001346 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001347 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001348 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001349
1350 // If the client is only demanding bits that we know, return the known
1351 // constant.
1352 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1353 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1354 return false;
1355}
1356
Chris Lattner867b99f2006-10-05 06:55:50 +00001357
1358/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1359/// 64 or fewer elements. DemandedElts contains the set of elements that are
1360/// actually used by the caller. This method analyzes which elements of the
1361/// operand are undef and returns that information in UndefElts.
1362///
1363/// If the information about demanded elements can be used to simplify the
1364/// operation, the operation is simplified, then the resultant value is
1365/// returned. This returns null if no change was made.
1366Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1367 uint64_t &UndefElts,
1368 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001369 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001370 assert(VWidth <= 64 && "Vector too wide to analyze!");
1371 uint64_t EltMask = ~0ULL >> (64-VWidth);
1372 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1373 "Invalid DemandedElts!");
1374
1375 if (isa<UndefValue>(V)) {
1376 // If the entire vector is undefined, just return this info.
1377 UndefElts = EltMask;
1378 return 0;
1379 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1380 UndefElts = EltMask;
1381 return UndefValue::get(V->getType());
1382 }
1383
1384 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001385 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1386 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001387 Constant *Undef = UndefValue::get(EltTy);
1388
1389 std::vector<Constant*> Elts;
1390 for (unsigned i = 0; i != VWidth; ++i)
1391 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1392 Elts.push_back(Undef);
1393 UndefElts |= (1ULL << i);
1394 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1395 Elts.push_back(Undef);
1396 UndefElts |= (1ULL << i);
1397 } else { // Otherwise, defined.
1398 Elts.push_back(CP->getOperand(i));
1399 }
1400
1401 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001402 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001403 return NewCP != CP ? NewCP : 0;
1404 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001405 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001406 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001407 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001408 Constant *Zero = Constant::getNullValue(EltTy);
1409 Constant *Undef = UndefValue::get(EltTy);
1410 std::vector<Constant*> Elts;
1411 for (unsigned i = 0; i != VWidth; ++i)
1412 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1413 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001414 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001415 }
1416
1417 if (!V->hasOneUse()) { // Other users may use these bits.
1418 if (Depth != 0) { // Not at the root.
1419 // TODO: Just compute the UndefElts information recursively.
1420 return false;
1421 }
1422 return false;
1423 } else if (Depth == 10) { // Limit search depth.
1424 return false;
1425 }
1426
1427 Instruction *I = dyn_cast<Instruction>(V);
1428 if (!I) return false; // Only analyze instructions.
1429
1430 bool MadeChange = false;
1431 uint64_t UndefElts2;
1432 Value *TmpV;
1433 switch (I->getOpcode()) {
1434 default: break;
1435
1436 case Instruction::InsertElement: {
1437 // If this is a variable index, we don't know which element it overwrites.
1438 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001439 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001440 if (Idx == 0) {
1441 // Note that we can't propagate undef elt info, because we don't know
1442 // which elt is getting updated.
1443 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1444 UndefElts2, Depth+1);
1445 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1446 break;
1447 }
1448
1449 // If this is inserting an element that isn't demanded, remove this
1450 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001451 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1453 return AddSoonDeadInstToWorklist(*I, 0);
1454
1455 // Otherwise, the element inserted overwrites whatever was there, so the
1456 // input demanded set is simpler than the output set.
1457 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1458 DemandedElts & ~(1ULL << IdxNo),
1459 UndefElts, Depth+1);
1460 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1461
1462 // The inserted element is defined.
1463 UndefElts |= 1ULL << IdxNo;
1464 break;
1465 }
Chris Lattner69878332007-04-14 22:29:23 +00001466 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001467 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001468 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1469 if (!VTy) break;
1470 unsigned InVWidth = VTy->getNumElements();
1471 uint64_t InputDemandedElts = 0;
1472 unsigned Ratio;
1473
1474 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001475 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001476 // elements as are demanded of us.
1477 Ratio = 1;
1478 InputDemandedElts = DemandedElts;
1479 } else if (VWidth > InVWidth) {
1480 // Untested so far.
1481 break;
1482
1483 // If there are more elements in the result than there are in the source,
1484 // then an input element is live if any of the corresponding output
1485 // elements are live.
1486 Ratio = VWidth/InVWidth;
1487 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1488 if (DemandedElts & (1ULL << OutIdx))
1489 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1490 }
1491 } else {
1492 // Untested so far.
1493 break;
1494
1495 // If there are more elements in the source than there are in the result,
1496 // then an input element is live if the corresponding output element is
1497 // live.
1498 Ratio = InVWidth/VWidth;
1499 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1500 if (DemandedElts & (1ULL << InIdx/Ratio))
1501 InputDemandedElts |= 1ULL << InIdx;
1502 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001503
Chris Lattner69878332007-04-14 22:29:23 +00001504 // div/rem demand all inputs, because they don't want divide by zero.
1505 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1506 UndefElts2, Depth+1);
1507 if (TmpV) {
1508 I->setOperand(0, TmpV);
1509 MadeChange = true;
1510 }
1511
1512 UndefElts = UndefElts2;
1513 if (VWidth > InVWidth) {
1514 assert(0 && "Unimp");
1515 // If there are more elements in the result than there are in the source,
1516 // then an output element is undef if the corresponding input element is
1517 // undef.
1518 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1519 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1520 UndefElts |= 1ULL << OutIdx;
1521 } else if (VWidth < InVWidth) {
1522 assert(0 && "Unimp");
1523 // If there are more elements in the source than there are in the result,
1524 // then a result element is undef if all of the corresponding input
1525 // elements are undef.
1526 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1527 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1529 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1530 }
1531 break;
1532 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 case Instruction::And:
1534 case Instruction::Or:
1535 case Instruction::Xor:
1536 case Instruction::Add:
1537 case Instruction::Sub:
1538 case Instruction::Mul:
1539 // div/rem demand all inputs, because they don't want divide by zero.
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541 UndefElts, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1544 UndefElts2, Depth+1);
1545 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1546
1547 // Output elements are undefined if both are undefined. Consider things
1548 // like undef&0. The result is known zero, not undef.
1549 UndefElts &= UndefElts2;
1550 break;
1551
1552 case Instruction::Call: {
1553 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1554 if (!II) break;
1555 switch (II->getIntrinsicID()) {
1556 default: break;
1557
1558 // Binary vector operations that work column-wise. A dest element is a
1559 // function of the corresponding input elements from the two inputs.
1560 case Intrinsic::x86_sse_sub_ss:
1561 case Intrinsic::x86_sse_mul_ss:
1562 case Intrinsic::x86_sse_min_ss:
1563 case Intrinsic::x86_sse_max_ss:
1564 case Intrinsic::x86_sse2_sub_sd:
1565 case Intrinsic::x86_sse2_mul_sd:
1566 case Intrinsic::x86_sse2_min_sd:
1567 case Intrinsic::x86_sse2_max_sd:
1568 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1569 UndefElts, Depth+1);
1570 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1571 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1572 UndefElts2, Depth+1);
1573 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1574
1575 // If only the low elt is demanded and this is a scalarizable intrinsic,
1576 // scalarize it now.
1577 if (DemandedElts == 1) {
1578 switch (II->getIntrinsicID()) {
1579 default: break;
1580 case Intrinsic::x86_sse_sub_ss:
1581 case Intrinsic::x86_sse_mul_ss:
1582 case Intrinsic::x86_sse2_sub_sd:
1583 case Intrinsic::x86_sse2_mul_sd:
1584 // TODO: Lower MIN/MAX/ABS/etc
1585 Value *LHS = II->getOperand(1);
1586 Value *RHS = II->getOperand(2);
1587 // Extract the element as scalars.
1588 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1589 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1590
1591 switch (II->getIntrinsicID()) {
1592 default: assert(0 && "Case stmts out of sync!");
1593 case Intrinsic::x86_sse_sub_ss:
1594 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001595 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001596 II->getName()), *II);
1597 break;
1598 case Intrinsic::x86_sse_mul_ss:
1599 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001600 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001601 II->getName()), *II);
1602 break;
1603 }
1604
1605 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001606 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1607 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001608 InsertNewInstBefore(New, *II);
1609 AddSoonDeadInstToWorklist(*II, 0);
1610 return New;
1611 }
1612 }
1613
1614 // Output elements are undefined if both are undefined. Consider things
1615 // like undef&0. The result is known zero, not undef.
1616 UndefElts &= UndefElts2;
1617 break;
1618 }
1619 break;
1620 }
1621 }
1622 return MadeChange ? I : 0;
1623}
1624
Dan Gohman45b4e482008-05-19 22:14:15 +00001625
Chris Lattner564a7272003-08-13 19:01:45 +00001626/// AssociativeOpt - Perform an optimization on an associative operator. This
1627/// function is designed to check a chain of associative operators for a
1628/// potential to apply a certain optimization. Since the optimization may be
1629/// applicable if the expression was reassociated, this checks the chain, then
1630/// reassociates the expression as necessary to expose the optimization
1631/// opportunity. This makes use of a special Functor, which must define
1632/// 'shouldApply' and 'apply' methods.
1633///
1634template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001635static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001636 unsigned Opcode = Root.getOpcode();
1637 Value *LHS = Root.getOperand(0);
1638
1639 // Quick check, see if the immediate LHS matches...
1640 if (F.shouldApply(LHS))
1641 return F.apply(Root);
1642
1643 // Otherwise, if the LHS is not of the same opcode as the root, return.
1644 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001645 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001646 // Should we apply this transform to the RHS?
1647 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1648
1649 // If not to the RHS, check to see if we should apply to the LHS...
1650 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1651 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1652 ShouldApply = true;
1653 }
1654
1655 // If the functor wants to apply the optimization to the RHS of LHSI,
1656 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1657 if (ShouldApply) {
1658 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001659
Chris Lattner564a7272003-08-13 19:01:45 +00001660 // Now all of the instructions are in the current basic block, go ahead
1661 // and perform the reassociation.
1662 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1663
1664 // First move the selected RHS to the LHS of the root...
1665 Root.setOperand(0, LHSI->getOperand(1));
1666
1667 // Make what used to be the LHS of the root be the user of the root...
1668 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001669 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001670 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1671 return 0;
1672 }
Chris Lattner65725312004-04-16 18:08:07 +00001673 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001674 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001675 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001676 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001677 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001678
1679 // Now propagate the ExtraOperand down the chain of instructions until we
1680 // get to LHSI.
1681 while (TmpLHSI != LHSI) {
1682 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001683 // Move the instruction to immediately before the chain we are
1684 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001685 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001686 ARI = NextLHSI;
1687
Chris Lattner564a7272003-08-13 19:01:45 +00001688 Value *NextOp = NextLHSI->getOperand(1);
1689 NextLHSI->setOperand(1, ExtraOperand);
1690 TmpLHSI = NextLHSI;
1691 ExtraOperand = NextOp;
1692 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001693
Chris Lattner564a7272003-08-13 19:01:45 +00001694 // Now that the instructions are reassociated, have the functor perform
1695 // the transformation...
1696 return F.apply(Root);
1697 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001698
Chris Lattner564a7272003-08-13 19:01:45 +00001699 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1700 }
1701 return 0;
1702}
1703
Dan Gohman844731a2008-05-13 00:00:25 +00001704namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001705
Nick Lewycky02d639f2008-05-23 04:34:58 +00001706// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001707struct AddRHS {
1708 Value *RHS;
1709 AddRHS(Value *rhs) : RHS(rhs) {}
1710 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1711 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001712 return BinaryOperator::CreateShl(Add.getOperand(0),
1713 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001714 }
1715};
1716
1717// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1718// iff C1&C2 == 0
1719struct AddMaskingAnd {
1720 Constant *C2;
1721 AddMaskingAnd(Constant *c) : C2(c) {}
1722 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001723 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001724 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001725 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001726 }
1727 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001728 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001729 }
1730};
1731
Dan Gohman844731a2008-05-13 00:00:25 +00001732}
1733
Chris Lattner6e7ba452005-01-01 16:22:27 +00001734static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001735 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001736 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001737 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001738 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001739
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001740 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001741 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001742 }
1743
Chris Lattner2eefe512004-04-09 19:05:30 +00001744 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001745 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1746 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001747
Chris Lattner2eefe512004-04-09 19:05:30 +00001748 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1749 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001750 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1751 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001752 }
1753
1754 Value *Op0 = SO, *Op1 = ConstOperand;
1755 if (!ConstIsRHS)
1756 std::swap(Op0, Op1);
1757 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001758 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001759 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001760 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001761 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001762 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001763 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001764 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001765 abort();
1766 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001767 return IC->InsertNewInstBefore(New, I);
1768}
1769
1770// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1771// constant as the other operand, try to fold the binary operator into the
1772// select arguments. This also works for Cast instructions, which obviously do
1773// not have a second operand.
1774static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1775 InstCombiner *IC) {
1776 // Don't modify shared select instructions
1777 if (!SI->hasOneUse()) return 0;
1778 Value *TV = SI->getOperand(1);
1779 Value *FV = SI->getOperand(2);
1780
1781 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001782 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001783 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001784
Chris Lattner6e7ba452005-01-01 16:22:27 +00001785 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1786 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1787
Gabor Greif051a9502008-04-06 20:25:17 +00001788 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1789 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001790 }
1791 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001792}
1793
Chris Lattner4e998b22004-09-29 05:07:12 +00001794
1795/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1796/// node as operand #0, see if we can fold the instruction into the PHI (which
1797/// is only possible if all operands to the PHI are constants).
1798Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1799 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001800 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001801 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001802
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001803 // Check to see if all of the operands of the PHI are constants. If there is
1804 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001805 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001806 BasicBlock *NonConstBB = 0;
1807 for (unsigned i = 0; i != NumPHIValues; ++i)
1808 if (!isa<Constant>(PN->getIncomingValue(i))) {
1809 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001810 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001811 NonConstBB = PN->getIncomingBlock(i);
1812
1813 // If the incoming non-constant value is in I's block, we have an infinite
1814 // loop.
1815 if (NonConstBB == I.getParent())
1816 return 0;
1817 }
1818
1819 // If there is exactly one non-constant value, we can insert a copy of the
1820 // operation in that block. However, if this is a critical edge, we would be
1821 // inserting the computation one some other paths (e.g. inside a loop). Only
1822 // do this if the pred block is unconditionally branching into the phi block.
1823 if (NonConstBB) {
1824 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1825 if (!BI || !BI->isUnconditional()) return 0;
1826 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001827
1828 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001829 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001830 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001831 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001832 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001833
1834 // Next, add all of the operands to the PHI.
1835 if (I.getNumOperands() == 2) {
1836 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001837 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001838 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001839 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001840 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1841 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1842 else
1843 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001844 } else {
1845 assert(PN->getIncomingBlock(i) == NonConstBB);
1846 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001847 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001848 PN->getIncomingValue(i), C, "phitmp",
1849 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001850 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001851 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001852 CI->getPredicate(),
1853 PN->getIncomingValue(i), C, "phitmp",
1854 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001855 else
1856 assert(0 && "Unknown binop!");
1857
Chris Lattnerdbab3862007-03-02 21:28:56 +00001858 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001859 }
1860 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001861 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001862 } else {
1863 CastInst *CI = cast<CastInst>(&I);
1864 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001865 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001866 Value *InV;
1867 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001868 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001869 } else {
1870 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001871 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001872 I.getType(), "phitmp",
1873 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001874 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001875 }
1876 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001877 }
1878 }
1879 return ReplaceInstUsesWith(I, NewPN);
1880}
1881
Chris Lattner2454a2e2008-01-29 06:52:45 +00001882
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001883/// WillNotOverflowSignedAdd - Return true if we can prove that:
1884/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1885/// This basically requires proving that the add in the original type would not
1886/// overflow to change the sign bit or have a carry out.
1887bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1888 // There are different heuristics we can use for this. Here are some simple
1889 // ones.
1890
1891 // Add has the property that adding any two 2's complement numbers can only
1892 // have one carry bit which can change a sign. As such, if LHS and RHS each
1893 // have at least two sign bits, we know that the addition of the two values will
1894 // sign extend fine.
1895 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1896 return true;
1897
1898
1899 // If one of the operands only has one non-zero bit, and if the other operand
1900 // has a known-zero bit in a more significant place than it (not including the
1901 // sign bit) the ripple may go up to and fill the zero, but won't change the
1902 // sign. For example, (X & ~4) + 1.
1903
1904 // TODO: Implement.
1905
1906 return false;
1907}
1908
Chris Lattner2454a2e2008-01-29 06:52:45 +00001909
Chris Lattner7e708292002-06-25 16:13:24 +00001910Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001911 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001912 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001913
Chris Lattner66331a42004-04-10 22:01:55 +00001914 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001915 // X + undef -> undef
1916 if (isa<UndefValue>(RHS))
1917 return ReplaceInstUsesWith(I, RHS);
1918
Chris Lattner66331a42004-04-10 22:01:55 +00001919 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001920 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001921 if (RHSC->isNullValue())
1922 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001923 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001924 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1925 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001926 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001927 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001928
Chris Lattner66331a42004-04-10 22:01:55 +00001929 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001930 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001931 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001932 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001933 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001934 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001935
1936 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1937 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001938 if (!isa<VectorType>(I.getType())) {
1939 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1940 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1941 KnownZero, KnownOne))
1942 return &I;
1943 }
Chris Lattner66331a42004-04-10 22:01:55 +00001944 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001945
1946 if (isa<PHINode>(LHS))
1947 if (Instruction *NV = FoldOpIntoPhi(I))
1948 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001949
Chris Lattner4f637d42006-01-06 17:59:59 +00001950 ConstantInt *XorRHS = 0;
1951 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001952 if (isa<ConstantInt>(RHSC) &&
1953 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001954 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001955 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001956
Zhou Sheng4351c642007-04-02 08:20:41 +00001957 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001958 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1959 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001960 do {
1961 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001962 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1963 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001964 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1965 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001966 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001967 if (!MaskedValueIsZero(XorLHS,
1968 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001969 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001970 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001971 }
1972 }
1973 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001974 C0080Val = APIntOps::lshr(C0080Val, Size);
1975 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1976 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001977
Reid Spencer35c38852007-03-28 01:36:16 +00001978 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001979 // with funny bit widths then this switch statement should be removed. It
1980 // is just here to get the size of the "middle" type back up to something
1981 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001982 const Type *MiddleType = 0;
1983 switch (Size) {
1984 default: break;
1985 case 32: MiddleType = Type::Int32Ty; break;
1986 case 16: MiddleType = Type::Int16Ty; break;
1987 case 8: MiddleType = Type::Int8Ty; break;
1988 }
1989 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001990 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001991 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001992 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001993 }
1994 }
Chris Lattner66331a42004-04-10 22:01:55 +00001995 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001996
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001997 if (I.getType() == Type::Int1Ty)
1998 return BinaryOperator::CreateXor(LHS, RHS);
1999
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002000 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002001 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002002 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002003
2004 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2005 if (RHSI->getOpcode() == Instruction::Sub)
2006 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2007 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2008 }
2009 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2010 if (LHSI->getOpcode() == Instruction::Sub)
2011 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2012 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2013 }
Robert Bocchino71698282004-07-27 21:02:21 +00002014 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002015
Chris Lattner5c4afb92002-05-08 22:46:53 +00002016 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002017 // -A + -B --> -(A + B)
2018 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002019 if (LHS->getType()->isIntOrIntVector()) {
2020 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002021 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002022 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002023 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002024 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002025 }
2026
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002027 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002028 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002029
2030 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002031 if (!isa<Constant>(RHS))
2032 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002033 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002034
Misha Brukmanfd939082005-04-21 23:48:37 +00002035
Chris Lattner50af16a2004-11-13 19:50:12 +00002036 ConstantInt *C2;
2037 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2038 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002039 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002040
2041 // X*C1 + X*C2 --> X * (C1+C2)
2042 ConstantInt *C1;
2043 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002044 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002045 }
2046
2047 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002048 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002049 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002050
Chris Lattnere617c9e2007-01-05 02:17:46 +00002051 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002052 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2053 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002054
Chris Lattnerad3448c2003-02-18 19:57:07 +00002055
Chris Lattner564a7272003-08-13 19:01:45 +00002056 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002057 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002058 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2059 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002060
2061 // A+B --> A|B iff A and B have no bits set in common.
2062 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2063 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2064 APInt LHSKnownOne(IT->getBitWidth(), 0);
2065 APInt LHSKnownZero(IT->getBitWidth(), 0);
2066 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2067 if (LHSKnownZero != 0) {
2068 APInt RHSKnownOne(IT->getBitWidth(), 0);
2069 APInt RHSKnownZero(IT->getBitWidth(), 0);
2070 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2071
2072 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002073 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002074 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002075 }
2076 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002077
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002078 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002079 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002080 Value *W, *X, *Y, *Z;
2081 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2082 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2083 if (W != Y) {
2084 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002085 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002086 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002087 std::swap(W, X);
2088 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002089 std::swap(Y, Z);
2090 std::swap(W, X);
2091 }
2092 }
2093
2094 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002095 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002096 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002097 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002098 }
2099 }
2100 }
2101
Chris Lattner6b032052003-10-02 15:11:26 +00002102 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002103 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002104 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002105 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002106
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002107 // (X & FF00) + xx00 -> (X+xx00) & FF00
2108 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002109 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002110 if (Anded == CRHS) {
2111 // See if all bits from the first bit set in the Add RHS up are included
2112 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002113 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002114
2115 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002116 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002117
2118 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002119 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002120
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002121 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2122 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002123 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002124 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002125 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002126 }
2127 }
2128 }
2129
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002130 // Try to fold constant add into select arguments.
2131 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002132 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002133 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002134 }
2135
Reid Spencer1628cec2006-10-26 06:15:43 +00002136 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002137 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002138 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002139 CastInst *CI = dyn_cast<CastInst>(LHS);
2140 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002141 if (!CI) {
2142 CI = dyn_cast<CastInst>(RHS);
2143 Other = LHS;
2144 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002145 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002146 (CI->getType()->getPrimitiveSizeInBits() ==
2147 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002148 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002149 unsigned AS =
2150 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002151 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2152 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002153 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002154 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002155 }
2156 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002157
Chris Lattner42790482007-12-20 01:56:58 +00002158 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002159 {
2160 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2161 Value *Other = RHS;
2162 if (!SI) {
2163 SI = dyn_cast<SelectInst>(RHS);
2164 Other = LHS;
2165 }
Chris Lattner42790482007-12-20 01:56:58 +00002166 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002167 Value *TV = SI->getTrueValue();
2168 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002169 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002170
2171 // Can we fold the add into the argument of the select?
2172 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002173 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2174 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002175 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002176 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2177 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002178 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002179 }
2180 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002181
2182 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2183 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2184 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2185 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002186
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002187 // Check for (add (sext x), y), see if we can merge this into an
2188 // integer add followed by a sext.
2189 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2190 // (add (sext x), cst) --> (sext (add x, cst'))
2191 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2192 Constant *CI =
2193 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2194 if (LHSConv->hasOneUse() &&
2195 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2196 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2197 // Insert the new, smaller add.
2198 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2199 CI, "addconv");
2200 InsertNewInstBefore(NewAdd, I);
2201 return new SExtInst(NewAdd, I.getType());
2202 }
2203 }
2204
2205 // (add (sext x), (sext y)) --> (sext (add int x, y))
2206 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2207 // Only do this if x/y have the same type, if at last one of them has a
2208 // single use (so we don't increase the number of sexts), and if the
2209 // integer add will not overflow.
2210 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2211 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2212 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2213 RHSConv->getOperand(0))) {
2214 // Insert the new integer add.
2215 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2216 RHSConv->getOperand(0),
2217 "addconv");
2218 InsertNewInstBefore(NewAdd, I);
2219 return new SExtInst(NewAdd, I.getType());
2220 }
2221 }
2222 }
2223
2224 // Check for (add double (sitofp x), y), see if we can merge this into an
2225 // integer add followed by a promotion.
2226 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2227 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2228 // ... if the constant fits in the integer value. This is useful for things
2229 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2230 // requires a constant pool load, and generally allows the add to be better
2231 // instcombined.
2232 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2233 Constant *CI =
2234 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2235 if (LHSConv->hasOneUse() &&
2236 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2237 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2238 // Insert the new integer add.
2239 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2240 CI, "addconv");
2241 InsertNewInstBefore(NewAdd, I);
2242 return new SIToFPInst(NewAdd, I.getType());
2243 }
2244 }
2245
2246 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2247 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2248 // Only do this if x/y have the same type, if at last one of them has a
2249 // single use (so we don't increase the number of int->fp conversions),
2250 // and if the integer add will not overflow.
2251 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2252 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2253 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2254 RHSConv->getOperand(0))) {
2255 // Insert the new integer add.
2256 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2257 RHSConv->getOperand(0),
2258 "addconv");
2259 InsertNewInstBefore(NewAdd, I);
2260 return new SIToFPInst(NewAdd, I.getType());
2261 }
2262 }
2263 }
2264
Chris Lattner7e708292002-06-25 16:13:24 +00002265 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002266}
2267
Chris Lattner7e708292002-06-25 16:13:24 +00002268Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002269 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002270
Chris Lattner233f7dc2002-08-12 21:17:25 +00002271 if (Op0 == Op1) // sub X, X -> 0
2272 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002273
Chris Lattner233f7dc2002-08-12 21:17:25 +00002274 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002275 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002276 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002277
Chris Lattnere87597f2004-10-16 18:11:37 +00002278 if (isa<UndefValue>(Op0))
2279 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2280 if (isa<UndefValue>(Op1))
2281 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2282
Chris Lattnerd65460f2003-11-05 01:06:05 +00002283 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2284 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002285 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002286 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002287
Chris Lattnerd65460f2003-11-05 01:06:05 +00002288 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002289 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002290 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002291 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002292
Chris Lattner76b7a062007-01-15 07:02:54 +00002293 // -(X >>u 31) -> (X >>s 31)
2294 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002295 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002296 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002297 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002298 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002299 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002300 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002301 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002302 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002303 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002304 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002305 }
2306 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002307 }
2308 else if (SI->getOpcode() == Instruction::AShr) {
2309 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2310 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002311 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002312 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002313 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002314 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002315 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002316 }
2317 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002318 }
2319 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002320 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002321
2322 // Try to fold constant sub into select arguments.
2323 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002324 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002325 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002326
2327 if (isa<PHINode>(Op0))
2328 if (Instruction *NV = FoldOpIntoPhi(I))
2329 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002330 }
2331
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002332 if (I.getType() == Type::Int1Ty)
2333 return BinaryOperator::CreateXor(Op0, Op1);
2334
Chris Lattner43d84d62005-04-07 16:15:25 +00002335 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2336 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002337 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002338 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002339 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002340 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002341 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002342 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2343 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2344 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002345 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002346 Op1I->getOperand(0));
2347 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002348 }
2349
Chris Lattnerfd059242003-10-15 16:48:29 +00002350 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002351 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2352 // is not used by anyone else...
2353 //
Chris Lattner0517e722004-02-02 20:09:56 +00002354 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002355 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002356 // Swap the two operands of the subexpr...
2357 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2358 Op1I->setOperand(0, IIOp1);
2359 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002360
Chris Lattnera2881962003-02-18 19:28:33 +00002361 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002362 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002363 }
2364
2365 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2366 //
2367 if (Op1I->getOpcode() == Instruction::And &&
2368 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2369 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2370
Chris Lattnerf523d062004-06-09 05:08:07 +00002371 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002372 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2373 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002374 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002375
Reid Spencerac5209e2006-10-16 23:08:08 +00002376 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002377 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002378 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002379 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002380 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002381 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002382 ConstantExpr::getNeg(DivRHS));
2383
Chris Lattnerad3448c2003-02-18 19:57:07 +00002384 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002385 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002386 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002387 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002388 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002389 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002390
2391 // X - ((X / Y) * Y) --> X % Y
2392 if (Op1I->getOpcode() == Instruction::Mul)
2393 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2394 if (Op0 == I->getOperand(0) &&
2395 Op1I->getOperand(1) == I->getOperand(1)) {
2396 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002397 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002398 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002399 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002400 }
Chris Lattner40371712002-05-09 01:29:19 +00002401 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002402 }
Chris Lattnera2881962003-02-18 19:28:33 +00002403
Chris Lattner9919e3d2006-12-02 00:13:08 +00002404 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002405 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002406 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002407 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2408 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2409 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2410 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002411 } else if (Op0I->getOpcode() == Instruction::Sub) {
2412 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002413 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002414 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002415 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002416
Chris Lattner50af16a2004-11-13 19:50:12 +00002417 ConstantInt *C1;
2418 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002419 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002420 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002421
Chris Lattner50af16a2004-11-13 19:50:12 +00002422 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2423 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002424 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002425 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002426 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002427}
2428
Chris Lattnera0141b92007-07-15 20:42:37 +00002429/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2430/// comparison only checks the sign bit. If it only checks the sign bit, set
2431/// TrueIfSigned if the result of the comparison is true when the input value is
2432/// signed.
2433static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2434 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002435 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002436 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2437 TrueIfSigned = true;
2438 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002439 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2440 TrueIfSigned = true;
2441 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002442 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2443 TrueIfSigned = false;
2444 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002445 case ICmpInst::ICMP_UGT:
2446 // True if LHS u> RHS and RHS == high-bit-mask - 1
2447 TrueIfSigned = true;
2448 return RHS->getValue() ==
2449 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2450 case ICmpInst::ICMP_UGE:
2451 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2452 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002453 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002454 default:
2455 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002456 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002457}
2458
Chris Lattner7e708292002-06-25 16:13:24 +00002459Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002460 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002461 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002462
Chris Lattnere87597f2004-10-16 18:11:37 +00002463 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2465
Chris Lattner233f7dc2002-08-12 21:17:25 +00002466 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002467 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2468 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002469
2470 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002471 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002472 if (SI->getOpcode() == Instruction::Shl)
2473 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002474 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002475 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002476
Zhou Sheng843f07672007-04-19 05:39:12 +00002477 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002478 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2479 if (CI->equalsInt(1)) // X * 1 == X
2480 return ReplaceInstUsesWith(I, Op0);
2481 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002482 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002483
Zhou Sheng97b52c22007-03-29 01:57:21 +00002484 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002485 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002486 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002487 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002488 }
Robert Bocchino71698282004-07-27 21:02:21 +00002489 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002490 if (Op1F->isNullValue())
2491 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002492
Chris Lattnera2881962003-02-18 19:28:33 +00002493 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2494 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002495 // We need a better interface for long double here.
2496 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2497 if (Op1F->isExactlyValue(1.0))
2498 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002499 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002500
2501 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2502 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002503 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002504 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002505 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002506 Op1, "tmp");
2507 InsertNewInstBefore(Add, I);
2508 Value *C1C2 = ConstantExpr::getMul(Op1,
2509 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002510 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002511
2512 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002513
2514 // Try to fold constant mul into select arguments.
2515 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002516 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002517 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002518
2519 if (isa<PHINode>(Op0))
2520 if (Instruction *NV = FoldOpIntoPhi(I))
2521 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002522 }
2523
Chris Lattnera4f445b2003-03-10 23:23:04 +00002524 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2525 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002527
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002528 if (I.getType() == Type::Int1Ty)
2529 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2530
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002531 // If one of the operands of the multiply is a cast from a boolean value, then
2532 // we know the bool is either zero or one, so this is a 'masking' multiply.
2533 // See if we can simplify things based on how the boolean was originally
2534 // formed.
2535 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002536 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002537 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002538 BoolCast = CI;
2539 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002540 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002541 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002542 BoolCast = CI;
2543 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002544 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002545 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2546 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002547 bool TIS = false;
2548
Reid Spencere4d87aa2006-12-23 06:05:41 +00002549 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002550 // multiply into a shift/and combination.
2551 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002552 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2553 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002554 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002555 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002556 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002557 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002558 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002559 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002560 BoolCast->getOperand(0)->getName()+
2561 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002562
2563 // If the multiply type is not the same as the source type, sign extend
2564 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002565 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002566 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2567 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002568 Instruction::CastOps opcode =
2569 (SrcBits == DstBits ? Instruction::BitCast :
2570 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2571 V = InsertCastBefore(opcode, V, I.getType(), I);
2572 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002573
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002574 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002575 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002576 }
2577 }
2578 }
2579
Chris Lattner7e708292002-06-25 16:13:24 +00002580 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002581}
2582
Reid Spencer1628cec2006-10-26 06:15:43 +00002583/// This function implements the transforms on div instructions that work
2584/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2585/// used by the visitors to those instructions.
2586/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002587Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002588 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002589
Chris Lattner50b2ca42008-02-19 06:12:18 +00002590 // undef / X -> 0 for integer.
2591 // undef / X -> undef for FP (the undef could be a snan).
2592 if (isa<UndefValue>(Op0)) {
2593 if (Op0->getType()->isFPOrFPVector())
2594 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002596 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002597
2598 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002599 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002600 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002601
Chris Lattner25feae52008-01-28 00:58:18 +00002602 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2603 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002604 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002605 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2606 // the same basic block, then we replace the select with Y, and the
2607 // condition of the select with false (if the cond value is in the same BB).
2608 // If the select has uses other than the div, this allows them to be
2609 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2610 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002611 if (ST->isNullValue()) {
2612 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2613 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002614 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002615 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2616 I.setOperand(1, SI->getOperand(2));
2617 else
2618 UpdateValueUsesWith(SI, SI->getOperand(2));
2619 return &I;
2620 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002621
Chris Lattner25feae52008-01-28 00:58:18 +00002622 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2623 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002624 if (ST->isNullValue()) {
2625 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2626 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002627 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002628 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2629 I.setOperand(1, SI->getOperand(1));
2630 else
2631 UpdateValueUsesWith(SI, SI->getOperand(1));
2632 return &I;
2633 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002634 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002635
Reid Spencer1628cec2006-10-26 06:15:43 +00002636 return 0;
2637}
Misha Brukmanfd939082005-04-21 23:48:37 +00002638
Reid Spencer1628cec2006-10-26 06:15:43 +00002639/// This function implements the transforms common to both integer division
2640/// instructions (udiv and sdiv). It is called by the visitors to those integer
2641/// division instructions.
2642/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002643Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2645
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002646 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002647 if (Op0 == Op1) {
2648 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2649 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2650 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2651 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2652 }
2653
2654 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2655 return ReplaceInstUsesWith(I, CI);
2656 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002657
Reid Spencer1628cec2006-10-26 06:15:43 +00002658 if (Instruction *Common = commonDivTransforms(I))
2659 return Common;
2660
2661 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2662 // div X, 1 == X
2663 if (RHS->equalsInt(1))
2664 return ReplaceInstUsesWith(I, Op0);
2665
2666 // (X / C1) / C2 -> X / (C1*C2)
2667 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2668 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2669 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002670 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2671 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2672 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002673 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002674 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002675 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002676
Reid Spencerbca0e382007-03-23 20:05:17 +00002677 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002678 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2679 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2680 return R;
2681 if (isa<PHINode>(Op0))
2682 if (Instruction *NV = FoldOpIntoPhi(I))
2683 return NV;
2684 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002685 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002686
Chris Lattnera2881962003-02-18 19:28:33 +00002687 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002688 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002689 if (LHS->equalsInt(0))
2690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2691
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002692 // It can't be division by zero, hence it must be division by one.
2693 if (I.getType() == Type::Int1Ty)
2694 return ReplaceInstUsesWith(I, Op0);
2695
Reid Spencer1628cec2006-10-26 06:15:43 +00002696 return 0;
2697}
2698
2699Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2700 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2701
2702 // Handle the integer div common cases
2703 if (Instruction *Common = commonIDivTransforms(I))
2704 return Common;
2705
2706 // X udiv C^2 -> X >> C
2707 // Check to see if this is an unsigned division with an exact power of 2,
2708 // if so, convert to a right shift.
2709 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002710 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002711 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002712 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002713 }
2714
2715 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002716 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002717 if (RHSI->getOpcode() == Instruction::Shl &&
2718 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002719 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002720 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002721 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002722 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002723 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002724 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002725 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002726 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002728 }
2729 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002730 }
2731
Reid Spencer1628cec2006-10-26 06:15:43 +00002732 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2733 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002734 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002735 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002736 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002737 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002738 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002739 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002740 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002741 // Construct the "on true" case of the select
2742 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002743 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002744 Op0, TC, SI->getName()+".t");
2745 TSI = InsertNewInstBefore(TSI, I);
2746
2747 // Construct the "on false" case of the select
2748 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002749 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002750 Op0, FC, SI->getName()+".f");
2751 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002752
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002753 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002754 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002755 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002756 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002757 return 0;
2758}
2759
Reid Spencer1628cec2006-10-26 06:15:43 +00002760Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2761 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2762
2763 // Handle the integer div common cases
2764 if (Instruction *Common = commonIDivTransforms(I))
2765 return Common;
2766
2767 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2768 // sdiv X, -1 == -X
2769 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002771
2772 // -X/C -> X/-C
2773 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002774 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002775 }
2776
2777 // If the sign bits of both operands are zero (i.e. we can prove they are
2778 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002779 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002780 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002781 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002782 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002783 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002784 }
2785 }
2786
2787 return 0;
2788}
2789
2790Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2791 return commonDivTransforms(I);
2792}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002793
Reid Spencer0a783f72006-11-02 01:53:59 +00002794/// This function implements the transforms on rem instructions that work
2795/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2796/// is used by the visitors to those instructions.
2797/// @brief Transforms common to all three rem instructions
2798Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002799 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002800
Chris Lattner50b2ca42008-02-19 06:12:18 +00002801 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002802 if (Constant *LHS = dyn_cast<Constant>(Op0))
2803 if (LHS->isNullValue())
2804 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2805
Chris Lattner50b2ca42008-02-19 06:12:18 +00002806 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2807 if (I.getType()->isFPOrFPVector())
2808 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002809 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002810 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002811 if (isa<UndefValue>(Op1))
2812 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002813
2814 // Handle cases involving: rem X, (select Cond, Y, Z)
2815 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2816 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2817 // the same basic block, then we replace the select with Y, and the
2818 // condition of the select with false (if the cond value is in the same
2819 // BB). If the select has uses other than the div, this allows them to be
2820 // simplified also.
2821 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2822 if (ST->isNullValue()) {
2823 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2824 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002825 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002826 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2827 I.setOperand(1, SI->getOperand(2));
2828 else
2829 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002830 return &I;
2831 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002832 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2833 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2834 if (ST->isNullValue()) {
2835 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2836 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002837 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002838 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2839 I.setOperand(1, SI->getOperand(1));
2840 else
2841 UpdateValueUsesWith(SI, SI->getOperand(1));
2842 return &I;
2843 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002844 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002845
Reid Spencer0a783f72006-11-02 01:53:59 +00002846 return 0;
2847}
2848
2849/// This function implements the transforms common to both integer remainder
2850/// instructions (urem and srem). It is called by the visitors to those integer
2851/// remainder instructions.
2852/// @brief Common integer remainder transforms
2853Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2854 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2855
2856 if (Instruction *common = commonRemTransforms(I))
2857 return common;
2858
Chris Lattner857e8cd2004-12-12 21:48:58 +00002859 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002860 // X % 0 == undef, we don't need to preserve faults!
2861 if (RHS->equalsInt(0))
2862 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2863
Chris Lattnera2881962003-02-18 19:28:33 +00002864 if (RHS->equalsInt(1)) // X % 1 == 0
2865 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2866
Chris Lattner97943922006-02-28 05:49:21 +00002867 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2868 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2869 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2870 return R;
2871 } else if (isa<PHINode>(Op0I)) {
2872 if (Instruction *NV = FoldOpIntoPhi(I))
2873 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002874 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002875
2876 // See if we can fold away this rem instruction.
2877 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2878 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2879 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2880 KnownZero, KnownOne))
2881 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002882 }
Chris Lattnera2881962003-02-18 19:28:33 +00002883 }
2884
Reid Spencer0a783f72006-11-02 01:53:59 +00002885 return 0;
2886}
2887
2888Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2889 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2890
2891 if (Instruction *common = commonIRemTransforms(I))
2892 return common;
2893
2894 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2895 // X urem C^2 -> X and C
2896 // Check to see if this is an unsigned remainder with an exact power of 2,
2897 // if so, convert to a bitwise and.
2898 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002899 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002900 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002901 }
2902
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002903 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002904 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2905 if (RHSI->getOpcode() == Instruction::Shl &&
2906 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002907 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002908 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002909 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002910 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002911 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002912 }
2913 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002914 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002915
Reid Spencer0a783f72006-11-02 01:53:59 +00002916 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2917 // where C1&C2 are powers of two.
2918 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2919 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2920 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2921 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002922 if ((STO->getValue().isPowerOf2()) &&
2923 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002924 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002925 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002926 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002927 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002928 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002929 }
2930 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002931 }
2932
Chris Lattner3f5b8772002-05-06 16:14:14 +00002933 return 0;
2934}
2935
Reid Spencer0a783f72006-11-02 01:53:59 +00002936Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2938
Dan Gohmancff55092007-11-05 23:16:33 +00002939 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002940 if (Instruction *common = commonIRemTransforms(I))
2941 return common;
2942
2943 if (Value *RHSNeg = dyn_castNegVal(Op1))
2944 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002945 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002946 // X % -Y -> X % Y
2947 AddUsesToWorkList(I);
2948 I.setOperand(1, RHSNeg);
2949 return &I;
2950 }
2951
Dan Gohmancff55092007-11-05 23:16:33 +00002952 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002953 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002954 if (I.getType()->isInteger()) {
2955 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2956 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2957 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002959 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002960 }
2961
2962 return 0;
2963}
2964
2965Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002966 return commonRemTransforms(I);
2967}
2968
Chris Lattner8b170942002-08-09 23:47:40 +00002969// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002970static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002971 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002972 if (!isSigned)
2973 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2974 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002975}
2976
2977// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002978static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002979 if (!isSigned)
2980 return C->getValue() == 1; // unsigned
2981
2982 // Calculate 1111111111000000000000
2983 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2984 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002985}
2986
Chris Lattner457dd822004-06-09 07:59:58 +00002987// isOneBitSet - Return true if there is exactly one bit set in the specified
2988// constant.
2989static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002990 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002991}
2992
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002993// isHighOnes - Return true if the constant is of the form 1+0+.
2994// This is the same as lowones(~X).
2995static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002996 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002997}
2998
Reid Spencere4d87aa2006-12-23 06:05:41 +00002999/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003000/// are carefully arranged to allow folding of expressions such as:
3001///
3002/// (A < B) | (A > B) --> (A != B)
3003///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003004/// Note that this is only valid if the first and second predicates have the
3005/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003006///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003007/// Three bits are used to represent the condition, as follows:
3008/// 0 A > B
3009/// 1 A == B
3010/// 2 A < B
3011///
3012/// <=> Value Definition
3013/// 000 0 Always false
3014/// 001 1 A > B
3015/// 010 2 A == B
3016/// 011 3 A >= B
3017/// 100 4 A < B
3018/// 101 5 A != B
3019/// 110 6 A <= B
3020/// 111 7 Always true
3021///
3022static unsigned getICmpCode(const ICmpInst *ICI) {
3023 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003024 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003025 case ICmpInst::ICMP_UGT: return 1; // 001
3026 case ICmpInst::ICMP_SGT: return 1; // 001
3027 case ICmpInst::ICMP_EQ: return 2; // 010
3028 case ICmpInst::ICMP_UGE: return 3; // 011
3029 case ICmpInst::ICMP_SGE: return 3; // 011
3030 case ICmpInst::ICMP_ULT: return 4; // 100
3031 case ICmpInst::ICMP_SLT: return 4; // 100
3032 case ICmpInst::ICMP_NE: return 5; // 101
3033 case ICmpInst::ICMP_ULE: return 6; // 110
3034 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003035 // True -> 7
3036 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003037 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003038 return 0;
3039 }
3040}
3041
Reid Spencere4d87aa2006-12-23 06:05:41 +00003042/// getICmpValue - This is the complement of getICmpCode, which turns an
3043/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003044/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003045/// of predicate to use in new icmp instructions.
3046static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3047 switch (code) {
3048 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003049 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003050 case 1:
3051 if (sign)
3052 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3053 else
3054 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3055 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3056 case 3:
3057 if (sign)
3058 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3059 else
3060 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3061 case 4:
3062 if (sign)
3063 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3064 else
3065 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3066 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3067 case 6:
3068 if (sign)
3069 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3070 else
3071 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003072 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003073 }
3074}
3075
Reid Spencere4d87aa2006-12-23 06:05:41 +00003076static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3077 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3078 (ICmpInst::isSignedPredicate(p1) &&
3079 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3080 (ICmpInst::isSignedPredicate(p2) &&
3081 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3082}
3083
3084namespace {
3085// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3086struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003087 InstCombiner &IC;
3088 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003089 ICmpInst::Predicate pred;
3090 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3091 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3092 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003093 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003094 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3095 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003096 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3097 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003098 return false;
3099 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003100 Instruction *apply(Instruction &Log) const {
3101 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3102 if (ICI->getOperand(0) != LHS) {
3103 assert(ICI->getOperand(1) == LHS);
3104 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003105 }
3106
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003107 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003108 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003109 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003110 unsigned Code;
3111 switch (Log.getOpcode()) {
3112 case Instruction::And: Code = LHSCode & RHSCode; break;
3113 case Instruction::Or: Code = LHSCode | RHSCode; break;
3114 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003115 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003116 }
3117
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003118 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3119 ICmpInst::isSignedPredicate(ICI->getPredicate());
3120
3121 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003122 if (Instruction *I = dyn_cast<Instruction>(RV))
3123 return I;
3124 // Otherwise, it's a constant boolean value...
3125 return IC.ReplaceInstUsesWith(Log, RV);
3126 }
3127};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003128} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003129
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003130// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3131// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003132// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003133Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003134 ConstantInt *OpRHS,
3135 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003136 BinaryOperator &TheAnd) {
3137 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003138 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003139 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003140 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003141
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003142 switch (Op->getOpcode()) {
3143 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003144 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003145 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003146 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003147 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003148 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003149 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003150 }
3151 break;
3152 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003153 if (Together == AndRHS) // (X | C) & C --> C
3154 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003155
Chris Lattner6e7ba452005-01-01 16:22:27 +00003156 if (Op->hasOneUse() && Together != OpRHS) {
3157 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003158 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003159 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003160 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003161 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003162 }
3163 break;
3164 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003165 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003166 // Adding a one to a single bit bit-field should be turned into an XOR
3167 // of the bit. First thing to check is to see if this AND is with a
3168 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003169 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003170
3171 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003172 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003173 // Ok, at this point, we know that we are masking the result of the
3174 // ADD down to exactly one bit. If the constant we are adding has
3175 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003176 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003177
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003178 // Check to see if any bits below the one bit set in AndRHSV are set.
3179 if ((AddRHS & (AndRHSV-1)) == 0) {
3180 // If not, the only thing that can effect the output of the AND is
3181 // the bit specified by AndRHSV. If that bit is set, the effect of
3182 // the XOR is to toggle the bit. If it is clear, then the ADD has
3183 // no effect.
3184 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3185 TheAnd.setOperand(0, X);
3186 return &TheAnd;
3187 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003188 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003189 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003190 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003191 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003192 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003193 }
3194 }
3195 }
3196 }
3197 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003198
3199 case Instruction::Shl: {
3200 // We know that the AND will not produce any of the bits shifted in, so if
3201 // the anded constant includes them, clear them now!
3202 //
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 ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3206 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003207
Zhou Sheng290bec52007-03-29 08:15:12 +00003208 if (CI->getValue() == ShlMask) {
3209 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003210 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3211 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003212 TheAnd.setOperand(1, CI);
3213 return &TheAnd;
3214 }
3215 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003216 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003217 case Instruction::LShr:
3218 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003219 // We know that the AND will not produce any of the bits shifted in, so if
3220 // the anded constant includes them, clear them now! This only applies to
3221 // unsigned shifts, because a signed shr may bring in set bits!
3222 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003223 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003224 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003225 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3226 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003227
Zhou Sheng290bec52007-03-29 08:15:12 +00003228 if (CI->getValue() == ShrMask) {
3229 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003230 return ReplaceInstUsesWith(TheAnd, Op);
3231 } else if (CI != AndRHS) {
3232 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3233 return &TheAnd;
3234 }
3235 break;
3236 }
3237 case Instruction::AShr:
3238 // Signed shr.
3239 // See if this is shifting in some sign extension, then masking it out
3240 // with an and.
3241 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003242 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003243 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003244 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3245 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003246 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003247 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003248 // Make the argument unsigned.
3249 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003250 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003251 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003252 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003253 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003254 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003255 }
3256 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003257 }
3258 return 0;
3259}
3260
Chris Lattner8b170942002-08-09 23:47:40 +00003261
Chris Lattnera96879a2004-09-29 17:40:11 +00003262/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3263/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003264/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3265/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003266/// insert new instructions.
3267Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003268 bool isSigned, bool Inside,
3269 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003270 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003271 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003272 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003273
Chris Lattnera96879a2004-09-29 17:40:11 +00003274 if (Inside) {
3275 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003276 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003277
Reid Spencere4d87aa2006-12-23 06:05:41 +00003278 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003279 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003280 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003281 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3282 return new ICmpInst(pred, V, Hi);
3283 }
3284
3285 // Emit V-Lo <u Hi-Lo
3286 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003287 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003288 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003289 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3290 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003291 }
3292
3293 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003294 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003295
Reid Spencere4e40032007-03-21 23:19:50 +00003296 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003297 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003298 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003299 ICmpInst::Predicate pred = (isSigned ?
3300 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3301 return new ICmpInst(pred, V, Hi);
3302 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003303
Reid Spencere4e40032007-03-21 23:19:50 +00003304 // Emit V-Lo >u Hi-1-Lo
3305 // Note that Hi has already had one subtracted from it, above.
3306 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003307 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003308 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003309 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3310 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003311}
3312
Chris Lattner7203e152005-09-18 07:22:02 +00003313// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3314// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3315// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3316// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003317static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003318 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003319 uint32_t BitWidth = Val->getType()->getBitWidth();
3320 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003321
3322 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003323 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003324 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003325 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003326 return true;
3327}
3328
Chris Lattner7203e152005-09-18 07:22:02 +00003329/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3330/// where isSub determines whether the operator is a sub. If we can fold one of
3331/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003332///
3333/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3334/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3335/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3336///
3337/// return (A +/- B).
3338///
3339Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003340 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003341 Instruction &I) {
3342 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3343 if (!LHSI || LHSI->getNumOperands() != 2 ||
3344 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3345
3346 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3347
3348 switch (LHSI->getOpcode()) {
3349 default: return 0;
3350 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003351 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003352 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003353 if ((Mask->getValue().countLeadingZeros() +
3354 Mask->getValue().countPopulation()) ==
3355 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003356 break;
3357
3358 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3359 // part, we don't need any explicit masks to take them out of A. If that
3360 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003361 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003362 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003363 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003364 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003365 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003366 break;
3367 }
3368 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003369 return 0;
3370 case Instruction::Or:
3371 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003372 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003373 if ((Mask->getValue().countLeadingZeros() +
3374 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003375 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003376 break;
3377 return 0;
3378 }
3379
3380 Instruction *New;
3381 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003382 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003383 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003384 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003385 return InsertNewInstBefore(New, I);
3386}
3387
Chris Lattner7e708292002-06-25 16:13:24 +00003388Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003389 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003390 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003391
Chris Lattnere87597f2004-10-16 18:11:37 +00003392 if (isa<UndefValue>(Op1)) // X & undef -> 0
3393 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3394
Chris Lattner6e7ba452005-01-01 16:22:27 +00003395 // and X, X = X
3396 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003397 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003398
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003399 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003400 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003401 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003402 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3403 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3404 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003405 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003406 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003407 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003408 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003409 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003410 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003411 } else if (isa<ConstantAggregateZero>(Op1)) {
3412 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003413 }
3414 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003415
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003416 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003417 const APInt& AndRHSMask = AndRHS->getValue();
3418 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003419
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003420 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003421 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003422 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003423 Value *Op0LHS = Op0I->getOperand(0);
3424 Value *Op0RHS = Op0I->getOperand(1);
3425 switch (Op0I->getOpcode()) {
3426 case Instruction::Xor:
3427 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003428 // If the mask is only needed on one incoming arm, push it up.
3429 if (Op0I->hasOneUse()) {
3430 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3431 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003432 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003433 Op0RHS->getName()+".masked");
3434 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003435 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003436 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003437 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003438 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003439 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3440 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003441 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003442 Op0LHS->getName()+".masked");
3443 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003444 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003445 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3446 }
3447 }
3448
Chris Lattner6e7ba452005-01-01 16:22:27 +00003449 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003450 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003451 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3452 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3453 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3454 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003455 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003456 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003457 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003458 break;
3459
3460 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003461 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3462 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3463 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3464 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003465 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003466 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003467 }
3468
Chris Lattner58403262003-07-23 19:25:52 +00003469 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003470 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003471 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003472 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003473 // If this is an integer truncation or change from signed-to-unsigned, and
3474 // if the source is an and/or with immediate, transform it. This
3475 // frequently occurs for bitfield accesses.
3476 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003477 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003478 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003479 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003480 if (CastOp->getOpcode() == Instruction::And) {
3481 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003482 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3483 // This will fold the two constants together, which may allow
3484 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003485 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003486 CastOp->getOperand(0), I.getType(),
3487 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003488 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003489 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003490 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003491 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003492 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003493 } else if (CastOp->getOpcode() == Instruction::Or) {
3494 // Change: and (cast (or X, C1) to T), C2
3495 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003496 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003497 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3498 return ReplaceInstUsesWith(I, AndRHS);
3499 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003500 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003501 }
Chris Lattner06782f82003-07-23 19:36:21 +00003502 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003503
3504 // Try to fold constant and into select arguments.
3505 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003506 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003507 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003508 if (isa<PHINode>(Op0))
3509 if (Instruction *NV = FoldOpIntoPhi(I))
3510 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003511 }
3512
Chris Lattner8d969642003-03-10 23:06:50 +00003513 Value *Op0NotVal = dyn_castNotVal(Op0);
3514 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003515
Chris Lattner5b62aa72004-06-18 06:07:51 +00003516 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3518
Misha Brukmancb6267b2004-07-30 12:50:08 +00003519 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003520 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003521 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003522 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003523 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003524 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003525 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003526
3527 {
Chris Lattner003b6202007-06-15 05:58:24 +00003528 Value *A = 0, *B = 0, *C = 0, *D = 0;
3529 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003530 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3531 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003532
3533 // (A|B) & ~(A&B) -> A^B
3534 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3535 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003536 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003537 }
3538 }
3539
3540 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003541 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3542 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003543
3544 // ~(A&B) & (A|B) -> A^B
3545 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3546 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003547 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003548 }
3549 }
Chris Lattner64daab52006-04-01 08:03:55 +00003550
3551 if (Op0->hasOneUse() &&
3552 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3553 if (A == Op1) { // (A^B)&A -> A&(A^B)
3554 I.swapOperands(); // Simplify below
3555 std::swap(Op0, Op1);
3556 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3557 cast<BinaryOperator>(Op0)->swapOperands();
3558 I.swapOperands(); // Simplify below
3559 std::swap(Op0, Op1);
3560 }
3561 }
3562 if (Op1->hasOneUse() &&
3563 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3564 if (B == Op0) { // B&(A^B) -> B&(B^A)
3565 cast<BinaryOperator>(Op1)->swapOperands();
3566 std::swap(A, B);
3567 }
3568 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003569 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003570 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003571 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003572 }
3573 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003574 }
3575
Reid Spencere4d87aa2006-12-23 06:05:41 +00003576 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3577 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3578 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003579 return R;
3580
Chris Lattner955f3312004-09-28 21:48:02 +00003581 Value *LHSVal, *RHSVal;
3582 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003583 ICmpInst::Predicate LHSCC, RHSCC;
3584 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3585 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3586 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3587 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3588 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3589 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3590 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003591 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3592
3593 // Don't try to fold ICMP_SLT + ICMP_ULT.
3594 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3595 ICmpInst::isSignedPredicate(LHSCC) ==
3596 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003597 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003598 ICmpInst::Predicate GT;
3599 if (ICmpInst::isSignedPredicate(LHSCC) ||
3600 (ICmpInst::isEquality(LHSCC) &&
3601 ICmpInst::isSignedPredicate(RHSCC)))
3602 GT = ICmpInst::ICMP_SGT;
3603 else
3604 GT = ICmpInst::ICMP_UGT;
3605
Reid Spencere4d87aa2006-12-23 06:05:41 +00003606 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3607 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003608 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003609 std::swap(LHS, RHS);
3610 std::swap(LHSCst, RHSCst);
3611 std::swap(LHSCC, RHSCC);
3612 }
3613
Reid Spencere4d87aa2006-12-23 06:05:41 +00003614 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003615 // comparing a value against two constants and and'ing the result
3616 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003617 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3618 // (from the FoldICmpLogical check above), that the two constants
3619 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003620 assert(LHSCst != RHSCst && "Compares not folded above?");
3621
3622 switch (LHSCC) {
3623 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003624 case ICmpInst::ICMP_EQ:
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 == 13 & X == 15) -> false
3628 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3629 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003630 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003631 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3632 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3633 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003634 return ReplaceInstUsesWith(I, LHS);
3635 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003637 switch (RHSCC) {
3638 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 case ICmpInst::ICMP_ULT:
3640 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3641 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3642 break; // (X != 13 & X u< 15) -> no change
3643 case ICmpInst::ICMP_SLT:
3644 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3645 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3646 break; // (X != 13 & X s< 15) -> no change
3647 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3648 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3649 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003650 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 case ICmpInst::ICMP_NE:
3652 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003653 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003654 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003655 LHSVal->getName()+".off");
3656 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003657 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3658 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003659 }
3660 break; // (X != 13 & X != 15) -> no change
3661 }
3662 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003663 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003664 switch (RHSCC) {
3665 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3667 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003668 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3670 break;
3671 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3672 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003673 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3675 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003676 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677 break;
3678 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003679 switch (RHSCC) {
3680 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3682 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3685 break;
3686 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3687 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003688 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003689 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3690 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003691 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 break;
3693 case ICmpInst::ICMP_UGT:
3694 switch (RHSCC) {
3695 default: assert(0 && "Unknown integer condition code!");
3696 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3697 return ReplaceInstUsesWith(I, LHS);
3698 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3699 return ReplaceInstUsesWith(I, RHS);
3700 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3701 break;
3702 case ICmpInst::ICMP_NE:
3703 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3704 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3705 break; // (X u> 13 & X != 15) -> no change
3706 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3707 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3708 true, I);
3709 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3710 break;
3711 }
3712 break;
3713 case ICmpInst::ICMP_SGT:
3714 switch (RHSCC) {
3715 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003716 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3718 return ReplaceInstUsesWith(I, RHS);
3719 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3720 break;
3721 case ICmpInst::ICMP_NE:
3722 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3723 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3724 break; // (X s> 13 & X != 15) -> no change
3725 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3726 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3727 true, I);
3728 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3729 break;
3730 }
3731 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003732 }
3733 }
3734 }
3735
Chris Lattner6fc205f2006-05-05 06:39:07 +00003736 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003737 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3738 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3739 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3740 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003741 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003742 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003743 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3744 I.getType(), TD) &&
3745 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3746 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003747 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003748 Op1C->getOperand(0),
3749 I.getName());
3750 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003751 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003752 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003753 }
Chris Lattnere511b742006-11-14 07:46:50 +00003754
3755 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003756 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3757 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3758 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003759 SI0->getOperand(1) == SI1->getOperand(1) &&
3760 (SI0->hasOneUse() || SI1->hasOneUse())) {
3761 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003762 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003763 SI1->getOperand(0),
3764 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003765 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003766 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003767 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003768 }
3769
Chris Lattner99c65742007-10-24 05:38:08 +00003770 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3771 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3772 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3773 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3774 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3775 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3776 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3777 // If either of the constants are nans, then the whole thing returns
3778 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003779 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003780 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3781 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3782 RHS->getOperand(0));
3783 }
3784 }
3785 }
3786
Chris Lattner7e708292002-06-25 16:13:24 +00003787 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003788}
3789
Chris Lattnerafe91a52006-06-15 19:07:26 +00003790/// CollectBSwapParts - Look to see if the specified value defines a single byte
3791/// in the result. If it does, and if the specified byte hasn't been filled in
3792/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003793static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003794 Instruction *I = dyn_cast<Instruction>(V);
3795 if (I == 0) return true;
3796
3797 // If this is an or instruction, it is an inner node of the bswap.
3798 if (I->getOpcode() == Instruction::Or)
3799 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3800 CollectBSwapParts(I->getOperand(1), ByteValues);
3801
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003802 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003803 // If this is a shift by a constant int, and it is "24", then its operand
3804 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003805 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003806 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003807 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003808 8*(ByteValues.size()-1))
3809 return true;
3810
3811 unsigned DestNo;
3812 if (I->getOpcode() == Instruction::Shl) {
3813 // X << 24 defines the top byte with the lowest of the input bytes.
3814 DestNo = ByteValues.size()-1;
3815 } else {
3816 // X >>u 24 defines the low byte with the highest of the input bytes.
3817 DestNo = 0;
3818 }
3819
3820 // If the destination byte value is already defined, the values are or'd
3821 // together, which isn't a bswap (unless it's an or of the same bits).
3822 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3823 return true;
3824 ByteValues[DestNo] = I->getOperand(0);
3825 return false;
3826 }
3827
3828 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3829 // don't have this.
3830 Value *Shift = 0, *ShiftLHS = 0;
3831 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3832 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3833 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3834 return true;
3835 Instruction *SI = cast<Instruction>(Shift);
3836
3837 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003838 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3839 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003840 return true;
3841
3842 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3843 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003844 if (AndAmt->getValue().getActiveBits() > 64)
3845 return true;
3846 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003847 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003848 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003849 break;
3850 // Unknown mask for bswap.
3851 if (DestByte == ByteValues.size()) return true;
3852
Reid Spencerb83eb642006-10-20 07:07:24 +00003853 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003854 unsigned SrcByte;
3855 if (SI->getOpcode() == Instruction::Shl)
3856 SrcByte = DestByte - ShiftBytes;
3857 else
3858 SrcByte = DestByte + ShiftBytes;
3859
3860 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3861 if (SrcByte != ByteValues.size()-DestByte-1)
3862 return true;
3863
3864 // If the destination byte value is already defined, the values are or'd
3865 // together, which isn't a bswap (unless it's an or of the same bits).
3866 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3867 return true;
3868 ByteValues[DestByte] = SI->getOperand(0);
3869 return false;
3870}
3871
3872/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3873/// If so, insert the new bswap intrinsic and return it.
3874Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003875 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3876 if (!ITy || ITy->getBitWidth() % 16)
3877 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003878
3879 /// ByteValues - For each byte of the result, we keep track of which value
3880 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003881 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003882 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003883
3884 // Try to find all the pieces corresponding to the bswap.
3885 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3886 CollectBSwapParts(I.getOperand(1), ByteValues))
3887 return 0;
3888
3889 // Check to see if all of the bytes come from the same value.
3890 Value *V = ByteValues[0];
3891 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3892
3893 // Check to make sure that all of the bytes come from the same value.
3894 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3895 if (ByteValues[i] != V)
3896 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003897 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003898 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003899 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003900 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003901}
3902
3903
Chris Lattner7e708292002-06-25 16:13:24 +00003904Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003905 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003907
Chris Lattner42593e62007-03-24 23:56:43 +00003908 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003909 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003910
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003911 // or X, X = X
3912 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003913 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003914
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003915 // See if we can simplify any instructions used by the instruction whose sole
3916 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003917 if (!isa<VectorType>(I.getType())) {
3918 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3919 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3920 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3921 KnownZero, KnownOne))
3922 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003923 } else if (isa<ConstantAggregateZero>(Op1)) {
3924 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3925 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3926 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3927 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003928 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003929
3930
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003931
Chris Lattner3f5b8772002-05-06 16:14:14 +00003932 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003933 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003934 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003935 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3936 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003937 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003938 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003939 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003940 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003941 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003942 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003943
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003944 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3945 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003946 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003947 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003948 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003949 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003950 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003951 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003952
3953 // Try to fold constant and into select arguments.
3954 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003955 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003956 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003957 if (isa<PHINode>(Op0))
3958 if (Instruction *NV = FoldOpIntoPhi(I))
3959 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003960 }
3961
Chris Lattner4f637d42006-01-06 17:59:59 +00003962 Value *A = 0, *B = 0;
3963 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003964
3965 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3966 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3967 return ReplaceInstUsesWith(I, Op1);
3968 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3969 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3970 return ReplaceInstUsesWith(I, Op0);
3971
Chris Lattner6423d4c2006-07-10 20:25:24 +00003972 // (A | B) | C and A | (B | C) -> bswap if possible.
3973 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003974 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003975 match(Op1, m_Or(m_Value(), m_Value())) ||
3976 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3977 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003978 if (Instruction *BSwap = MatchBSwap(I))
3979 return BSwap;
3980 }
3981
Chris Lattner6e4c6492005-05-09 04:58:36 +00003982 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3983 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003984 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003985 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003986 InsertNewInstBefore(NOr, I);
3987 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003988 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003989 }
3990
3991 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3992 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003993 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003994 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003995 InsertNewInstBefore(NOr, I);
3996 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003997 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003998 }
3999
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004000 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004001 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004002 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4003 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004004 Value *V1 = 0, *V2 = 0, *V3 = 0;
4005 C1 = dyn_cast<ConstantInt>(C);
4006 C2 = dyn_cast<ConstantInt>(D);
4007 if (C1 && C2) { // (A & C1)|(B & C2)
4008 // If we have: ((V + N) & C1) | (V & C2)
4009 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4010 // replace with V+N.
4011 if (C1->getValue() == ~C2->getValue()) {
4012 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4013 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4014 // Add commutes, try both ways.
4015 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4016 return ReplaceInstUsesWith(I, A);
4017 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4018 return ReplaceInstUsesWith(I, A);
4019 }
4020 // Or commutes, try both ways.
4021 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4022 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4023 // Add commutes, try both ways.
4024 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4025 return ReplaceInstUsesWith(I, B);
4026 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4027 return ReplaceInstUsesWith(I, B);
4028 }
4029 }
Chris Lattner044e5332007-04-08 08:01:49 +00004030 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004031 }
4032
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004033 // Check to see if we have any common things being and'ed. If so, find the
4034 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004035 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4036 if (A == B) // (A & C)|(A & D) == A & (C|D)
4037 V1 = A, V2 = C, V3 = D;
4038 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4039 V1 = A, V2 = B, V3 = C;
4040 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4041 V1 = C, V2 = A, V3 = D;
4042 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4043 V1 = C, V2 = A, V3 = B;
4044
4045 if (V1) {
4046 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004047 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4048 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004049 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004050 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004051 }
Chris Lattnere511b742006-11-14 07:46:50 +00004052
4053 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004054 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4055 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4056 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004057 SI0->getOperand(1) == SI1->getOperand(1) &&
4058 (SI0->hasOneUse() || SI1->hasOneUse())) {
4059 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004060 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004061 SI1->getOperand(0),
4062 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004063 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004064 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004065 }
4066 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004067
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004068 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4069 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004070 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004071 } else {
4072 A = 0;
4073 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004074 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004075 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4076 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004077 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004078
Misha Brukmancb6267b2004-07-30 12:50:08 +00004079 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004080 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004081 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004082 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004083 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004084 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004085 }
Chris Lattnera2881962003-02-18 19:28:33 +00004086
Reid Spencere4d87aa2006-12-23 06:05:41 +00004087 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4088 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4089 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004090 return R;
4091
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004092 Value *LHSVal, *RHSVal;
4093 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004094 ICmpInst::Predicate LHSCC, RHSCC;
4095 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4096 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4097 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4098 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4099 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4100 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4101 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004102 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4103 // We can't fold (ugt x, C) | (sgt x, C2).
4104 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004105 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004106 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004107 bool NeedsSwap;
4108 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004109 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004110 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004111 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004112
4113 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004114 std::swap(LHS, RHS);
4115 std::swap(LHSCst, RHSCst);
4116 std::swap(LHSCC, RHSCC);
4117 }
4118
Reid Spencere4d87aa2006-12-23 06:05:41 +00004119 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004120 // comparing a value against two constants and or'ing the result
4121 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004122 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4123 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004124 // equal.
4125 assert(LHSCst != RHSCst && "Compares not folded above?");
4126
4127 switch (LHSCC) {
4128 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004129 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004130 switch (RHSCC) {
4131 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004132 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004133 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4134 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004136 LHSVal->getName()+".off");
4137 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004138 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004139 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004140 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004141 break; // (X == 13 | X == 15) -> no change
4142 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4143 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004144 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004145 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4146 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4147 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004148 return ReplaceInstUsesWith(I, RHS);
4149 }
4150 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004151 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004152 switch (RHSCC) {
4153 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4155 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4156 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004157 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004158 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4159 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4160 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004161 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004162 }
4163 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004165 switch (RHSCC) {
4166 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004167 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004168 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004169 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004170 // If RHSCst is [us]MAXINT, it is always false. Not handling
4171 // this can cause overflow.
4172 if (RHSCst->isMaxValue(false))
4173 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004174 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4175 false, I);
4176 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4177 break;
4178 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4179 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004180 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004181 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4182 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004183 }
4184 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004185 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004186 switch (RHSCC) {
4187 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004188 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4189 break;
4190 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004191 // If RHSCst is [us]MAXINT, it is always false. Not handling
4192 // this can cause overflow.
4193 if (RHSCst->isMaxValue(true))
4194 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004195 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4196 false, I);
4197 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4198 break;
4199 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4200 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4201 return ReplaceInstUsesWith(I, RHS);
4202 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4203 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004204 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004205 break;
4206 case ICmpInst::ICMP_UGT:
4207 switch (RHSCC) {
4208 default: assert(0 && "Unknown integer condition code!");
4209 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4210 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4211 return ReplaceInstUsesWith(I, LHS);
4212 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4213 break;
4214 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4215 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004216 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004217 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4218 break;
4219 }
4220 break;
4221 case ICmpInst::ICMP_SGT:
4222 switch (RHSCC) {
4223 default: assert(0 && "Unknown integer condition code!");
4224 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4225 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4226 return ReplaceInstUsesWith(I, LHS);
4227 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4228 break;
4229 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4230 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004231 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004232 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4233 break;
4234 }
4235 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004236 }
4237 }
4238 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004239
4240 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004241 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004242 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004243 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004244 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4245 !isa<ICmpInst>(Op1C->getOperand(0))) {
4246 const Type *SrcTy = Op0C->getOperand(0)->getType();
4247 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4248 // Only do this if the casts both really cause code to be
4249 // generated.
4250 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4251 I.getType(), TD) &&
4252 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4253 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004254 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004255 Op1C->getOperand(0),
4256 I.getName());
4257 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004258 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004259 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004260 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004261 }
Chris Lattner99c65742007-10-24 05:38:08 +00004262 }
4263
4264
4265 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4266 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4267 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4268 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004269 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4270 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004271 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4272 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4273 // If either of the constants are nans, then the whole thing returns
4274 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004275 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004276 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4277
4278 // Otherwise, no need to compare the two constants, compare the
4279 // rest.
4280 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4281 RHS->getOperand(0));
4282 }
4283 }
4284 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004285
Chris Lattner7e708292002-06-25 16:13:24 +00004286 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004287}
4288
Dan Gohman844731a2008-05-13 00:00:25 +00004289namespace {
4290
Chris Lattnerc317d392004-02-16 01:20:27 +00004291// XorSelf - Implements: X ^ X --> 0
4292struct XorSelf {
4293 Value *RHS;
4294 XorSelf(Value *rhs) : RHS(rhs) {}
4295 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4296 Instruction *apply(BinaryOperator &Xor) const {
4297 return &Xor;
4298 }
4299};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004300
Dan Gohman844731a2008-05-13 00:00:25 +00004301}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004302
Chris Lattner7e708292002-06-25 16:13:24 +00004303Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004304 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004306
Evan Chengd34af782008-03-25 20:07:13 +00004307 if (isa<UndefValue>(Op1)) {
4308 if (isa<UndefValue>(Op0))
4309 // Handle undef ^ undef -> 0 special case. This is a common
4310 // idiom (misuse).
4311 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004312 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004313 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004314
Chris Lattnerc317d392004-02-16 01:20:27 +00004315 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4316 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004317 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004318 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004319 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004320
4321 // See if we can simplify any instructions used by the instruction whose sole
4322 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004323 if (!isa<VectorType>(I.getType())) {
4324 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4325 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4326 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4327 KnownZero, KnownOne))
4328 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004329 } else if (isa<ConstantAggregateZero>(Op1)) {
4330 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004331 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004332
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004333 // Is this a ~ operation?
4334 if (Value *NotOp = dyn_castNotVal(&I)) {
4335 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4336 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4337 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4338 if (Op0I->getOpcode() == Instruction::And ||
4339 Op0I->getOpcode() == Instruction::Or) {
4340 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4341 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4342 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004343 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004344 Op0I->getOperand(1)->getName()+".not");
4345 InsertNewInstBefore(NotY, I);
4346 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004347 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004348 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004349 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004350 }
4351 }
4352 }
4353 }
4354
4355
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004356 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004357 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4358 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4359 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004360 return new ICmpInst(ICI->getInversePredicate(),
4361 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004362
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004363 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4364 return new FCmpInst(FCI->getInversePredicate(),
4365 FCI->getOperand(0), FCI->getOperand(1));
4366 }
4367
Nick Lewycky517e1f52008-05-31 19:01:33 +00004368 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4369 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4370 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4371 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4372 Instruction::CastOps Opcode = Op0C->getOpcode();
4373 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4374 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4375 Op0C->getDestTy())) {
4376 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4377 CI->getOpcode(), CI->getInversePredicate(),
4378 CI->getOperand(0), CI->getOperand(1)), I);
4379 NewCI->takeName(CI);
4380 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4381 }
4382 }
4383 }
4384 }
4385 }
4386
Reid Spencere4d87aa2006-12-23 06:05:41 +00004387 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004388 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004389 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4390 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004391 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4392 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004393 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004394 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004395 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004396
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004397 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004398 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004399 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004400 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004401 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004402 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004403 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004404 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004405 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004406 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004407 // (X + C) ^ signbit -> (X + C + signbit)
4408 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004409 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004410
Chris Lattner7c4049c2004-01-12 19:35:11 +00004411 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004412 } else if (Op0I->getOpcode() == Instruction::Or) {
4413 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004414 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004415 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4416 // Anything in both C1 and C2 is known to be zero, remove it from
4417 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004418 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004419 NewRHS = ConstantExpr::getAnd(NewRHS,
4420 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004421 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004422 I.setOperand(0, Op0I->getOperand(0));
4423 I.setOperand(1, NewRHS);
4424 return &I;
4425 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004426 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004427 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004428 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004429
4430 // Try to fold constant and into select arguments.
4431 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004432 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004433 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004434 if (isa<PHINode>(Op0))
4435 if (Instruction *NV = FoldOpIntoPhi(I))
4436 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004437 }
4438
Chris Lattner8d969642003-03-10 23:06:50 +00004439 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004440 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004441 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004442
Chris Lattner8d969642003-03-10 23:06:50 +00004443 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004444 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004445 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004446
Chris Lattner318bf792007-03-18 22:51:34 +00004447
4448 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4449 if (Op1I) {
4450 Value *A, *B;
4451 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4452 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004453 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004454 I.swapOperands();
4455 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004456 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004457 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004458 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004459 }
Chris Lattner318bf792007-03-18 22:51:34 +00004460 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4461 if (Op0 == A) // A^(A^B) == B
4462 return ReplaceInstUsesWith(I, B);
4463 else if (Op0 == B) // A^(B^A) == B
4464 return ReplaceInstUsesWith(I, A);
4465 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004466 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004467 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004468 std::swap(A, B);
4469 }
Chris Lattner318bf792007-03-18 22:51:34 +00004470 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004471 I.swapOperands(); // Simplified below.
4472 std::swap(Op0, Op1);
4473 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004474 }
Chris Lattner318bf792007-03-18 22:51:34 +00004475 }
4476
4477 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4478 if (Op0I) {
4479 Value *A, *B;
4480 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4481 if (A == Op1) // (B|A)^B == (A|B)^B
4482 std::swap(A, B);
4483 if (B == Op1) { // (A|B)^B == A & ~B
4484 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004485 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4486 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004487 }
Chris Lattner318bf792007-03-18 22:51:34 +00004488 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4489 if (Op1 == A) // (A^B)^A == B
4490 return ReplaceInstUsesWith(I, B);
4491 else if (Op1 == B) // (B^A)^A == B
4492 return ReplaceInstUsesWith(I, A);
4493 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4494 if (A == Op1) // (A&B)^A -> (B&A)^A
4495 std::swap(A, B);
4496 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004497 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004498 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004499 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4500 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004501 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004502 }
Chris Lattner318bf792007-03-18 22:51:34 +00004503 }
4504
4505 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4506 if (Op0I && Op1I && Op0I->isShift() &&
4507 Op0I->getOpcode() == Op1I->getOpcode() &&
4508 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4509 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4510 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004511 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004512 Op1I->getOperand(0),
4513 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004514 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004515 Op1I->getOperand(1));
4516 }
4517
4518 if (Op0I && Op1I) {
4519 Value *A, *B, *C, *D;
4520 // (A & B)^(A | B) -> A ^ B
4521 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4522 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4523 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004524 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004525 }
4526 // (A | B)^(A & B) -> A ^ B
4527 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4528 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4529 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004530 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004531 }
4532
4533 // (A & B)^(C & D)
4534 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4535 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4536 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4537 // (X & Y)^(X & Y) -> (Y^Z) & X
4538 Value *X = 0, *Y = 0, *Z = 0;
4539 if (A == C)
4540 X = A, Y = B, Z = D;
4541 else if (A == D)
4542 X = A, Y = B, Z = C;
4543 else if (B == C)
4544 X = B, Y = A, Z = D;
4545 else if (B == D)
4546 X = B, Y = A, Z = C;
4547
4548 if (X) {
4549 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004550 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4551 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004552 }
4553 }
4554 }
4555
Reid Spencere4d87aa2006-12-23 06:05:41 +00004556 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4557 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4558 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004559 return R;
4560
Chris Lattner6fc205f2006-05-05 06:39:07 +00004561 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004562 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004563 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004564 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4565 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004566 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004567 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004568 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4569 I.getType(), TD) &&
4570 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4571 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004572 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004573 Op1C->getOperand(0),
4574 I.getName());
4575 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004576 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004577 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004578 }
Chris Lattner99c65742007-10-24 05:38:08 +00004579 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004580
Chris Lattner7e708292002-06-25 16:13:24 +00004581 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004582}
4583
Chris Lattnera96879a2004-09-29 17:40:11 +00004584/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4585/// overflowed for this type.
4586static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004587 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004588 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004589
Reid Spencere4e40032007-03-21 23:19:50 +00004590 if (IsSigned)
4591 if (In2->getValue().isNegative())
4592 return Result->getValue().sgt(In1->getValue());
4593 else
4594 return Result->getValue().slt(In1->getValue());
4595 else
4596 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004597}
4598
Chris Lattner574da9b2005-01-13 20:14:25 +00004599/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4600/// code necessary to compute the offset from the base pointer (without adding
4601/// in the base pointer). Return the result as a signed integer of intptr size.
4602static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4603 TargetData &TD = IC.getTargetData();
4604 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004605 const Type *IntPtrTy = TD.getIntPtrType();
4606 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004607
4608 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004609 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004610 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004611
Gabor Greif177dd3f2008-06-12 21:37:33 +00004612 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4613 ++i, ++GTI) {
4614 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004615 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004616 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4617 if (OpC->isZero()) continue;
4618
4619 // Handle a struct index, which adds its field offset to the pointer.
4620 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4621 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4622
4623 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4624 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004625 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004626 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004627 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004628 ConstantInt::get(IntPtrTy, Size),
4629 GEP->getName()+".offs"), I);
4630 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004631 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004632
4633 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4634 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4635 Scale = ConstantExpr::getMul(OC, Scale);
4636 if (Constant *RC = dyn_cast<Constant>(Result))
4637 Result = ConstantExpr::getAdd(RC, Scale);
4638 else {
4639 // Emit an add instruction.
4640 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004641 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004642 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004643 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004644 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004645 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004646 // Convert to correct type.
4647 if (Op->getType() != IntPtrTy) {
4648 if (Constant *OpC = dyn_cast<Constant>(Op))
4649 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4650 else
4651 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4652 Op->getName()+".c"), I);
4653 }
4654 if (Size != 1) {
4655 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4656 if (Constant *OpC = dyn_cast<Constant>(Op))
4657 Op = ConstantExpr::getMul(OpC, Scale);
4658 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004659 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004660 GEP->getName()+".idx"), I);
4661 }
4662
4663 // Emit an add instruction.
4664 if (isa<Constant>(Op) && isa<Constant>(Result))
4665 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4666 cast<Constant>(Result));
4667 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004668 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004669 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004670 }
4671 return Result;
4672}
4673
Chris Lattner10c0d912008-04-22 02:53:33 +00004674
4675/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4676/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4677/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4678/// complex, and scales are involved. The above expression would also be legal
4679/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4680/// later form is less amenable to optimization though, and we are allowed to
4681/// generate the first by knowing that pointer arithmetic doesn't overflow.
4682///
4683/// If we can't emit an optimized form for this expression, this returns null.
4684///
4685static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4686 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004687 TargetData &TD = IC.getTargetData();
4688 gep_type_iterator GTI = gep_type_begin(GEP);
4689
4690 // Check to see if this gep only has a single variable index. If so, and if
4691 // any constant indices are a multiple of its scale, then we can compute this
4692 // in terms of the scale of the variable index. For example, if the GEP
4693 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4694 // because the expression will cross zero at the same point.
4695 unsigned i, e = GEP->getNumOperands();
4696 int64_t Offset = 0;
4697 for (i = 1; i != e; ++i, ++GTI) {
4698 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4699 // Compute the aggregate offset of constant indices.
4700 if (CI->isZero()) continue;
4701
4702 // Handle a struct index, which adds its field offset to the pointer.
4703 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4704 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4705 } else {
4706 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4707 Offset += Size*CI->getSExtValue();
4708 }
4709 } else {
4710 // Found our variable index.
4711 break;
4712 }
4713 }
4714
4715 // If there are no variable indices, we must have a constant offset, just
4716 // evaluate it the general way.
4717 if (i == e) return 0;
4718
4719 Value *VariableIdx = GEP->getOperand(i);
4720 // Determine the scale factor of the variable element. For example, this is
4721 // 4 if the variable index is into an array of i32.
4722 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4723
4724 // Verify that there are no other variable indices. If so, emit the hard way.
4725 for (++i, ++GTI; i != e; ++i, ++GTI) {
4726 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4727 if (!CI) return 0;
4728
4729 // Compute the aggregate offset of constant indices.
4730 if (CI->isZero()) continue;
4731
4732 // Handle a struct index, which adds its field offset to the pointer.
4733 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4734 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4735 } else {
4736 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4737 Offset += Size*CI->getSExtValue();
4738 }
4739 }
4740
4741 // Okay, we know we have a single variable index, which must be a
4742 // pointer/array/vector index. If there is no offset, life is simple, return
4743 // the index.
4744 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4745 if (Offset == 0) {
4746 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4747 // we don't need to bother extending: the extension won't affect where the
4748 // computation crosses zero.
4749 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4750 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4751 VariableIdx->getNameStart(), &I);
4752 return VariableIdx;
4753 }
4754
4755 // Otherwise, there is an index. The computation we will do will be modulo
4756 // the pointer size, so get it.
4757 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4758
4759 Offset &= PtrSizeMask;
4760 VariableScale &= PtrSizeMask;
4761
4762 // To do this transformation, any constant index must be a multiple of the
4763 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4764 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4765 // multiple of the variable scale.
4766 int64_t NewOffs = Offset / (int64_t)VariableScale;
4767 if (Offset != NewOffs*(int64_t)VariableScale)
4768 return 0;
4769
4770 // Okay, we can do this evaluation. Start by converting the index to intptr.
4771 const Type *IntPtrTy = TD.getIntPtrType();
4772 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004773 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004774 true /*SExt*/,
4775 VariableIdx->getNameStart(), &I);
4776 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004777 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004778}
4779
4780
Reid Spencere4d87aa2006-12-23 06:05:41 +00004781/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004782/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004783Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4784 ICmpInst::Predicate Cond,
4785 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004786 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004787
Chris Lattner10c0d912008-04-22 02:53:33 +00004788 // Look through bitcasts.
4789 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4790 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004791
Chris Lattner574da9b2005-01-13 20:14:25 +00004792 Value *PtrBase = GEPLHS->getOperand(0);
4793 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004794 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004795 // This transformation (ignoring the base and scales) is valid because we
4796 // know pointers can't overflow. See if we can output an optimized form.
4797 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4798
4799 // If not, synthesize the offset the hard way.
4800 if (Offset == 0)
4801 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004802 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4803 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004804 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004805 // If the base pointers are different, but the indices are the same, just
4806 // compare the base pointer.
4807 if (PtrBase != GEPRHS->getOperand(0)) {
4808 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004809 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004810 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004811 if (IndicesTheSame)
4812 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4813 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4814 IndicesTheSame = false;
4815 break;
4816 }
4817
4818 // If all indices are the same, just compare the base pointers.
4819 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4821 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004822
4823 // Otherwise, the base pointers are different and the indices are
4824 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004825 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004826 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004827
Chris Lattnere9d782b2005-01-13 22:25:21 +00004828 // If one of the GEPs has all zero indices, recurse.
4829 bool AllZeros = true;
4830 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4831 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4832 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4833 AllZeros = false;
4834 break;
4835 }
4836 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004837 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4838 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004839
4840 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004841 AllZeros = true;
4842 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4843 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4844 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4845 AllZeros = false;
4846 break;
4847 }
4848 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004849 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004850
Chris Lattner4401c9c2005-01-14 00:20:05 +00004851 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4852 // If the GEPs only differ by one index, compare it.
4853 unsigned NumDifferences = 0; // Keep track of # differences.
4854 unsigned DiffOperand = 0; // The operand that differs.
4855 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4856 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004857 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4858 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004859 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004860 NumDifferences = 2;
4861 break;
4862 } else {
4863 if (NumDifferences++) break;
4864 DiffOperand = i;
4865 }
4866 }
4867
4868 if (NumDifferences == 0) // SAME GEP?
4869 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004870 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004871 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004872
Chris Lattner4401c9c2005-01-14 00:20:05 +00004873 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004874 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4875 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004876 // Make sure we do a signed comparison here.
4877 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004878 }
4879 }
4880
Reid Spencere4d87aa2006-12-23 06:05:41 +00004881 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004882 // the result to fold to a constant!
4883 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4884 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4885 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4886 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4887 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004888 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004889 }
4890 }
4891 return 0;
4892}
4893
Chris Lattnera5406232008-05-19 20:18:56 +00004894/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4895///
4896Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4897 Instruction *LHSI,
4898 Constant *RHSC) {
4899 if (!isa<ConstantFP>(RHSC)) return 0;
4900 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4901
4902 // Get the width of the mantissa. We don't want to hack on conversions that
4903 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004904 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004905 if (MantissaWidth == -1) return 0; // Unknown.
4906
4907 // Check to see that the input is converted from an integer type that is small
4908 // enough that preserves all bits. TODO: check here for "known" sign bits.
4909 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4910 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4911
4912 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4913 if (isa<UIToFPInst>(LHSI))
4914 ++InputSize;
4915
4916 // If the conversion would lose info, don't hack on this.
4917 if ((int)InputSize > MantissaWidth)
4918 return 0;
4919
4920 // Otherwise, we can potentially simplify the comparison. We know that it
4921 // will always come through as an integer value and we know the constant is
4922 // not a NAN (it would have been previously simplified).
4923 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4924
4925 ICmpInst::Predicate Pred;
4926 switch (I.getPredicate()) {
4927 default: assert(0 && "Unexpected predicate!");
4928 case FCmpInst::FCMP_UEQ:
4929 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4930 case FCmpInst::FCMP_UGT:
4931 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4932 case FCmpInst::FCMP_UGE:
4933 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4934 case FCmpInst::FCMP_ULT:
4935 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4936 case FCmpInst::FCMP_ULE:
4937 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4938 case FCmpInst::FCMP_UNE:
4939 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4940 case FCmpInst::FCMP_ORD:
4941 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4942 case FCmpInst::FCMP_UNO:
4943 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4944 }
4945
4946 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4947
4948 // Now we know that the APFloat is a normal number, zero or inf.
4949
Chris Lattner85162782008-05-20 03:50:52 +00004950 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004951 // comparing an i8 to 300.0.
4952 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4953
4954 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4955 // and large values.
4956 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4957 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4958 APFloat::rmNearestTiesToEven);
4959 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004960 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4961 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004962 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4963 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4964 }
4965
4966 // See if the RHS value is < SignedMin.
4967 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4968 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4969 APFloat::rmNearestTiesToEven);
4970 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004971 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4972 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00004973 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4974 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4975 }
4976
4977 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4978 // it may still be fractional. See if it is fractional by casting the FP
4979 // value to the integer value and back, checking for equality. Don't do this
4980 // for zero, because -0.0 is not fractional.
4981 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4982 if (!RHS.isZero() &&
4983 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4984 // If we had a comparison against a fractional value, we have to adjust
4985 // the compare predicate and sometimes the value. RHSC is rounded towards
4986 // zero at this point.
4987 switch (Pred) {
4988 default: assert(0 && "Unexpected integer comparison!");
4989 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4990 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4991 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4992 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4993 case ICmpInst::ICMP_SLE:
4994 // (float)int <= 4.4 --> int <= 4
4995 // (float)int <= -4.4 --> int < -4
4996 if (RHS.isNegative())
4997 Pred = ICmpInst::ICMP_SLT;
4998 break;
4999 case ICmpInst::ICMP_SLT:
5000 // (float)int < -4.4 --> int < -4
5001 // (float)int < 4.4 --> int <= 4
5002 if (!RHS.isNegative())
5003 Pred = ICmpInst::ICMP_SLE;
5004 break;
5005 case ICmpInst::ICMP_SGT:
5006 // (float)int > 4.4 --> int > 4
5007 // (float)int > -4.4 --> int >= -4
5008 if (RHS.isNegative())
5009 Pred = ICmpInst::ICMP_SGE;
5010 break;
5011 case ICmpInst::ICMP_SGE:
5012 // (float)int >= -4.4 --> int >= -4
5013 // (float)int >= 4.4 --> int > 4
5014 if (!RHS.isNegative())
5015 Pred = ICmpInst::ICMP_SGT;
5016 break;
5017 }
5018 }
5019
5020 // Lower this FP comparison into an appropriate integer version of the
5021 // comparison.
5022 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5023}
5024
Reid Spencere4d87aa2006-12-23 06:05:41 +00005025Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5026 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005027 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005028
Chris Lattner58e97462007-01-14 19:42:17 +00005029 // Fold trivial predicates.
5030 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5031 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5032 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5033 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5034
5035 // Simplify 'fcmp pred X, X'
5036 if (Op0 == Op1) {
5037 switch (I.getPredicate()) {
5038 default: assert(0 && "Unknown predicate!");
5039 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5040 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5041 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5042 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5043 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5044 case FCmpInst::FCMP_OLT: // True if ordered and less than
5045 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5046 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5047
5048 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5049 case FCmpInst::FCMP_ULT: // True if unordered or less than
5050 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5051 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5052 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5053 I.setPredicate(FCmpInst::FCMP_UNO);
5054 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5055 return &I;
5056
5057 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5058 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5059 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5060 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5061 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5062 I.setPredicate(FCmpInst::FCMP_ORD);
5063 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5064 return &I;
5065 }
5066 }
5067
Reid Spencere4d87aa2006-12-23 06:05:41 +00005068 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005069 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005070
Reid Spencere4d87aa2006-12-23 06:05:41 +00005071 // Handle fcmp with constant RHS
5072 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005073 // If the constant is a nan, see if we can fold the comparison based on it.
5074 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5075 if (CFP->getValueAPF().isNaN()) {
5076 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5077 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005078 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5079 "Comparison must be either ordered or unordered!");
5080 // True if unordered.
5081 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005082 }
5083 }
5084
Reid Spencere4d87aa2006-12-23 06:05:41 +00005085 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5086 switch (LHSI->getOpcode()) {
5087 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005088 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5089 // block. If in the same block, we're encouraging jump threading. If
5090 // not, we are just pessimizing the code by making an i1 phi.
5091 if (LHSI->getParent() == I.getParent())
5092 if (Instruction *NV = FoldOpIntoPhi(I))
5093 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005094 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005095 case Instruction::SIToFP:
5096 case Instruction::UIToFP:
5097 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5098 return NV;
5099 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005100 case Instruction::Select:
5101 // If either operand of the select is a constant, we can fold the
5102 // comparison into the select arms, which will cause one to be
5103 // constant folded and the select turned into a bitwise or.
5104 Value *Op1 = 0, *Op2 = 0;
5105 if (LHSI->hasOneUse()) {
5106 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5107 // Fold the known value into the constant operand.
5108 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5109 // Insert a new FCmp of the other select operand.
5110 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5111 LHSI->getOperand(2), RHSC,
5112 I.getName()), I);
5113 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5114 // Fold the known value into the constant operand.
5115 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5116 // Insert a new FCmp of the other select operand.
5117 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5118 LHSI->getOperand(1), RHSC,
5119 I.getName()), I);
5120 }
5121 }
5122
5123 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005124 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005125 break;
5126 }
5127 }
5128
5129 return Changed ? &I : 0;
5130}
5131
5132Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5133 bool Changed = SimplifyCompare(I);
5134 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5135 const Type *Ty = Op0->getType();
5136
5137 // icmp X, X
5138 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005139 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005140 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005141
5142 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005143 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005144
Reid Spencere4d87aa2006-12-23 06:05:41 +00005145 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005146 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005147 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5148 isa<ConstantPointerNull>(Op0)) &&
5149 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005150 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005151 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005152 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005153
Reid Spencere4d87aa2006-12-23 06:05:41 +00005154 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005155 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005156 switch (I.getPredicate()) {
5157 default: assert(0 && "Invalid icmp instruction!");
5158 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005159 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005160 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005161 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005162 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005163 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005164 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005165
Reid Spencere4d87aa2006-12-23 06:05:41 +00005166 case ICmpInst::ICMP_UGT:
5167 case ICmpInst::ICMP_SGT:
5168 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005169 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005170 case ICmpInst::ICMP_ULT:
5171 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005172 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005173 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005174 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005175 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 case ICmpInst::ICMP_UGE:
5177 case ICmpInst::ICMP_SGE:
5178 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005179 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005180 case ICmpInst::ICMP_ULE:
5181 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005182 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005183 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005184 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005185 }
5186 }
Chris Lattner8b170942002-08-09 23:47:40 +00005187 }
5188
Chris Lattner2be51ae2004-06-09 04:24:29 +00005189 // See if we are doing a comparison between a constant and an instruction that
5190 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005191 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005192 Value *A, *B;
5193
Chris Lattnerb6566012008-01-05 01:18:20 +00005194 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5195 if (I.isEquality() && CI->isNullValue() &&
5196 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5197 // (icmp cond A B) if cond is equality
5198 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005199 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005200
Reid Spencere4d87aa2006-12-23 06:05:41 +00005201 switch (I.getPredicate()) {
5202 default: break;
5203 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5204 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005205 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005206 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5207 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5208 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5209 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005210 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5211 if (CI->isMinValue(true))
5212 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5213 ConstantInt::getAllOnesValue(Op0->getType()));
5214
Reid Spencere4d87aa2006-12-23 06:05:41 +00005215 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005216
Reid Spencere4d87aa2006-12-23 06:05:41 +00005217 case ICmpInst::ICMP_SLT:
5218 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005219 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5221 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5222 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5223 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5224 break;
5225
5226 case ICmpInst::ICMP_UGT:
5227 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005228 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005229 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5230 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5231 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5232 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005233
5234 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5235 if (CI->isMaxValue(true))
5236 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5237 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005238 break;
5239
5240 case ICmpInst::ICMP_SGT:
5241 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005242 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005243 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5244 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5245 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5246 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5247 break;
5248
5249 case ICmpInst::ICMP_ULE:
5250 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005251 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005252 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5253 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5254 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5255 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5256 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005257
Reid Spencere4d87aa2006-12-23 06:05:41 +00005258 case ICmpInst::ICMP_SLE:
5259 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005260 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005261 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5262 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5263 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5264 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5265 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005266
Reid Spencere4d87aa2006-12-23 06:05:41 +00005267 case ICmpInst::ICMP_UGE:
5268 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005269 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005270 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5271 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5272 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5273 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5274 break;
5275
5276 case ICmpInst::ICMP_SGE:
5277 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005278 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005279 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5280 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5281 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5282 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5283 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005284 }
5285
Reid Spencere4d87aa2006-12-23 06:05:41 +00005286 // If we still have a icmp le or icmp ge instruction, turn it into the
5287 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005288 // already been handled above, this requires little checking.
5289 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005290 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005291 default: break;
5292 case ICmpInst::ICMP_ULE:
5293 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5294 case ICmpInst::ICMP_SLE:
5295 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5296 case ICmpInst::ICMP_UGE:
5297 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5298 case ICmpInst::ICMP_SGE:
5299 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005300 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005301
5302 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005303 // in the input. If this comparison is a normal comparison, it demands all
5304 // bits, if it is a sign bit comparison, it only demands the sign bit.
5305
5306 bool UnusedBit;
5307 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5308
Reid Spencer0460fb32007-03-22 20:36:03 +00005309 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5310 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005311 if (SimplifyDemandedBits(Op0,
5312 isSignBit ? APInt::getSignBit(BitWidth)
5313 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005314 KnownZero, KnownOne, 0))
5315 return &I;
5316
5317 // Given the known and unknown bits, compute a range that the LHS could be
5318 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005319 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005320 // Compute the Min, Max and RHS values based on the known bits. For the
5321 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005322 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5323 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005324 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005325 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5326 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005327 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005328 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5329 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005330 }
5331 switch (I.getPredicate()) { // LE/GE have been folded already.
5332 default: assert(0 && "Unknown icmp opcode!");
5333 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005334 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005335 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005336 break;
5337 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005338 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005339 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005340 break;
5341 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005342 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005343 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005344 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005345 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005346 break;
5347 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005348 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005349 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005350 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005351 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005352 break;
5353 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005354 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005355 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005356 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005357 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005358 break;
5359 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005360 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005361 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005362 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005363 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005364 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005365 }
5366 }
5367
Reid Spencere4d87aa2006-12-23 06:05:41 +00005368 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005369 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005370 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005371 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005372 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5373 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005374 }
5375
Chris Lattner01deb9d2007-04-03 17:43:25 +00005376 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005377 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5378 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5379 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005380 case Instruction::GetElementPtr:
5381 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005382 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005383 bool isAllZeros = true;
5384 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5385 if (!isa<Constant>(LHSI->getOperand(i)) ||
5386 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5387 isAllZeros = false;
5388 break;
5389 }
5390 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005391 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005392 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5393 }
5394 break;
5395
Chris Lattner6970b662005-04-23 15:31:55 +00005396 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005397 // Only fold icmp into the PHI if the phi and fcmp are in the same
5398 // block. If in the same block, we're encouraging jump threading. If
5399 // not, we are just pessimizing the code by making an i1 phi.
5400 if (LHSI->getParent() == I.getParent())
5401 if (Instruction *NV = FoldOpIntoPhi(I))
5402 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005403 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005404 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005405 // If either operand of the select is a constant, we can fold the
5406 // comparison into the select arms, which will cause one to be
5407 // constant folded and the select turned into a bitwise or.
5408 Value *Op1 = 0, *Op2 = 0;
5409 if (LHSI->hasOneUse()) {
5410 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5411 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005412 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5413 // Insert a new ICmp of the other select operand.
5414 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5415 LHSI->getOperand(2), RHSC,
5416 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005417 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5418 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005419 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5420 // Insert a new ICmp of the other select operand.
5421 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5422 LHSI->getOperand(1), RHSC,
5423 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005424 }
5425 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005426
Chris Lattner6970b662005-04-23 15:31:55 +00005427 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005428 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005429 break;
5430 }
Chris Lattner4802d902007-04-06 18:57:34 +00005431 case Instruction::Malloc:
5432 // If we have (malloc != null), and if the malloc has a single use, we
5433 // can assume it is successful and remove the malloc.
5434 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5435 AddToWorkList(LHSI);
5436 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005437 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005438 }
5439 break;
5440 }
Chris Lattner6970b662005-04-23 15:31:55 +00005441 }
5442
Reid Spencere4d87aa2006-12-23 06:05:41 +00005443 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005444 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005445 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005446 return NI;
5447 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005448 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5449 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005450 return NI;
5451
Reid Spencere4d87aa2006-12-23 06:05:41 +00005452 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005453 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5454 // now.
5455 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5456 if (isa<PointerType>(Op0->getType()) &&
5457 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005458 // We keep moving the cast from the left operand over to the right
5459 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005460 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005461
Chris Lattner57d86372007-01-06 01:45:59 +00005462 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5463 // so eliminate it as well.
5464 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5465 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005466
Chris Lattnerde90b762003-11-03 04:25:02 +00005467 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005468 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005469 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005470 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005471 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005472 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005473 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005474 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005475 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005476 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005477 }
Chris Lattner57d86372007-01-06 01:45:59 +00005478 }
5479
5480 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005481 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005482 // This comes up when you have code like
5483 // int X = A < B;
5484 // if (X) ...
5485 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005486 // with a constant or another cast from the same type.
5487 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005488 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005489 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005490 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005491
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005492 // ~x < ~y --> y < x
5493 { Value *A, *B;
5494 if (match(Op0, m_Not(m_Value(A))) &&
5495 match(Op1, m_Not(m_Value(B))))
5496 return new ICmpInst(I.getPredicate(), B, A);
5497 }
5498
Chris Lattner65b72ba2006-09-18 04:22:48 +00005499 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005500 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005501
5502 // -x == -y --> x == y
5503 if (match(Op0, m_Neg(m_Value(A))) &&
5504 match(Op1, m_Neg(m_Value(B))))
5505 return new ICmpInst(I.getPredicate(), A, B);
5506
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005507 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5508 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5509 Value *OtherVal = A == Op1 ? B : A;
5510 return new ICmpInst(I.getPredicate(), OtherVal,
5511 Constant::getNullValue(A->getType()));
5512 }
5513
5514 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5515 // A^c1 == C^c2 --> A == C^(c1^c2)
5516 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5517 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5518 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005519 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005520 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005521 return new ICmpInst(I.getPredicate(), A,
5522 InsertNewInstBefore(Xor, I));
5523 }
5524
5525 // A^B == A^D -> B == D
5526 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5527 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5528 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5529 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5530 }
5531 }
5532
5533 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5534 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005535 // A == (A^B) -> B == 0
5536 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005537 return new ICmpInst(I.getPredicate(), OtherVal,
5538 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005539 }
5540 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005541 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005542 return new ICmpInst(I.getPredicate(), B,
5543 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005544 }
5545 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005546 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005547 return new ICmpInst(I.getPredicate(), B,
5548 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005549 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005550
Chris Lattner9c2328e2006-11-14 06:06:06 +00005551 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5552 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5553 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5554 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5555 Value *X = 0, *Y = 0, *Z = 0;
5556
5557 if (A == C) {
5558 X = B; Y = D; Z = A;
5559 } else if (A == D) {
5560 X = B; Y = C; Z = A;
5561 } else if (B == C) {
5562 X = A; Y = D; Z = B;
5563 } else if (B == D) {
5564 X = A; Y = C; Z = B;
5565 }
5566
5567 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005568 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5569 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005570 I.setOperand(0, Op1);
5571 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5572 return &I;
5573 }
5574 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005575 }
Chris Lattner7e708292002-06-25 16:13:24 +00005576 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005577}
5578
Chris Lattner562ef782007-06-20 23:46:26 +00005579
5580/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5581/// and CmpRHS are both known to be integer constants.
5582Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5583 ConstantInt *DivRHS) {
5584 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5585 const APInt &CmpRHSV = CmpRHS->getValue();
5586
5587 // FIXME: If the operand types don't match the type of the divide
5588 // then don't attempt this transform. The code below doesn't have the
5589 // logic to deal with a signed divide and an unsigned compare (and
5590 // vice versa). This is because (x /s C1) <s C2 produces different
5591 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5592 // (x /u C1) <u C2. Simply casting the operands and result won't
5593 // work. :( The if statement below tests that condition and bails
5594 // if it finds it.
5595 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5596 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5597 return 0;
5598 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005599 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005600
5601 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5602 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5603 // C2 (CI). By solving for X we can turn this into a range check
5604 // instead of computing a divide.
5605 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5606
5607 // Determine if the product overflows by seeing if the product is
5608 // not equal to the divide. Make sure we do the same kind of divide
5609 // as in the LHS instruction that we're folding.
5610 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5611 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5612
5613 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005614 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005615
Chris Lattner1dbfd482007-06-21 18:11:19 +00005616 // Figure out the interval that is being checked. For example, a comparison
5617 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5618 // Compute this interval based on the constants involved and the signedness of
5619 // the compare/divide. This computes a half-open interval, keeping track of
5620 // whether either value in the interval overflows. After analysis each
5621 // overflow variable is set to 0 if it's corresponding bound variable is valid
5622 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5623 int LoOverflow = 0, HiOverflow = 0;
5624 ConstantInt *LoBound = 0, *HiBound = 0;
5625
5626
Chris Lattner562ef782007-06-20 23:46:26 +00005627 if (!DivIsSigned) { // udiv
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 HiOverflow = LoOverflow = ProdOV;
5631 if (!HiOverflow)
5632 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005633 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005634 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005635 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005636 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5637 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005638 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005639 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5640 HiOverflow = LoOverflow = ProdOV;
5641 if (!HiOverflow)
5642 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005643 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005644 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005645 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5646 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005647 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005648 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005649 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005650 }
Dan Gohman76491272008-02-13 22:09:18 +00005651 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005652 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005653 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005654 LoBound = AddOne(DivRHS);
5655 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005656 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5657 HiOverflow = 1; // [INTMIN+1, overflow)
5658 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5659 }
Dan Gohman76491272008-02-13 22:09:18 +00005660 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005661 // e.g. X/-5 op 3 --> [-19, -14)
5662 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005663 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005664 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005665 HiBound = AddOne(Prod);
5666 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005667 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005668 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005669 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005670 HiBound = Subtract(Prod, DivRHS);
5671 }
5672
Chris Lattner1dbfd482007-06-21 18:11:19 +00005673 // Dividing by a negative swaps the condition. LT <-> GT
5674 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005675 }
5676
5677 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005678 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005679 default: assert(0 && "Unhandled icmp opcode!");
5680 case ICmpInst::ICMP_EQ:
5681 if (LoOverflow && HiOverflow)
5682 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5683 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005684 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005685 ICmpInst::ICMP_UGE, X, LoBound);
5686 else if (LoOverflow)
5687 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5688 ICmpInst::ICMP_ULT, X, HiBound);
5689 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005690 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005691 case ICmpInst::ICMP_NE:
5692 if (LoOverflow && HiOverflow)
5693 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5694 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005695 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005696 ICmpInst::ICMP_ULT, X, LoBound);
5697 else if (LoOverflow)
5698 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5699 ICmpInst::ICMP_UGE, X, HiBound);
5700 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005701 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005702 case ICmpInst::ICMP_ULT:
5703 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005704 if (LoOverflow == +1) // Low bound is greater than input range.
5705 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5706 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005707 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005708 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005709 case ICmpInst::ICMP_UGT:
5710 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005711 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005712 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005713 else if (HiOverflow == -1) // High bound less than input range.
5714 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5715 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005716 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5717 else
5718 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5719 }
5720}
5721
5722
Chris Lattner01deb9d2007-04-03 17:43:25 +00005723/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5724///
5725Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5726 Instruction *LHSI,
5727 ConstantInt *RHS) {
5728 const APInt &RHSV = RHS->getValue();
5729
5730 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005731 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005732 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5733 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5734 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005735 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5736 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005737 Value *CompareVal = LHSI->getOperand(0);
5738
5739 // If the sign bit of the XorCST is not set, there is no change to
5740 // the operation, just stop using the Xor.
5741 if (!XorCST->getValue().isNegative()) {
5742 ICI.setOperand(0, CompareVal);
5743 AddToWorkList(LHSI);
5744 return &ICI;
5745 }
5746
5747 // Was the old condition true if the operand is positive?
5748 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5749
5750 // If so, the new one isn't.
5751 isTrueIfPositive ^= true;
5752
5753 if (isTrueIfPositive)
5754 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5755 else
5756 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5757 }
5758 }
5759 break;
5760 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5761 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5762 LHSI->getOperand(0)->hasOneUse()) {
5763 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5764
5765 // If the LHS is an AND of a truncating cast, we can widen the
5766 // and/compare to be the input width without changing the value
5767 // produced, eliminating a cast.
5768 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5769 // We can do this transformation if either the AND constant does not
5770 // have its sign bit set or if it is an equality comparison.
5771 // Extending a relational comparison when we're checking the sign
5772 // bit would not work.
5773 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005774 (ICI.isEquality() ||
5775 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005776 uint32_t BitWidth =
5777 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5778 APInt NewCST = AndCST->getValue();
5779 NewCST.zext(BitWidth);
5780 APInt NewCI = RHSV;
5781 NewCI.zext(BitWidth);
5782 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005783 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005784 ConstantInt::get(NewCST),LHSI->getName());
5785 InsertNewInstBefore(NewAnd, ICI);
5786 return new ICmpInst(ICI.getPredicate(), NewAnd,
5787 ConstantInt::get(NewCI));
5788 }
5789 }
5790
5791 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5792 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5793 // happens a LOT in code produced by the C front-end, for bitfield
5794 // access.
5795 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5796 if (Shift && !Shift->isShift())
5797 Shift = 0;
5798
5799 ConstantInt *ShAmt;
5800 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5801 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5802 const Type *AndTy = AndCST->getType(); // Type of the and.
5803
5804 // We can fold this as long as we can't shift unknown bits
5805 // into the mask. This can only happen with signed shift
5806 // rights, as they sign-extend.
5807 if (ShAmt) {
5808 bool CanFold = Shift->isLogicalShift();
5809 if (!CanFold) {
5810 // To test for the bad case of the signed shr, see if any
5811 // of the bits shifted in could be tested after the mask.
5812 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5813 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5814
5815 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5816 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5817 AndCST->getValue()) == 0)
5818 CanFold = true;
5819 }
5820
5821 if (CanFold) {
5822 Constant *NewCst;
5823 if (Shift->getOpcode() == Instruction::Shl)
5824 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5825 else
5826 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5827
5828 // Check to see if we are shifting out any of the bits being
5829 // compared.
5830 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5831 // If we shifted bits out, the fold is not going to work out.
5832 // As a special case, check to see if this means that the
5833 // result is always true or false now.
5834 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5835 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5836 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5837 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5838 } else {
5839 ICI.setOperand(1, NewCst);
5840 Constant *NewAndCST;
5841 if (Shift->getOpcode() == Instruction::Shl)
5842 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5843 else
5844 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5845 LHSI->setOperand(1, NewAndCST);
5846 LHSI->setOperand(0, Shift->getOperand(0));
5847 AddToWorkList(Shift); // Shift is dead.
5848 AddUsesToWorkList(ICI);
5849 return &ICI;
5850 }
5851 }
5852 }
5853
5854 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5855 // preferable because it allows the C<<Y expression to be hoisted out
5856 // of a loop if Y is invariant and X is not.
5857 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5858 ICI.isEquality() && !Shift->isArithmeticShift() &&
5859 isa<Instruction>(Shift->getOperand(0))) {
5860 // Compute C << Y.
5861 Value *NS;
5862 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005863 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005864 Shift->getOperand(1), "tmp");
5865 } else {
5866 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005867 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005868 Shift->getOperand(1), "tmp");
5869 }
5870 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5871
5872 // Compute X & (C << Y).
5873 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005874 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005875 InsertNewInstBefore(NewAnd, ICI);
5876
5877 ICI.setOperand(0, NewAnd);
5878 return &ICI;
5879 }
5880 }
5881 break;
5882
Chris Lattnera0141b92007-07-15 20:42:37 +00005883 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5884 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5885 if (!ShAmt) break;
5886
5887 uint32_t TypeBits = RHSV.getBitWidth();
5888
5889 // Check that the shift amount is in range. If not, don't perform
5890 // undefined shifts. When the shift is visited it will be
5891 // simplified.
5892 if (ShAmt->uge(TypeBits))
5893 break;
5894
5895 if (ICI.isEquality()) {
5896 // If we are comparing against bits always shifted out, the
5897 // comparison cannot succeed.
5898 Constant *Comp =
5899 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5900 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5901 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5902 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5903 return ReplaceInstUsesWith(ICI, Cst);
5904 }
5905
5906 if (LHSI->hasOneUse()) {
5907 // Otherwise strength reduce the shift into an and.
5908 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5909 Constant *Mask =
5910 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005911
Chris Lattnera0141b92007-07-15 20:42:37 +00005912 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005913 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005914 Mask, LHSI->getName()+".mask");
5915 Value *And = InsertNewInstBefore(AndI, ICI);
5916 return new ICmpInst(ICI.getPredicate(), And,
5917 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005918 }
5919 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005920
5921 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5922 bool TrueIfSigned = false;
5923 if (LHSI->hasOneUse() &&
5924 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5925 // (X << 31) <s 0 --> (X&1) != 0
5926 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5927 (TypeBits-ShAmt->getZExtValue()-1));
5928 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005929 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005930 Mask, LHSI->getName()+".mask");
5931 Value *And = InsertNewInstBefore(AndI, ICI);
5932
5933 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5934 And, Constant::getNullValue(And->getType()));
5935 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005936 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005937 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005938
5939 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005940 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005941 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005942 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005943 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005944
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005945 // Check that the shift amount is in range. If not, don't perform
5946 // undefined shifts. When the shift is visited it will be
5947 // simplified.
5948 uint32_t TypeBits = RHSV.getBitWidth();
5949 if (ShAmt->uge(TypeBits))
5950 break;
5951
5952 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005953
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005954 // If we are comparing against bits always shifted out, the
5955 // comparison cannot succeed.
5956 APInt Comp = RHSV << ShAmtVal;
5957 if (LHSI->getOpcode() == Instruction::LShr)
5958 Comp = Comp.lshr(ShAmtVal);
5959 else
5960 Comp = Comp.ashr(ShAmtVal);
5961
5962 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5963 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5964 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5965 return ReplaceInstUsesWith(ICI, Cst);
5966 }
5967
5968 // Otherwise, check to see if the bits shifted out are known to be zero.
5969 // If so, we can compare against the unshifted value:
5970 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00005971 if (LHSI->hasOneUse() &&
5972 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005973 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5974 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5975 ConstantExpr::getShl(RHS, ShAmt));
5976 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005977
Evan Chengf30752c2008-04-23 00:38:06 +00005978 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005979 // Otherwise strength reduce the shift into an and.
5980 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5981 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005982
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005983 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005984 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005985 Mask, LHSI->getName()+".mask");
5986 Value *And = InsertNewInstBefore(AndI, ICI);
5987 return new ICmpInst(ICI.getPredicate(), And,
5988 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005989 }
5990 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005991 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005992
5993 case Instruction::SDiv:
5994 case Instruction::UDiv:
5995 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5996 // Fold this div into the comparison, producing a range check.
5997 // Determine, based on the divide type, what the range is being
5998 // checked. If there is an overflow on the low or high side, remember
5999 // it, otherwise compute the range [low, hi) bounding the new value.
6000 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006001 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6002 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6003 DivRHS))
6004 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006005 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006006
6007 case Instruction::Add:
6008 // Fold: icmp pred (add, X, C1), C2
6009
6010 if (!ICI.isEquality()) {
6011 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6012 if (!LHSC) break;
6013 const APInt &LHSV = LHSC->getValue();
6014
6015 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6016 .subtract(LHSV);
6017
6018 if (ICI.isSignedPredicate()) {
6019 if (CR.getLower().isSignBit()) {
6020 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6021 ConstantInt::get(CR.getUpper()));
6022 } else if (CR.getUpper().isSignBit()) {
6023 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6024 ConstantInt::get(CR.getLower()));
6025 }
6026 } else {
6027 if (CR.getLower().isMinValue()) {
6028 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6029 ConstantInt::get(CR.getUpper()));
6030 } else if (CR.getUpper().isMinValue()) {
6031 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6032 ConstantInt::get(CR.getLower()));
6033 }
6034 }
6035 }
6036 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006037 }
6038
6039 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6040 if (ICI.isEquality()) {
6041 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6042
6043 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6044 // the second operand is a constant, simplify a bit.
6045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6046 switch (BO->getOpcode()) {
6047 case Instruction::SRem:
6048 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6049 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6050 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6051 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6052 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006053 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006054 BO->getName());
6055 InsertNewInstBefore(NewRem, ICI);
6056 return new ICmpInst(ICI.getPredicate(), NewRem,
6057 Constant::getNullValue(BO->getType()));
6058 }
6059 }
6060 break;
6061 case Instruction::Add:
6062 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6063 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6064 if (BO->hasOneUse())
6065 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6066 Subtract(RHS, BOp1C));
6067 } else if (RHSV == 0) {
6068 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6069 // efficiently invertible, or if the add has just this one use.
6070 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6071
6072 if (Value *NegVal = dyn_castNegVal(BOp1))
6073 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6074 else if (Value *NegVal = dyn_castNegVal(BOp0))
6075 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6076 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006077 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006078 InsertNewInstBefore(Neg, ICI);
6079 Neg->takeName(BO);
6080 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6081 }
6082 }
6083 break;
6084 case Instruction::Xor:
6085 // For the xor case, we can xor two constants together, eliminating
6086 // the explicit xor.
6087 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6088 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6089 ConstantExpr::getXor(RHS, BOC));
6090
6091 // FALLTHROUGH
6092 case Instruction::Sub:
6093 // Replace (([sub|xor] A, B) != 0) with (A != B)
6094 if (RHSV == 0)
6095 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6096 BO->getOperand(1));
6097 break;
6098
6099 case Instruction::Or:
6100 // If bits are being or'd in that are not present in the constant we
6101 // are comparing against, then the comparison could never succeed!
6102 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6103 Constant *NotCI = ConstantExpr::getNot(RHS);
6104 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6105 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6106 isICMP_NE));
6107 }
6108 break;
6109
6110 case Instruction::And:
6111 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6112 // If bits are being compared against that are and'd out, then the
6113 // comparison can never succeed!
6114 if ((RHSV & ~BOC->getValue()) != 0)
6115 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6116 isICMP_NE));
6117
6118 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6119 if (RHS == BOC && RHSV.isPowerOf2())
6120 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6121 ICmpInst::ICMP_NE, LHSI,
6122 Constant::getNullValue(RHS->getType()));
6123
6124 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006125 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006126 Value *X = BO->getOperand(0);
6127 Constant *Zero = Constant::getNullValue(X->getType());
6128 ICmpInst::Predicate pred = isICMP_NE ?
6129 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6130 return new ICmpInst(pred, X, Zero);
6131 }
6132
6133 // ((X & ~7) == 0) --> X < 8
6134 if (RHSV == 0 && isHighOnes(BOC)) {
6135 Value *X = BO->getOperand(0);
6136 Constant *NegX = ConstantExpr::getNeg(BOC);
6137 ICmpInst::Predicate pred = isICMP_NE ?
6138 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6139 return new ICmpInst(pred, X, NegX);
6140 }
6141 }
6142 default: break;
6143 }
6144 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6145 // Handle icmp {eq|ne} <intrinsic>, intcst.
6146 if (II->getIntrinsicID() == Intrinsic::bswap) {
6147 AddToWorkList(II);
6148 ICI.setOperand(0, II->getOperand(1));
6149 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6150 return &ICI;
6151 }
6152 }
6153 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006154 // If the LHS is a cast from an integral value of the same size,
6155 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006156 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6157 Value *CastOp = Cast->getOperand(0);
6158 const Type *SrcTy = CastOp->getType();
6159 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6160 if (SrcTy->isInteger() &&
6161 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6162 // If this is an unsigned comparison, try to make the comparison use
6163 // smaller constant values.
6164 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6165 // X u< 128 => X s> -1
6166 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6167 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6168 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6169 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6170 // X u> 127 => X s< 0
6171 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6172 Constant::getNullValue(SrcTy));
6173 }
6174 }
6175 }
6176 }
6177 return 0;
6178}
6179
6180/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6181/// We only handle extending casts so far.
6182///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006183Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6184 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006185 Value *LHSCIOp = LHSCI->getOperand(0);
6186 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006187 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006188 Value *RHSCIOp;
6189
Chris Lattner8c756c12007-05-05 22:41:33 +00006190 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6191 // integer type is the same size as the pointer type.
6192 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6193 getTargetData().getPointerSizeInBits() ==
6194 cast<IntegerType>(DestTy)->getBitWidth()) {
6195 Value *RHSOp = 0;
6196 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006197 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006198 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6199 RHSOp = RHSC->getOperand(0);
6200 // If the pointer types don't match, insert a bitcast.
6201 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006202 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006203 }
6204
6205 if (RHSOp)
6206 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6207 }
6208
6209 // The code below only handles extension cast instructions, so far.
6210 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006211 if (LHSCI->getOpcode() != Instruction::ZExt &&
6212 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006213 return 0;
6214
Reid Spencere4d87aa2006-12-23 06:05:41 +00006215 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6216 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006217
Reid Spencere4d87aa2006-12-23 06:05:41 +00006218 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006219 // Not an extension from the same type?
6220 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006221 if (RHSCIOp->getType() != LHSCIOp->getType())
6222 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006223
Nick Lewycky4189a532008-01-28 03:48:02 +00006224 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006225 // and the other is a zext), then we can't handle this.
6226 if (CI->getOpcode() != LHSCI->getOpcode())
6227 return 0;
6228
Nick Lewycky4189a532008-01-28 03:48:02 +00006229 // Deal with equality cases early.
6230 if (ICI.isEquality())
6231 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6232
6233 // A signed comparison of sign extended values simplifies into a
6234 // signed comparison.
6235 if (isSignedCmp && isSignedExt)
6236 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6237
6238 // The other three cases all fold into an unsigned comparison.
6239 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006240 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006241
Reid Spencere4d87aa2006-12-23 06:05:41 +00006242 // If we aren't dealing with a constant on the RHS, exit early
6243 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6244 if (!CI)
6245 return 0;
6246
6247 // Compute the constant that would happen if we truncated to SrcTy then
6248 // reextended to DestTy.
6249 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6250 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6251
6252 // If the re-extended constant didn't change...
6253 if (Res2 == CI) {
6254 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6255 // For example, we might have:
6256 // %A = sext short %X to uint
6257 // %B = icmp ugt uint %A, 1330
6258 // It is incorrect to transform this into
6259 // %B = icmp ugt short %X, 1330
6260 // because %A may have negative value.
6261 //
6262 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6263 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006264 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006265 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6266 else
6267 return 0;
6268 }
6269
6270 // The re-extended constant changed so the constant cannot be represented
6271 // in the shorter type. Consequently, we cannot emit a simple comparison.
6272
6273 // First, handle some easy cases. We know the result cannot be equal at this
6274 // point so handle the ICI.isEquality() cases
6275 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006276 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006277 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006278 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006279
6280 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6281 // should have been folded away previously and not enter in here.
6282 Value *Result;
6283 if (isSignedCmp) {
6284 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006285 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006286 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006287 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006288 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006289 } else {
6290 // We're performing an unsigned comparison.
6291 if (isSignedExt) {
6292 // We're performing an unsigned comp with a sign extended value.
6293 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006294 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006295 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6296 NegOne, ICI.getName()), ICI);
6297 } else {
6298 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006299 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006300 }
6301 }
6302
6303 // Finally, return the value computed.
6304 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6305 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6306 return ReplaceInstUsesWith(ICI, Result);
6307 } else {
6308 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6309 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6310 "ICmp should be folded!");
6311 if (Constant *CI = dyn_cast<Constant>(Result))
6312 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6313 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006314 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006315 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006316}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006317
Reid Spencer832254e2007-02-02 02:16:23 +00006318Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6319 return commonShiftTransforms(I);
6320}
6321
6322Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6323 return commonShiftTransforms(I);
6324}
6325
6326Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006327 if (Instruction *R = commonShiftTransforms(I))
6328 return R;
6329
6330 Value *Op0 = I.getOperand(0);
6331
6332 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6333 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6334 if (CSI->isAllOnesValue())
6335 return ReplaceInstUsesWith(I, CSI);
6336
6337 // See if we can turn a signed shr into an unsigned shr.
6338 if (MaskedValueIsZero(Op0,
6339 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006340 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006341
6342 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006343}
6344
6345Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6346 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006347 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006348
6349 // shl X, 0 == X and shr X, 0 == X
6350 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006351 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006352 Op0 == Constant::getNullValue(Op0->getType()))
6353 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006354
Reid Spencere4d87aa2006-12-23 06:05:41 +00006355 if (isa<UndefValue>(Op0)) {
6356 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006357 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006358 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006359 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6360 }
6361 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006362 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6363 return ReplaceInstUsesWith(I, Op0);
6364 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006365 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006366 }
6367
Chris Lattner2eefe512004-04-09 19:05:30 +00006368 // Try to fold constant and into select arguments.
6369 if (isa<Constant>(Op0))
6370 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006371 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006372 return R;
6373
Reid Spencerb83eb642006-10-20 07:07:24 +00006374 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006375 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6376 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006377 return 0;
6378}
6379
Reid Spencerb83eb642006-10-20 07:07:24 +00006380Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006381 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006382 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006383
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006384 // See if we can simplify any instructions used by the instruction whose sole
6385 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006386 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6387 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6388 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006389 KnownZero, KnownOne))
6390 return &I;
6391
Chris Lattner4d5542c2006-01-06 07:12:35 +00006392 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6393 // of a signed value.
6394 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006395 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006396 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006397 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6398 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006399 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006400 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006401 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006402 }
6403
6404 // ((X*C1) << C2) == (X * (C1 << C2))
6405 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6406 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6407 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006408 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006409 ConstantExpr::getShl(BOOp, Op1));
6410
6411 // Try to fold constant and into select arguments.
6412 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6413 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6414 return R;
6415 if (isa<PHINode>(Op0))
6416 if (Instruction *NV = FoldOpIntoPhi(I))
6417 return NV;
6418
Chris Lattner8999dd32007-12-22 09:07:47 +00006419 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6420 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6421 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6422 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6423 // place. Don't try to do this transformation in this case. Also, we
6424 // require that the input operand is a shift-by-constant so that we have
6425 // confidence that the shifts will get folded together. We could do this
6426 // xform in more cases, but it is unlikely to be profitable.
6427 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6428 isa<ConstantInt>(TrOp->getOperand(1))) {
6429 // Okay, we'll do this xform. Make the shift of shift.
6430 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006431 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006432 I.getName());
6433 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6434
6435 // For logical shifts, the truncation has the effect of making the high
6436 // part of the register be zeros. Emulate this by inserting an AND to
6437 // clear the top bits as needed. This 'and' will usually be zapped by
6438 // other xforms later if dead.
6439 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6440 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6441 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6442
6443 // The mask we constructed says what the trunc would do if occurring
6444 // between the shifts. We want to know the effect *after* the second
6445 // shift. We know that it is a logical shift by a constant, so adjust the
6446 // mask as appropriate.
6447 if (I.getOpcode() == Instruction::Shl)
6448 MaskV <<= Op1->getZExtValue();
6449 else {
6450 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6451 MaskV = MaskV.lshr(Op1->getZExtValue());
6452 }
6453
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006454 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006455 TI->getName());
6456 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6457
6458 // Return the value truncated to the interesting size.
6459 return new TruncInst(And, I.getType());
6460 }
6461 }
6462
Chris Lattner4d5542c2006-01-06 07:12:35 +00006463 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006464 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6465 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6466 Value *V1, *V2;
6467 ConstantInt *CC;
6468 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006469 default: break;
6470 case Instruction::Add:
6471 case Instruction::And:
6472 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006473 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006474 // These operators commute.
6475 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006476 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6477 match(Op0BO->getOperand(1),
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(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006480 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006481 Op0BO->getName());
6482 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(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006485 Op0BO->getOperand(1)->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 Lattner150f12a2005-09-18 06:30:59 +00006492 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006493 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006494 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006495 match(Op0BOOp1,
6496 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006497 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6498 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006499 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006500 Op0BO->getOperand(0), 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(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006509 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006510 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006511
Reid Spencera07cb7d2007-02-02 14:41:37 +00006512 // FALL THROUGH.
6513 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006514 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006515 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6516 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006517 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006518 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006519 Op0BO->getOperand(1), Op1,
6520 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006521 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006522 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006523 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006524 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006525 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006526 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006527 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006528 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006529 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006530
Chris Lattner13d4ab42006-05-31 21:14:00 +00006531 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006532 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6533 match(Op0BO->getOperand(0),
6534 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006535 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006536 cast<BinaryOperator>(Op0BO->getOperand(0))
6537 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006538 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006539 Op0BO->getOperand(1), Op1,
6540 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006541 InsertNewInstBefore(YS, I); // (Y << C)
6542 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006543 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006544 V1->getName()+".mask");
6545 InsertNewInstBefore(XM, I); // X & (CC << C)
6546
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006547 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006548 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006549
Chris Lattner11021cb2005-09-18 05:12:10 +00006550 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006551 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006552 }
6553
6554
6555 // If the operand is an bitwise operator with a constant RHS, and the
6556 // shift is the only use, we can pull it out of the shift.
6557 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6558 bool isValid = true; // Valid only for And, Or, Xor
6559 bool highBitSet = false; // Transform if high bit of constant set?
6560
6561 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006562 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006563 case Instruction::Add:
6564 isValid = isLeftShift;
6565 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006566 case Instruction::Or:
6567 case Instruction::Xor:
6568 highBitSet = false;
6569 break;
6570 case Instruction::And:
6571 highBitSet = true;
6572 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006573 }
6574
6575 // If this is a signed shift right, and the high bit is modified
6576 // by the logical operation, do not perform the transformation.
6577 // The highBitSet boolean indicates the value of the high bit of
6578 // the constant which would cause it to be modified for this
6579 // operation.
6580 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006581 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006582 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006583
6584 if (isValid) {
6585 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6586
6587 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006588 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006589 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006590 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006591
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006592 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006593 NewRHS);
6594 }
6595 }
6596 }
6597 }
6598
Chris Lattnerad0124c2006-01-06 07:52:12 +00006599 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006600 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6601 if (ShiftOp && !ShiftOp->isShift())
6602 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006603
Reid Spencerb83eb642006-10-20 07:07:24 +00006604 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006605 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006606 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6607 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006608 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6609 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6610 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006611
Zhou Sheng4351c642007-04-02 08:20:41 +00006612 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006613 if (AmtSum > TypeBits)
6614 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006615
6616 const IntegerType *Ty = cast<IntegerType>(I.getType());
6617
6618 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006619 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006620 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006621 ConstantInt::get(Ty, AmtSum));
6622 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6623 I.getOpcode() == Instruction::AShr) {
6624 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006625 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006626 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6627 I.getOpcode() == Instruction::LShr) {
6628 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6629 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006630 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006631 InsertNewInstBefore(Shift, I);
6632
Zhou Shenge9e03f62007-03-28 15:02:20 +00006633 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006634 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006635 }
6636
Chris Lattnerb87056f2007-02-05 00:57:54 +00006637 // Okay, if we get here, one shift must be left, and the other shift must be
6638 // right. See if the amounts are equal.
6639 if (ShiftAmt1 == ShiftAmt2) {
6640 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6641 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006642 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006643 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006644 }
6645 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6646 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006647 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006648 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006649 }
6650 // We can simplify ((X << C) >>s C) into a trunc + sext.
6651 // NOTE: we could do this for any C, but that would make 'unusual' integer
6652 // types. For now, just stick to ones well-supported by the code
6653 // generators.
6654 const Type *SExtType = 0;
6655 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006656 case 1 :
6657 case 8 :
6658 case 16 :
6659 case 32 :
6660 case 64 :
6661 case 128:
6662 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6663 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006664 default: break;
6665 }
6666 if (SExtType) {
6667 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6668 InsertNewInstBefore(NewTrunc, I);
6669 return new SExtInst(NewTrunc, Ty);
6670 }
6671 // Otherwise, we can't handle it yet.
6672 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006673 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006674
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006675 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006676 if (I.getOpcode() == Instruction::Shl) {
6677 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6678 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006679 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006680 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006681 InsertNewInstBefore(Shift, I);
6682
Reid Spencer55702aa2007-03-25 21:11:44 +00006683 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006684 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006685 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006686
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006687 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006688 if (I.getOpcode() == Instruction::LShr) {
6689 assert(ShiftOp->getOpcode() == Instruction::Shl);
6690 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006691 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006692 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006693
Reid Spencerd5e30f02007-03-26 17:18:58 +00006694 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006695 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006696 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006697
6698 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6699 } else {
6700 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006701 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006702
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006703 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006704 if (I.getOpcode() == Instruction::Shl) {
6705 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6706 ShiftOp->getOpcode() == Instruction::AShr);
6707 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006708 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006709 ConstantInt::get(Ty, ShiftDiff));
6710 InsertNewInstBefore(Shift, I);
6711
Reid Spencer55702aa2007-03-25 21:11:44 +00006712 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006713 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006714 }
6715
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006716 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006717 if (I.getOpcode() == Instruction::LShr) {
6718 assert(ShiftOp->getOpcode() == Instruction::Shl);
6719 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006720 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006721 InsertNewInstBefore(Shift, I);
6722
Reid Spencer68d27cf2007-03-26 23:45:51 +00006723 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006724 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006725 }
6726
6727 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006728 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006729 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006730 return 0;
6731}
6732
Chris Lattnera1be5662002-05-02 17:06:02 +00006733
Chris Lattnercfd65102005-10-29 04:36:15 +00006734/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6735/// expression. If so, decompose it, returning some value X, such that Val is
6736/// X*Scale+Offset.
6737///
6738static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006739 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006740 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006741 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006742 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006743 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006744 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006745 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6746 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6747 if (I->getOpcode() == Instruction::Shl) {
6748 // This is a value scaled by '1 << the shift amt'.
6749 Scale = 1U << RHS->getZExtValue();
6750 Offset = 0;
6751 return I->getOperand(0);
6752 } else if (I->getOpcode() == Instruction::Mul) {
6753 // This value is scaled by 'RHS'.
6754 Scale = RHS->getZExtValue();
6755 Offset = 0;
6756 return I->getOperand(0);
6757 } else if (I->getOpcode() == Instruction::Add) {
6758 // We have X+C. Check to see if we really have (X*C2)+C1,
6759 // where C1 is divisible by C2.
6760 unsigned SubScale;
6761 Value *SubVal =
6762 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6763 Offset += RHS->getZExtValue();
6764 Scale = SubScale;
6765 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006766 }
6767 }
6768 }
6769
6770 // Otherwise, we can't look past this.
6771 Scale = 1;
6772 Offset = 0;
6773 return Val;
6774}
6775
6776
Chris Lattnerb3f83972005-10-24 06:03:58 +00006777/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6778/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006779Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006780 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006781 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006782
Chris Lattnerb53c2382005-10-24 06:22:12 +00006783 // Remove any uses of AI that are dead.
6784 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006785
Chris Lattnerb53c2382005-10-24 06:22:12 +00006786 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6787 Instruction *User = cast<Instruction>(*UI++);
6788 if (isInstructionTriviallyDead(User)) {
6789 while (UI != E && *UI == User)
6790 ++UI; // If this instruction uses AI more than once, don't break UI.
6791
Chris Lattnerb53c2382005-10-24 06:22:12 +00006792 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006793 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006794 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006795 }
6796 }
6797
Chris Lattnerb3f83972005-10-24 06:03:58 +00006798 // Get the type really allocated and the type casted to.
6799 const Type *AllocElTy = AI.getAllocatedType();
6800 const Type *CastElTy = PTy->getElementType();
6801 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006802
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006803 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6804 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006805 if (CastElTyAlign < AllocElTyAlign) return 0;
6806
Chris Lattner39387a52005-10-24 06:35:18 +00006807 // If the allocation has multiple uses, only promote it if we are strictly
6808 // increasing the alignment of the resultant allocation. If we keep it the
6809 // same, we open the door to infinite loops of various kinds.
6810 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6811
Duncan Sands514ab342007-11-01 20:53:16 +00006812 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6813 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006814 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006815
Chris Lattner455fcc82005-10-29 03:19:53 +00006816 // See if we can satisfy the modulus by pulling a scale out of the array
6817 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006818 unsigned ArraySizeScale;
6819 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006820 Value *NumElements = // See if the array size is a decomposable linear expr.
6821 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6822
Chris Lattner455fcc82005-10-29 03:19:53 +00006823 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6824 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006825 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6826 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006827
Chris Lattner455fcc82005-10-29 03:19:53 +00006828 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6829 Value *Amt = 0;
6830 if (Scale == 1) {
6831 Amt = NumElements;
6832 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006833 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006834 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6835 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006836 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006837 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006838 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006839 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006840 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006841 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006842 }
6843
Jeff Cohen86796be2007-04-04 16:58:57 +00006844 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6845 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006846 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006847 Amt = InsertNewInstBefore(Tmp, AI);
6848 }
6849
Chris Lattnerb3f83972005-10-24 06:03:58 +00006850 AllocationInst *New;
6851 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006852 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006853 else
Chris Lattner6934a042007-02-11 01:23:03 +00006854 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006855 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006856 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006857
6858 // If the allocation has multiple uses, insert a cast and change all things
6859 // that used it to use the new cast. This will also hack on CI, but it will
6860 // die soon.
6861 if (!AI.hasOneUse()) {
6862 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006863 // New is the allocation instruction, pointer typed. AI is the original
6864 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6865 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006866 InsertNewInstBefore(NewCast, AI);
6867 AI.replaceAllUsesWith(NewCast);
6868 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006869 return ReplaceInstUsesWith(CI, New);
6870}
6871
Chris Lattner70074e02006-05-13 02:06:03 +00006872/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006873/// and return it as type Ty without inserting any new casts and without
6874/// changing the computed value. This is used by code that tries to decide
6875/// whether promoting or shrinking integer operations to wider or smaller types
6876/// will allow us to eliminate a truncate or extend.
6877///
6878/// This is a truncation operation if Ty is smaller than V->getType(), or an
6879/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00006880///
6881/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6882/// should return true if trunc(V) can be computed by computing V in the smaller
6883/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6884/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6885/// efficiently truncated.
6886///
6887/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6888/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6889/// the final result.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006890bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6891 unsigned CastOpc,
6892 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006893 // We can always evaluate constants in another type.
6894 if (isa<ConstantInt>(V))
6895 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006896
6897 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006898 if (!I) return false;
6899
6900 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006901
Chris Lattner951626b2007-08-02 06:11:14 +00006902 // If this is an extension or truncate, we can often eliminate it.
6903 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6904 // If this is a cast from the destination type, we can trivially eliminate
6905 // it, and this will remove a cast overall.
6906 if (I->getOperand(0)->getType() == Ty) {
6907 // If the first operand is itself a cast, and is eliminable, do not count
6908 // this as an eliminable cast. We would prefer to eliminate those two
6909 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00006910 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00006911 ++NumCastsRemoved;
6912 return true;
6913 }
6914 }
6915
6916 // We can't extend or shrink something that has multiple uses: doing so would
6917 // require duplicating the instruction in general, which isn't profitable.
6918 if (!I->hasOneUse()) return false;
6919
Chris Lattner70074e02006-05-13 02:06:03 +00006920 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006921 case Instruction::Add:
6922 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006923 case Instruction::And:
6924 case Instruction::Or:
6925 case Instruction::Xor:
6926 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006927 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6928 NumCastsRemoved) &&
6929 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6930 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006931
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006932 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006933 // A multiply can be truncated by truncating its operands.
6934 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6935 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6936 NumCastsRemoved) &&
6937 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6938 NumCastsRemoved);
6939
Chris Lattner46b96052006-11-29 07:18:39 +00006940 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006941 // If we are truncating the result of this SHL, and if it's a shift of a
6942 // constant amount, we can always perform a SHL in a smaller type.
6943 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006944 uint32_t BitWidth = Ty->getBitWidth();
6945 if (BitWidth < OrigTy->getBitWidth() &&
6946 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006947 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6948 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006949 }
6950 break;
6951 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006952 // If this is a truncate of a logical shr, we can truncate it to a smaller
6953 // lshr iff we know that the bits we would otherwise be shifting in are
6954 // already zeros.
6955 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006956 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6957 uint32_t BitWidth = Ty->getBitWidth();
6958 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006959 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006960 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6961 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006962 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6963 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006964 }
6965 }
Chris Lattner46b96052006-11-29 07:18:39 +00006966 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006967 case Instruction::ZExt:
6968 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006969 case Instruction::Trunc:
6970 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006971 // can safely replace it. Note that replacing it does not reduce the number
6972 // of casts in the input.
6973 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006974 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00006975 break;
Chris Lattner8114b712008-06-18 04:00:49 +00006976
6977 case Instruction::PHI: {
6978 // We can change a phi if we can change all operands.
6979 PHINode *PN = cast<PHINode>(I);
6980 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6981 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
6982 NumCastsRemoved))
6983 return false;
6984 return true;
6985 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006986 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006987 // TODO: Can handle more cases here.
6988 break;
6989 }
6990
6991 return false;
6992}
6993
6994/// EvaluateInDifferentType - Given an expression that
6995/// CanEvaluateInDifferentType returns true for, actually insert the code to
6996/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006997Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006998 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006999 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007000 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007001
7002 // Otherwise, it must be an instruction.
7003 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007004 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007005 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007006 case Instruction::Add:
7007 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007008 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007009 case Instruction::And:
7010 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007011 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007012 case Instruction::AShr:
7013 case Instruction::LShr:
7014 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007015 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007016 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007017 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner8114b712008-06-18 04:00:49 +00007018 LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007019 break;
7020 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007021 case Instruction::Trunc:
7022 case Instruction::ZExt:
7023 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007024 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007025 // just return the source. There's no need to insert it because it is not
7026 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007027 if (I->getOperand(0)->getType() == Ty)
7028 return I->getOperand(0);
7029
Chris Lattner8114b712008-06-18 04:00:49 +00007030 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007031 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007032 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007033 break;
Chris Lattner8114b712008-06-18 04:00:49 +00007034 case Instruction::PHI: {
7035 PHINode *OPN = cast<PHINode>(I);
7036 PHINode *NPN = PHINode::Create(Ty);
7037 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7038 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7039 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7040 }
7041 Res = NPN;
7042 break;
7043 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007044 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007045 // TODO: Can handle more cases here.
7046 assert(0 && "Unreachable!");
7047 break;
7048 }
7049
Chris Lattner8114b712008-06-18 04:00:49 +00007050 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007051 return InsertNewInstBefore(Res, *I);
7052}
7053
Reid Spencer3da59db2006-11-27 01:05:10 +00007054/// @brief Implement the transforms common to all CastInst visitors.
7055Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007056 Value *Src = CI.getOperand(0);
7057
Dan Gohman23d9d272007-05-11 21:10:54 +00007058 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007059 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007060 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007061 if (Instruction::CastOps opc =
7062 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7063 // The first cast (CSrc) is eliminable so we need to fix up or replace
7064 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007065 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007066 }
7067 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007068
Reid Spencer3da59db2006-11-27 01:05:10 +00007069 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007070 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7071 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7072 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007073
7074 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007075 if (isa<PHINode>(Src))
7076 if (Instruction *NV = FoldOpIntoPhi(CI))
7077 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007078
Reid Spencer3da59db2006-11-27 01:05:10 +00007079 return 0;
7080}
7081
Chris Lattnerd3e28342007-04-27 17:44:50 +00007082/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7083Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7084 Value *Src = CI.getOperand(0);
7085
Chris Lattnerd3e28342007-04-27 17:44:50 +00007086 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007087 // If casting the result of a getelementptr instruction with no offset, turn
7088 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007089 if (GEP->hasAllZeroIndices()) {
7090 // Changing the cast operand is usually not a good idea but it is safe
7091 // here because the pointer operand is being replaced with another
7092 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007093 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007094 CI.setOperand(0, GEP->getOperand(0));
7095 return &CI;
7096 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007097
7098 // If the GEP has a single use, and the base pointer is a bitcast, and the
7099 // GEP computes a constant offset, see if we can convert these three
7100 // instructions into fewer. This typically happens with unions and other
7101 // non-type-safe code.
7102 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7103 if (GEP->hasAllConstantIndices()) {
7104 // We are guaranteed to get a constant from EmitGEPOffset.
7105 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7106 int64_t Offset = OffsetV->getSExtValue();
7107
7108 // Get the base pointer input of the bitcast, and the type it points to.
7109 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7110 const Type *GEPIdxTy =
7111 cast<PointerType>(OrigBase->getType())->getElementType();
7112 if (GEPIdxTy->isSized()) {
7113 SmallVector<Value*, 8> NewIndices;
7114
Chris Lattnerc42e2262007-05-05 01:59:31 +00007115 // Start with the index over the outer type. Note that the type size
7116 // might be zero (even if the offset isn't zero) if the indexed type
7117 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007118 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007119 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007120 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007121 FirstIdx = Offset/TySize;
7122 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007123
Chris Lattnerc42e2262007-05-05 01:59:31 +00007124 // Handle silly modulus not returning values values [0..TySize).
7125 if (Offset < 0) {
7126 --FirstIdx;
7127 Offset += TySize;
7128 assert(Offset >= 0);
7129 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007130 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007131 }
7132
7133 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007134
7135 // Index into the types. If we fail, set OrigBase to null.
7136 while (Offset) {
7137 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7138 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007139 if (Offset < (int64_t)SL->getSizeInBytes()) {
7140 unsigned Elt = SL->getElementContainingOffset(Offset);
7141 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007142
Chris Lattner6b6aef82007-05-15 00:16:00 +00007143 Offset -= SL->getElementOffset(Elt);
7144 GEPIdxTy = STy->getElementType(Elt);
7145 } else {
7146 // Otherwise, we can't index into this, bail out.
7147 Offset = 0;
7148 OrigBase = 0;
7149 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007150 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7151 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007152 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007153 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7154 Offset %= EltSize;
7155 } else {
7156 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7157 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007158 GEPIdxTy = STy->getElementType();
7159 } else {
7160 // Otherwise, we can't index into this, bail out.
7161 Offset = 0;
7162 OrigBase = 0;
7163 }
7164 }
7165 if (OrigBase) {
7166 // If we were able to index down into an element, create the GEP
7167 // and bitcast the result. This eliminates one bitcast, potentially
7168 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007169 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7170 NewIndices.begin(),
7171 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007172 InsertNewInstBefore(NGEP, CI);
7173 NGEP->takeName(GEP);
7174
Chris Lattner9bc14642007-04-28 00:57:34 +00007175 if (isa<BitCastInst>(CI))
7176 return new BitCastInst(NGEP, CI.getType());
7177 assert(isa<PtrToIntInst>(CI));
7178 return new PtrToIntInst(NGEP, CI.getType());
7179 }
7180 }
7181 }
7182 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007183 }
7184
7185 return commonCastTransforms(CI);
7186}
7187
7188
7189
Chris Lattnerc739cd62007-03-03 05:27:34 +00007190/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7191/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007192/// cases.
7193/// @brief Implement the transforms common to CastInst with integer operands
7194Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7195 if (Instruction *Result = commonCastTransforms(CI))
7196 return Result;
7197
7198 Value *Src = CI.getOperand(0);
7199 const Type *SrcTy = Src->getType();
7200 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007201 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7202 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007203
Reid Spencer3da59db2006-11-27 01:05:10 +00007204 // See if we can simplify any instructions used by the LHS whose sole
7205 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007206 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7207 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007208 KnownZero, KnownOne))
7209 return &CI;
7210
7211 // If the source isn't an instruction or has more than one use then we
7212 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007213 Instruction *SrcI = dyn_cast<Instruction>(Src);
7214 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007215 return 0;
7216
Chris Lattnerc739cd62007-03-03 05:27:34 +00007217 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007218 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007219 if (!isa<BitCastInst>(CI) &&
7220 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007221 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007222 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007223 // eliminates the cast, so it is always a win. If this is a zero-extension,
7224 // we need to do an AND to maintain the clear top-part of the computation,
7225 // so we require that the input have eliminated at least one cast. If this
7226 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007227 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007228 bool DoXForm;
7229 switch (CI.getOpcode()) {
7230 default:
7231 // All the others use floating point so we shouldn't actually
7232 // get here because of the check above.
7233 assert(0 && "Unknown cast type");
7234 case Instruction::Trunc:
7235 DoXForm = true;
7236 break;
7237 case Instruction::ZExt:
7238 DoXForm = NumCastsRemoved >= 1;
7239 break;
7240 case Instruction::SExt:
7241 DoXForm = NumCastsRemoved >= 2;
7242 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007243 }
7244
7245 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007246 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7247 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007248 assert(Res->getType() == DestTy);
7249 switch (CI.getOpcode()) {
7250 default: assert(0 && "Unknown cast type!");
7251 case Instruction::Trunc:
7252 case Instruction::BitCast:
7253 // Just replace this cast with the result.
7254 return ReplaceInstUsesWith(CI, Res);
7255 case Instruction::ZExt: {
7256 // We need to emit an AND to clear the high bits.
7257 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007258 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7259 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007260 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007261 }
7262 case Instruction::SExt:
7263 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007264 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007265 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7266 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007267 }
7268 }
7269 }
7270
7271 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7272 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7273
7274 switch (SrcI->getOpcode()) {
7275 case Instruction::Add:
7276 case Instruction::Mul:
7277 case Instruction::And:
7278 case Instruction::Or:
7279 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007280 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007281 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7282 // Don't insert two casts if they cannot be eliminated. We allow
7283 // two casts to be inserted if the sizes are the same. This could
7284 // only be converting signedness, which is a noop.
7285 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7287 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007288 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007289 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7290 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007291 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007292 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007293 }
7294 }
7295
7296 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7297 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7298 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007299 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007300 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007301 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007302 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007303 }
7304 break;
7305 case Instruction::SDiv:
7306 case Instruction::UDiv:
7307 case Instruction::SRem:
7308 case Instruction::URem:
7309 // If we are just changing the sign, rewrite.
7310 if (DestBitSize == SrcBitSize) {
7311 // Don't insert two casts if they cannot be eliminated. We allow
7312 // two casts to be inserted if the sizes are the same. This could
7313 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007314 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7315 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007316 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7317 Op0, DestTy, SrcI);
7318 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7319 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007320 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007321 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7322 }
7323 }
7324 break;
7325
7326 case Instruction::Shl:
7327 // Allow changing the sign of the source operand. Do not allow
7328 // changing the size of the shift, UNLESS the shift amount is a
7329 // constant. We must not change variable sized shifts to a smaller
7330 // size, because it is undefined to shift more bits out than exist
7331 // in the value.
7332 if (DestBitSize == SrcBitSize ||
7333 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007334 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7335 Instruction::BitCast : Instruction::Trunc);
7336 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007337 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007338 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007339 }
7340 break;
7341 case Instruction::AShr:
7342 // If this is a signed shr, and if all bits shifted in are about to be
7343 // truncated off, turn it into an unsigned shr to allow greater
7344 // simplifications.
7345 if (DestBitSize < SrcBitSize &&
7346 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007347 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007348 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7349 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007350 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007351 }
7352 }
7353 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007354 }
7355 return 0;
7356}
7357
Chris Lattner8a9f5712007-04-11 06:57:46 +00007358Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007359 if (Instruction *Result = commonIntCastTransforms(CI))
7360 return Result;
7361
7362 Value *Src = CI.getOperand(0);
7363 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007364 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7365 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007366
7367 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7368 switch (SrcI->getOpcode()) {
7369 default: break;
7370 case Instruction::LShr:
7371 // We can shrink lshr to something smaller if we know the bits shifted in
7372 // are already zeros.
7373 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007374 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007375
7376 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007377 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007378 Value* SrcIOp0 = SrcI->getOperand(0);
7379 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007380 if (ShAmt >= DestBitWidth) // All zeros.
7381 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7382
7383 // Okay, we can shrink this. Truncate the input, then return a new
7384 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007385 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7386 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7387 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007388 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007389 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007390 } else { // This is a variable shr.
7391
7392 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7393 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7394 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007395 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007396 Value *One = ConstantInt::get(SrcI->getType(), 1);
7397
Reid Spencer832254e2007-02-02 02:16:23 +00007398 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007399 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007400 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007401 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007402 SrcI->getOperand(0),
7403 "tmp"), CI);
7404 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007405 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007406 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007407 }
7408 break;
7409 }
7410 }
7411
7412 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007413}
7414
Evan Chengb98a10e2008-03-24 00:21:34 +00007415/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7416/// in order to eliminate the icmp.
7417Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7418 bool DoXform) {
7419 // If we are just checking for a icmp eq of a single bit and zext'ing it
7420 // to an integer, then shift the bit to the appropriate place and then
7421 // cast to integer to avoid the comparison.
7422 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7423 const APInt &Op1CV = Op1C->getValue();
7424
7425 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7426 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7427 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7428 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7429 if (!DoXform) return ICI;
7430
7431 Value *In = ICI->getOperand(0);
7432 Value *Sh = ConstantInt::get(In->getType(),
7433 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007434 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007435 In->getName()+".lobit"),
7436 CI);
7437 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007438 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007439 false/*ZExt*/, "tmp", &CI);
7440
7441 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7442 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007443 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007444 In->getName()+".not"),
7445 CI);
7446 }
7447
7448 return ReplaceInstUsesWith(CI, In);
7449 }
7450
7451
7452
7453 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7454 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7455 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7456 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7457 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7458 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7459 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7460 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7461 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7462 // This only works for EQ and NE
7463 ICI->isEquality()) {
7464 // If Op1C some other power of two, convert:
7465 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7466 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7467 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7468 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7469
7470 APInt KnownZeroMask(~KnownZero);
7471 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7472 if (!DoXform) return ICI;
7473
7474 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7475 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7476 // (X&4) == 2 --> false
7477 // (X&4) != 2 --> true
7478 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7479 Res = ConstantExpr::getZExt(Res, CI.getType());
7480 return ReplaceInstUsesWith(CI, Res);
7481 }
7482
7483 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7484 Value *In = ICI->getOperand(0);
7485 if (ShiftAmt) {
7486 // Perform a logical shr by shiftamt.
7487 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007488 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007489 ConstantInt::get(In->getType(), ShiftAmt),
7490 In->getName()+".lobit"), CI);
7491 }
7492
7493 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7494 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007495 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007496 InsertNewInstBefore(cast<Instruction>(In), CI);
7497 }
7498
7499 if (CI.getType() == In->getType())
7500 return ReplaceInstUsesWith(CI, In);
7501 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007502 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007503 }
7504 }
7505 }
7506
7507 return 0;
7508}
7509
Chris Lattner8a9f5712007-04-11 06:57:46 +00007510Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007511 // If one of the common conversion will work ..
7512 if (Instruction *Result = commonIntCastTransforms(CI))
7513 return Result;
7514
7515 Value *Src = CI.getOperand(0);
7516
7517 // If this is a cast of a cast
7518 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007519 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7520 // types and if the sizes are just right we can convert this into a logical
7521 // 'and' which will be much cheaper than the pair of casts.
7522 if (isa<TruncInst>(CSrc)) {
7523 // Get the sizes of the types involved
7524 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007525 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7526 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7527 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007528 // If we're actually extending zero bits and the trunc is a no-op
7529 if (MidSize < DstSize && SrcSize == DstSize) {
7530 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007531 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007532 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007533 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007535 // Unfortunately, if the type changed, we need to cast it back.
7536 if (And->getType() != CI.getType()) {
7537 And->setName(CSrc->getName()+".mask");
7538 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007539 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007540 }
7541 return And;
7542 }
7543 }
7544 }
7545
Evan Chengb98a10e2008-03-24 00:21:34 +00007546 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7547 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007548
Evan Chengb98a10e2008-03-24 00:21:34 +00007549 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7550 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7551 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7552 // of the (zext icmp) will be transformed.
7553 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7554 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7555 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7556 (transformZExtICmp(LHS, CI, false) ||
7557 transformZExtICmp(RHS, CI, false))) {
7558 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7559 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007560 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007561 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007562 }
7563
Reid Spencer3da59db2006-11-27 01:05:10 +00007564 return 0;
7565}
7566
Chris Lattner8a9f5712007-04-11 06:57:46 +00007567Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007568 if (Instruction *I = commonIntCastTransforms(CI))
7569 return I;
7570
Chris Lattner8a9f5712007-04-11 06:57:46 +00007571 Value *Src = CI.getOperand(0);
7572
7573 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7574 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7575 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7576 // If we are just checking for a icmp eq of a single bit and zext'ing it
7577 // to an integer, then shift the bit to the appropriate place and then
7578 // cast to integer to avoid the comparison.
7579 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7580 const APInt &Op1CV = Op1C->getValue();
7581
7582 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7583 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7584 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7585 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7586 Value *In = ICI->getOperand(0);
7587 Value *Sh = ConstantInt::get(In->getType(),
7588 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007589 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007590 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007591 CI);
7592 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007593 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007594 true/*SExt*/, "tmp", &CI);
7595
7596 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007597 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007598 In->getName()+".not"), CI);
7599
7600 return ReplaceInstUsesWith(CI, In);
7601 }
7602 }
7603 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007604
7605 // See if the value being truncated is already sign extended. If so, just
7606 // eliminate the trunc/sext pair.
7607 if (getOpcode(Src) == Instruction::Trunc) {
7608 Value *Op = cast<User>(Src)->getOperand(0);
7609 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7610 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7611 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7612 unsigned NumSignBits = ComputeNumSignBits(Op);
7613
7614 if (OpBits == DestBits) {
7615 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7616 // bits, it is already ready.
7617 if (NumSignBits > DestBits-MidBits)
7618 return ReplaceInstUsesWith(CI, Op);
7619 } else if (OpBits < DestBits) {
7620 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7621 // bits, just sext from i32.
7622 if (NumSignBits > OpBits-MidBits)
7623 return new SExtInst(Op, CI.getType(), "tmp");
7624 } else {
7625 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7626 // bits, just truncate to i32.
7627 if (NumSignBits > OpBits-MidBits)
7628 return new TruncInst(Op, CI.getType(), "tmp");
7629 }
7630 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007631
Chris Lattnerba417832007-04-11 06:12:58 +00007632 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007633}
7634
Chris Lattnerb7530652008-01-27 05:29:54 +00007635/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7636/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007637static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007638 APFloat F = CFP->getValueAPF();
7639 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007640 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007641 return 0;
7642}
7643
7644/// LookThroughFPExtensions - If this is an fp extension instruction, look
7645/// through it until we get the source value.
7646static Value *LookThroughFPExtensions(Value *V) {
7647 if (Instruction *I = dyn_cast<Instruction>(V))
7648 if (I->getOpcode() == Instruction::FPExt)
7649 return LookThroughFPExtensions(I->getOperand(0));
7650
7651 // If this value is a constant, return the constant in the smallest FP type
7652 // that can accurately represent it. This allows us to turn
7653 // (float)((double)X+2.0) into x+2.0f.
7654 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7655 if (CFP->getType() == Type::PPC_FP128Ty)
7656 return V; // No constant folding of this.
7657 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007658 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007659 return V;
7660 if (CFP->getType() == Type::DoubleTy)
7661 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007662 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007663 return V;
7664 // Don't try to shrink to various long double types.
7665 }
7666
7667 return V;
7668}
7669
7670Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7671 if (Instruction *I = commonCastTransforms(CI))
7672 return I;
7673
7674 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7675 // smaller than the destination type, we can eliminate the truncate by doing
7676 // the add as the smaller type. This applies to add/sub/mul/div as well as
7677 // many builtins (sqrt, etc).
7678 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7679 if (OpI && OpI->hasOneUse()) {
7680 switch (OpI->getOpcode()) {
7681 default: break;
7682 case Instruction::Add:
7683 case Instruction::Sub:
7684 case Instruction::Mul:
7685 case Instruction::FDiv:
7686 case Instruction::FRem:
7687 const Type *SrcTy = OpI->getType();
7688 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7689 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7690 if (LHSTrunc->getType() != SrcTy &&
7691 RHSTrunc->getType() != SrcTy) {
7692 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7693 // If the source types were both smaller than the destination type of
7694 // the cast, do this xform.
7695 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7696 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7697 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7698 CI.getType(), CI);
7699 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7700 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007701 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007702 }
7703 }
7704 break;
7705 }
7706 }
7707 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007708}
7709
7710Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7711 return commonCastTransforms(CI);
7712}
7713
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007714Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7715 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7716 // mantissa to accurately represent all values of X. For example, do not
7717 // do this with i64->float->i64.
7718 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7719 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7720 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007721 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007722 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7723
7724 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007725}
7726
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007727Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7728 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7729 // mantissa to accurately represent all values of X. For example, do not
7730 // do this with i64->float->i64.
7731 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7732 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7733 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007734 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007735 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7736
7737 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007738}
7739
7740Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7741 return commonCastTransforms(CI);
7742}
7743
7744Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7745 return commonCastTransforms(CI);
7746}
7747
7748Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007749 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007750}
7751
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007752Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7753 if (Instruction *I = commonCastTransforms(CI))
7754 return I;
7755
7756 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7757 if (!DestPointee->isSized()) return 0;
7758
7759 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7760 ConstantInt *Cst;
7761 Value *X;
7762 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7763 m_ConstantInt(Cst)))) {
7764 // If the source and destination operands have the same type, see if this
7765 // is a single-index GEP.
7766 if (X->getType() == CI.getType()) {
7767 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007768 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007769
7770 // Convert the constant to intptr type.
7771 APInt Offset = Cst->getValue();
7772 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7773
7774 // If Offset is evenly divisible by Size, we can do this xform.
7775 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7776 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007777 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007778 }
7779 }
7780 // TODO: Could handle other cases, e.g. where add is indexing into field of
7781 // struct etc.
7782 } else if (CI.getOperand(0)->hasOneUse() &&
7783 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7784 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7785 // "inttoptr+GEP" instead of "add+intptr".
7786
7787 // Get the size of the pointee type.
7788 uint64_t Size = TD->getABITypeSize(DestPointee);
7789
7790 // Convert the constant to intptr type.
7791 APInt Offset = Cst->getValue();
7792 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7793
7794 // If Offset is evenly divisible by Size, we can do this xform.
7795 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7796 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7797
7798 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7799 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007800 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007801 }
7802 }
7803 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007804}
7805
Chris Lattnerd3e28342007-04-27 17:44:50 +00007806Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007807 // If the operands are integer typed then apply the integer transforms,
7808 // otherwise just apply the common ones.
7809 Value *Src = CI.getOperand(0);
7810 const Type *SrcTy = Src->getType();
7811 const Type *DestTy = CI.getType();
7812
Chris Lattner42a75512007-01-15 02:27:26 +00007813 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007814 if (Instruction *Result = commonIntCastTransforms(CI))
7815 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007816 } else if (isa<PointerType>(SrcTy)) {
7817 if (Instruction *I = commonPointerCastTransforms(CI))
7818 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007819 } else {
7820 if (Instruction *Result = commonCastTransforms(CI))
7821 return Result;
7822 }
7823
7824
7825 // Get rid of casts from one type to the same type. These are useless and can
7826 // be replaced by the operand.
7827 if (DestTy == Src->getType())
7828 return ReplaceInstUsesWith(CI, Src);
7829
Reid Spencer3da59db2006-11-27 01:05:10 +00007830 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007831 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7832 const Type *DstElTy = DstPTy->getElementType();
7833 const Type *SrcElTy = SrcPTy->getElementType();
7834
Nate Begeman83ad90a2008-03-31 00:22:16 +00007835 // If the address spaces don't match, don't eliminate the bitcast, which is
7836 // required for changing types.
7837 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7838 return 0;
7839
Chris Lattnerd3e28342007-04-27 17:44:50 +00007840 // If we are casting a malloc or alloca to a pointer to a type of the same
7841 // size, rewrite the allocation instruction to allocate the "right" type.
7842 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7843 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7844 return V;
7845
Chris Lattnerd717c182007-05-05 22:32:24 +00007846 // If the source and destination are pointers, and this cast is equivalent
7847 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007848 // This can enhance SROA and other transforms that want type-safe pointers.
7849 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7850 unsigned NumZeros = 0;
7851 while (SrcElTy != DstElTy &&
7852 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7853 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7854 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7855 ++NumZeros;
7856 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007857
Chris Lattnerd3e28342007-04-27 17:44:50 +00007858 // If we found a path from the src to dest, create the getelementptr now.
7859 if (SrcElTy == DstElTy) {
7860 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007861 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7862 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007863 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007864 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007865
Reid Spencer3da59db2006-11-27 01:05:10 +00007866 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7867 if (SVI->hasOneUse()) {
7868 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7869 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007870 if (isa<VectorType>(DestTy) &&
7871 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007872 SVI->getType()->getNumElements()) {
7873 CastInst *Tmp;
7874 // If either of the operands is a cast from CI.getType(), then
7875 // evaluating the shuffle in the casted destination's type will allow
7876 // us to eliminate at least one cast.
7877 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7878 Tmp->getOperand(0)->getType() == DestTy) ||
7879 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7880 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007881 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7882 SVI->getOperand(0), DestTy, &CI);
7883 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7884 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007885 // Return a new shuffle vector. Use the same element ID's, as we
7886 // know the vector types match #elts.
7887 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007888 }
7889 }
7890 }
7891 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007892 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007893}
7894
Chris Lattnere576b912004-04-09 23:46:01 +00007895/// GetSelectFoldableOperands - We want to turn code that looks like this:
7896/// %C = or %A, %B
7897/// %D = select %cond, %C, %A
7898/// into:
7899/// %C = select %cond, %B, 0
7900/// %D = or %A, %C
7901///
7902/// Assuming that the specified instruction is an operand to the select, return
7903/// a bitmask indicating which operands of this instruction are foldable if they
7904/// equal the other incoming value of the select.
7905///
7906static unsigned GetSelectFoldableOperands(Instruction *I) {
7907 switch (I->getOpcode()) {
7908 case Instruction::Add:
7909 case Instruction::Mul:
7910 case Instruction::And:
7911 case Instruction::Or:
7912 case Instruction::Xor:
7913 return 3; // Can fold through either operand.
7914 case Instruction::Sub: // Can only fold on the amount subtracted.
7915 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007916 case Instruction::LShr:
7917 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007918 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007919 default:
7920 return 0; // Cannot fold
7921 }
7922}
7923
7924/// GetSelectFoldableConstant - For the same transformation as the previous
7925/// function, return the identity constant that goes into the select.
7926static Constant *GetSelectFoldableConstant(Instruction *I) {
7927 switch (I->getOpcode()) {
7928 default: assert(0 && "This cannot happen!"); abort();
7929 case Instruction::Add:
7930 case Instruction::Sub:
7931 case Instruction::Or:
7932 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007933 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007934 case Instruction::LShr:
7935 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007936 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007937 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007938 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007939 case Instruction::Mul:
7940 return ConstantInt::get(I->getType(), 1);
7941 }
7942}
7943
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007944/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7945/// have the same opcode and only one use each. Try to simplify this.
7946Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7947 Instruction *FI) {
7948 if (TI->getNumOperands() == 1) {
7949 // If this is a non-volatile load or a cast from the same type,
7950 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007951 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007952 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7953 return 0;
7954 } else {
7955 return 0; // unknown unary op.
7956 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007957
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007958 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007959 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7960 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007961 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007962 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00007963 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007964 }
7965
Reid Spencer832254e2007-02-02 02:16:23 +00007966 // Only handle binary operators here.
7967 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007968 return 0;
7969
7970 // Figure out if the operations have any operands in common.
7971 Value *MatchOp, *OtherOpT, *OtherOpF;
7972 bool MatchIsOpZero;
7973 if (TI->getOperand(0) == FI->getOperand(0)) {
7974 MatchOp = TI->getOperand(0);
7975 OtherOpT = TI->getOperand(1);
7976 OtherOpF = FI->getOperand(1);
7977 MatchIsOpZero = true;
7978 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7979 MatchOp = TI->getOperand(1);
7980 OtherOpT = TI->getOperand(0);
7981 OtherOpF = FI->getOperand(0);
7982 MatchIsOpZero = false;
7983 } else if (!TI->isCommutative()) {
7984 return 0;
7985 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7986 MatchOp = TI->getOperand(0);
7987 OtherOpT = TI->getOperand(1);
7988 OtherOpF = FI->getOperand(0);
7989 MatchIsOpZero = true;
7990 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7991 MatchOp = TI->getOperand(1);
7992 OtherOpT = TI->getOperand(0);
7993 OtherOpF = FI->getOperand(1);
7994 MatchIsOpZero = true;
7995 } else {
7996 return 0;
7997 }
7998
7999 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008000 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8001 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008002 InsertNewInstBefore(NewSI, SI);
8003
8004 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8005 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008006 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008007 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008008 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008009 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008010 assert(0 && "Shouldn't get here");
8011 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008012}
8013
Chris Lattner3d69f462004-03-12 05:52:32 +00008014Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008015 Value *CondVal = SI.getCondition();
8016 Value *TrueVal = SI.getTrueValue();
8017 Value *FalseVal = SI.getFalseValue();
8018
8019 // select true, X, Y -> X
8020 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008021 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008022 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008023
8024 // select C, X, X -> X
8025 if (TrueVal == FalseVal)
8026 return ReplaceInstUsesWith(SI, TrueVal);
8027
Chris Lattnere87597f2004-10-16 18:11:37 +00008028 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8029 return ReplaceInstUsesWith(SI, FalseVal);
8030 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8031 return ReplaceInstUsesWith(SI, TrueVal);
8032 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8033 if (isa<Constant>(TrueVal))
8034 return ReplaceInstUsesWith(SI, TrueVal);
8035 else
8036 return ReplaceInstUsesWith(SI, FalseVal);
8037 }
8038
Reid Spencer4fe16d62007-01-11 18:21:29 +00008039 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008040 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008041 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008042 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008043 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008044 } else {
8045 // Change: A = select B, false, C --> A = and !B, C
8046 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008047 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008048 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008049 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008050 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008051 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008052 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008053 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008054 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008055 } else {
8056 // Change: A = select B, C, true --> A = or !B, C
8057 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008058 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008059 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008060 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008061 }
8062 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008063
8064 // select a, b, a -> a&b
8065 // select a, a, b -> a|b
8066 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008067 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008068 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008069 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008070 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008071
Chris Lattner2eefe512004-04-09 19:05:30 +00008072 // Selecting between two integer constants?
8073 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8074 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008075 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008076 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008077 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008078 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008079 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008080 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008081 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008082 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008083 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008084 }
Chris Lattnerba417832007-04-11 06:12:58 +00008085
8086 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008087
Reid Spencere4d87aa2006-12-23 06:05:41 +00008088 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008089
Reid Spencere4d87aa2006-12-23 06:05:41 +00008090 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008091 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008092 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008093 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008094 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008096 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008097 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008098 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008099 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008100 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008101 InsertNewInstBefore(SRA, SI);
8102
Reid Spencer3da59db2006-11-27 01:05:10 +00008103 // Finally, convert to the type of the select RHS. We figure out
8104 // if this requires a SExt, Trunc or BitCast based on the sizes.
8105 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008106 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8107 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008108 if (SRASize < SISize)
8109 opc = Instruction::SExt;
8110 else if (SRASize > SISize)
8111 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008112 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008113 }
8114 }
8115
8116
8117 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008118 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008119 // non-constant value, eliminate this whole mess. This corresponds to
8120 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008121 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008122 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008123 cast<Constant>(IC->getOperand(1))->isNullValue())
8124 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8125 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008126 isa<ConstantInt>(ICA->getOperand(1)) &&
8127 (ICA->getOperand(1) == TrueValC ||
8128 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008129 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8130 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008131 // know whether we have a icmp_ne or icmp_eq and whether the
8132 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008133 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008134 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008135 Value *V = ICA;
8136 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008137 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008138 Instruction::Xor, V, ICA->getOperand(1)), SI);
8139 return ReplaceInstUsesWith(SI, V);
8140 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008141 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008142 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008143
8144 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008145 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8146 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008147 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008148 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8149 // This is not safe in general for floating point:
8150 // consider X== -0, Y== +0.
8151 // It becomes safe if either operand is a nonzero constant.
8152 ConstantFP *CFPt, *CFPf;
8153 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8154 !CFPt->getValueAPF().isZero()) ||
8155 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8156 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008157 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008158 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008159 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008160 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008161 return ReplaceInstUsesWith(SI, TrueVal);
8162 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8163
Reid Spencere4d87aa2006-12-23 06:05:41 +00008164 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008165 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008166 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8167 // This is not safe in general for floating point:
8168 // consider X== -0, Y== +0.
8169 // It becomes safe if either operand is a nonzero constant.
8170 ConstantFP *CFPt, *CFPf;
8171 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8172 !CFPt->getValueAPF().isZero()) ||
8173 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8174 !CFPf->getValueAPF().isZero()))
8175 return ReplaceInstUsesWith(SI, FalseVal);
8176 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008177 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008178 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8179 return ReplaceInstUsesWith(SI, TrueVal);
8180 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8181 }
8182 }
8183
8184 // See if we are selecting two values based on a comparison of the two values.
8185 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8186 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8187 // Transform (X == Y) ? X : Y -> Y
8188 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8189 return ReplaceInstUsesWith(SI, FalseVal);
8190 // Transform (X != Y) ? X : Y -> X
8191 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8192 return ReplaceInstUsesWith(SI, TrueVal);
8193 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8194
8195 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8196 // Transform (X == Y) ? Y : X -> X
8197 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8198 return ReplaceInstUsesWith(SI, FalseVal);
8199 // Transform (X != Y) ? Y : X -> Y
8200 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008201 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008202 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8203 }
8204 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008205
Chris Lattner87875da2005-01-13 22:52:24 +00008206 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8207 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8208 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008209 Instruction *AddOp = 0, *SubOp = 0;
8210
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008211 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8212 if (TI->getOpcode() == FI->getOpcode())
8213 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8214 return IV;
8215
8216 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8217 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008218 if (TI->getOpcode() == Instruction::Sub &&
8219 FI->getOpcode() == Instruction::Add) {
8220 AddOp = FI; SubOp = TI;
8221 } else if (FI->getOpcode() == Instruction::Sub &&
8222 TI->getOpcode() == Instruction::Add) {
8223 AddOp = TI; SubOp = FI;
8224 }
8225
8226 if (AddOp) {
8227 Value *OtherAddOp = 0;
8228 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8229 OtherAddOp = AddOp->getOperand(1);
8230 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8231 OtherAddOp = AddOp->getOperand(0);
8232 }
8233
8234 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008235 // So at this point we know we have (Y -> OtherAddOp):
8236 // select C, (add X, Y), (sub X, Z)
8237 Value *NegVal; // Compute -Z
8238 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8239 NegVal = ConstantExpr::getNeg(C);
8240 } else {
8241 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008242 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008243 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008244
8245 Value *NewTrueOp = OtherAddOp;
8246 Value *NewFalseOp = NegVal;
8247 if (AddOp != TI)
8248 std::swap(NewTrueOp, NewFalseOp);
8249 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008250 SelectInst::Create(CondVal, NewTrueOp,
8251 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008252
8253 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008254 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008255 }
8256 }
8257 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008258
Chris Lattnere576b912004-04-09 23:46:01 +00008259 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008260 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008261 // See the comment above GetSelectFoldableOperands for a description of the
8262 // transformation we are doing here.
8263 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8264 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8265 !isa<Constant>(FalseVal))
8266 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8267 unsigned OpToFold = 0;
8268 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8269 OpToFold = 1;
8270 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8271 OpToFold = 2;
8272 }
8273
8274 if (OpToFold) {
8275 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008276 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008277 SelectInst::Create(SI.getCondition(),
8278 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008279 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008280 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008282 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008283 else {
8284 assert(0 && "Unknown instruction!!");
8285 }
8286 }
8287 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008288
Chris Lattnere576b912004-04-09 23:46:01 +00008289 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8290 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8291 !isa<Constant>(TrueVal))
8292 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8293 unsigned OpToFold = 0;
8294 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8295 OpToFold = 1;
8296 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8297 OpToFold = 2;
8298 }
8299
8300 if (OpToFold) {
8301 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008302 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008303 SelectInst::Create(SI.getCondition(), C,
8304 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008305 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008306 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008308 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008309 else
Chris Lattnere576b912004-04-09 23:46:01 +00008310 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008311 }
8312 }
8313 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008314
8315 if (BinaryOperator::isNot(CondVal)) {
8316 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8317 SI.setOperand(1, FalseVal);
8318 SI.setOperand(2, TrueVal);
8319 return &SI;
8320 }
8321
Chris Lattner3d69f462004-03-12 05:52:32 +00008322 return 0;
8323}
8324
Dan Gohmaneee962e2008-04-10 18:43:06 +00008325/// EnforceKnownAlignment - If the specified pointer points to an object that
8326/// we control, modify the object's alignment to PrefAlign. This isn't
8327/// often possible though. If alignment is important, a more reliable approach
8328/// is to simply align all global variables and allocation instructions to
8329/// their preferred alignment from the beginning.
8330///
8331static unsigned EnforceKnownAlignment(Value *V,
8332 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008333
Dan Gohmaneee962e2008-04-10 18:43:06 +00008334 User *U = dyn_cast<User>(V);
8335 if (!U) return Align;
8336
8337 switch (getOpcode(U)) {
8338 default: break;
8339 case Instruction::BitCast:
8340 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8341 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008342 // If all indexes are zero, it is just the alignment of the base pointer.
8343 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008344 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008345 if (!isa<Constant>(*i) ||
8346 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008347 AllZeroOperands = false;
8348 break;
8349 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008350
8351 if (AllZeroOperands) {
8352 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008353 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008354 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008355 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008356 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008357 }
8358
8359 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8360 // If there is a large requested alignment and we can, bump up the alignment
8361 // of the global.
8362 if (!GV->isDeclaration()) {
8363 GV->setAlignment(PrefAlign);
8364 Align = PrefAlign;
8365 }
8366 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8367 // If there is a requested alignment and if this is an alloca, round up. We
8368 // don't do this for malloc, because some systems can't respect the request.
8369 if (isa<AllocaInst>(AI)) {
8370 AI->setAlignment(PrefAlign);
8371 Align = PrefAlign;
8372 }
8373 }
8374
8375 return Align;
8376}
8377
8378/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8379/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8380/// and it is more than the alignment of the ultimate object, see if we can
8381/// increase the alignment of the ultimate object, making this check succeed.
8382unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8383 unsigned PrefAlign) {
8384 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8385 sizeof(PrefAlign) * CHAR_BIT;
8386 APInt Mask = APInt::getAllOnesValue(BitWidth);
8387 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8388 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8389 unsigned TrailZ = KnownZero.countTrailingOnes();
8390 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8391
8392 if (PrefAlign > Align)
8393 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8394
8395 // We don't need to make any adjustment.
8396 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008397}
8398
Chris Lattnerf497b022008-01-13 23:50:23 +00008399Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008400 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8401 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008402 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8403 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8404
8405 if (CopyAlign < MinAlign) {
8406 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8407 return MI;
8408 }
8409
8410 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8411 // load/store.
8412 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8413 if (MemOpLength == 0) return 0;
8414
Chris Lattner37ac6082008-01-14 00:28:35 +00008415 // Source and destination pointer types are always "i8*" for intrinsic. See
8416 // if the size is something we can handle with a single primitive load/store.
8417 // A single load+store correctly handles overlapping memory in the memmove
8418 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008419 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008420 if (Size == 0) return MI; // Delete this mem transfer.
8421
8422 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008423 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008424
Chris Lattner37ac6082008-01-14 00:28:35 +00008425 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008426 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008427
8428 // Memcpy forces the use of i8* for the source and destination. That means
8429 // that if you're using memcpy to move one double around, you'll get a cast
8430 // from double* to i8*. We'd much rather use a double load+store rather than
8431 // an i64 load+store, here because this improves the odds that the source or
8432 // dest address will be promotable. See if we can find a better type than the
8433 // integer datatype.
8434 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8435 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8436 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8437 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8438 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008439 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008440 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8441 if (STy->getNumElements() == 1)
8442 SrcETy = STy->getElementType(0);
8443 else
8444 break;
8445 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8446 if (ATy->getNumElements() == 1)
8447 SrcETy = ATy->getElementType();
8448 else
8449 break;
8450 } else
8451 break;
8452 }
8453
Dan Gohman8f8e2692008-05-23 01:52:21 +00008454 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008455 NewPtrTy = PointerType::getUnqual(SrcETy);
8456 }
8457 }
8458
8459
Chris Lattnerf497b022008-01-13 23:50:23 +00008460 // If the memcpy/memmove provides better alignment info than we can
8461 // infer, use it.
8462 SrcAlign = std::max(SrcAlign, CopyAlign);
8463 DstAlign = std::max(DstAlign, CopyAlign);
8464
8465 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8466 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008467 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8468 InsertNewInstBefore(L, *MI);
8469 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8470
8471 // Set the size of the copy to 0, it will be deleted on the next iteration.
8472 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8473 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008474}
Chris Lattner3d69f462004-03-12 05:52:32 +00008475
Chris Lattner69ea9d22008-04-30 06:39:11 +00008476Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8477 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8478 if (MI->getAlignment()->getZExtValue() < Alignment) {
8479 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8480 return MI;
8481 }
8482
8483 // Extract the length and alignment and fill if they are constant.
8484 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8485 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8486 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8487 return 0;
8488 uint64_t Len = LenC->getZExtValue();
8489 Alignment = MI->getAlignment()->getZExtValue();
8490
8491 // If the length is zero, this is a no-op
8492 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8493
8494 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8495 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8496 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8497
8498 Value *Dest = MI->getDest();
8499 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8500
8501 // Alignment 0 is identity for alignment 1 for memset, but not store.
8502 if (Alignment == 0) Alignment = 1;
8503
8504 // Extract the fill value and store.
8505 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8506 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8507 Alignment), *MI);
8508
8509 // Set the size of the copy to 0, it will be deleted on the next iteration.
8510 MI->setLength(Constant::getNullValue(LenC->getType()));
8511 return MI;
8512 }
8513
8514 return 0;
8515}
8516
8517
Chris Lattner8b0ea312006-01-13 20:11:04 +00008518/// visitCallInst - CallInst simplification. This mostly only handles folding
8519/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8520/// the heavy lifting.
8521///
Chris Lattner9fe38862003-06-19 17:00:31 +00008522Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008523 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8524 if (!II) return visitCallSite(&CI);
8525
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008526 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8527 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008528 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008529 bool Changed = false;
8530
8531 // memmove/cpy/set of zero bytes is a noop.
8532 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8533 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8534
Chris Lattner35b9e482004-10-12 04:52:52 +00008535 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008536 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008537 // Replace the instruction with just byte operations. We would
8538 // transform other cases to loads/stores, but we don't know if
8539 // alignment is sufficient.
8540 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008541 }
8542
Chris Lattner35b9e482004-10-12 04:52:52 +00008543 // If we have a memmove and the source operation is a constant global,
8544 // then the source and dest pointers can't alias, so we can change this
8545 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008546 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008547 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8548 if (GVSrc->isConstant()) {
8549 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008550 Intrinsic::ID MemCpyID;
8551 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8552 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008553 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008554 MemCpyID = Intrinsic::memcpy_i64;
8555 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008556 Changed = true;
8557 }
Chris Lattnera935db82008-05-28 05:30:41 +00008558
8559 // memmove(x,x,size) -> noop.
8560 if (MMI->getSource() == MMI->getDest())
8561 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008562 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008563
Chris Lattner95a959d2006-03-06 20:18:44 +00008564 // If we can determine a pointer alignment that is bigger than currently
8565 // set, update the alignment.
8566 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008567 if (Instruction *I = SimplifyMemTransfer(MI))
8568 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008569 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8570 if (Instruction *I = SimplifyMemSet(MSI))
8571 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008572 }
8573
Chris Lattner8b0ea312006-01-13 20:11:04 +00008574 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00008575 }
8576
8577 switch (II->getIntrinsicID()) {
8578 default: break;
8579 case Intrinsic::bswap:
8580 // bswap(bswap(x)) -> x
8581 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8582 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8583 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8584 break;
8585 case Intrinsic::ppc_altivec_lvx:
8586 case Intrinsic::ppc_altivec_lvxl:
8587 case Intrinsic::x86_sse_loadu_ps:
8588 case Intrinsic::x86_sse2_loadu_pd:
8589 case Intrinsic::x86_sse2_loadu_dq:
8590 // Turn PPC lvx -> load if the pointer is known aligned.
8591 // Turn X86 loadups -> load if the pointer is known aligned.
8592 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8593 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8594 PointerType::getUnqual(II->getType()),
8595 CI);
8596 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00008597 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008598 break;
8599 case Intrinsic::ppc_altivec_stvx:
8600 case Intrinsic::ppc_altivec_stvxl:
8601 // Turn stvx -> store if the pointer is known aligned.
8602 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8603 const Type *OpPtrTy =
8604 PointerType::getUnqual(II->getOperand(1)->getType());
8605 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8606 return new StoreInst(II->getOperand(1), Ptr);
8607 }
8608 break;
8609 case Intrinsic::x86_sse_storeu_ps:
8610 case Intrinsic::x86_sse2_storeu_pd:
8611 case Intrinsic::x86_sse2_storeu_dq:
8612 case Intrinsic::x86_sse2_storel_dq:
8613 // Turn X86 storeu -> store if the pointer is known aligned.
8614 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8615 const Type *OpPtrTy =
8616 PointerType::getUnqual(II->getOperand(2)->getType());
8617 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8618 return new StoreInst(II->getOperand(2), Ptr);
8619 }
8620 break;
8621
8622 case Intrinsic::x86_sse_cvttss2si: {
8623 // These intrinsics only demands the 0th element of its input vector. If
8624 // we can simplify the input based on that, do so now.
8625 uint64_t UndefElts;
8626 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8627 UndefElts)) {
8628 II->setOperand(1, V);
8629 return II;
8630 }
8631 break;
8632 }
8633
8634 case Intrinsic::ppc_altivec_vperm:
8635 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8636 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8637 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00008638
Chris Lattner0521e3c2008-06-18 04:33:20 +00008639 // Check that all of the elements are integer constants or undefs.
8640 bool AllEltsOk = true;
8641 for (unsigned i = 0; i != 16; ++i) {
8642 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8643 !isa<UndefValue>(Mask->getOperand(i))) {
8644 AllEltsOk = false;
8645 break;
8646 }
8647 }
8648
8649 if (AllEltsOk) {
8650 // Cast the input vectors to byte vectors.
8651 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8652 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8653 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008654
Chris Lattner0521e3c2008-06-18 04:33:20 +00008655 // Only extract each element once.
8656 Value *ExtractedElts[32];
8657 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8658
Chris Lattnere2ed0572006-04-06 19:19:17 +00008659 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00008660 if (isa<UndefValue>(Mask->getOperand(i)))
8661 continue;
8662 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8663 Idx &= 31; // Match the hardware behavior.
8664
8665 if (ExtractedElts[Idx] == 0) {
8666 Instruction *Elt =
8667 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8668 InsertNewInstBefore(Elt, CI);
8669 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008670 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00008671
Chris Lattner0521e3c2008-06-18 04:33:20 +00008672 // Insert this value into the result vector.
8673 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8674 i, "tmp");
8675 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008676 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008677 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008678 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008679 }
8680 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008681
Chris Lattner0521e3c2008-06-18 04:33:20 +00008682 case Intrinsic::stackrestore: {
8683 // If the save is right next to the restore, remove the restore. This can
8684 // happen when variable allocas are DCE'd.
8685 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8686 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8687 BasicBlock::iterator BI = SS;
8688 if (&*++BI == II)
8689 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008690 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008691 }
8692
8693 // Scan down this block to see if there is another stack restore in the
8694 // same block without an intervening call/alloca.
8695 BasicBlock::iterator BI = II;
8696 TerminatorInst *TI = II->getParent()->getTerminator();
8697 bool CannotRemove = false;
8698 for (++BI; &*BI != TI; ++BI) {
8699 if (isa<AllocaInst>(BI)) {
8700 CannotRemove = true;
8701 break;
8702 }
8703 if (isa<CallInst>(BI)) {
8704 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008705 CannotRemove = true;
8706 break;
8707 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008708 // If there is a stackrestore below this one, remove this one.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008709 return EraseInstFromFunction(CI);
Chris Lattner0521e3c2008-06-18 04:33:20 +00008710 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008711 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008712
8713 // If the stack restore is in a return/unwind block and if there are no
8714 // allocas or calls between the restore and the return, nuke the restore.
8715 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8716 return EraseInstFromFunction(CI);
8717 break;
8718 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008719 }
8720
Chris Lattner8b0ea312006-01-13 20:11:04 +00008721 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008722}
8723
8724// InvokeInst simplification
8725//
8726Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008727 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008728}
8729
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008730/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8731/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008732static bool isSafeToEliminateVarargsCast(const CallSite CS,
8733 const CastInst * const CI,
8734 const TargetData * const TD,
8735 const int ix) {
8736 if (!CI->isLosslessCast())
8737 return false;
8738
8739 // The size of ByVal arguments is derived from the type, so we
8740 // can't change to a type with a different size. If the size were
8741 // passed explicitly we could avoid this check.
8742 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8743 return true;
8744
8745 const Type* SrcTy =
8746 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8747 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8748 if (!SrcTy->isSized() || !DstTy->isSized())
8749 return false;
8750 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8751 return false;
8752 return true;
8753}
8754
Chris Lattnera44d8a22003-10-07 22:32:43 +00008755// visitCallSite - Improvements for call and invoke instructions.
8756//
8757Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008758 bool Changed = false;
8759
8760 // If the callee is a constexpr cast of a function, attempt to move the cast
8761 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008762 if (transformConstExprCastCall(CS)) return 0;
8763
Chris Lattner6c266db2003-10-07 22:54:13 +00008764 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008765
Chris Lattner08b22ec2005-05-13 07:09:09 +00008766 if (Function *CalleeF = dyn_cast<Function>(Callee))
8767 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8768 Instruction *OldCall = CS.getInstruction();
8769 // If the call and callee calling conventions don't match, this call must
8770 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008771 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008772 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8773 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008774 if (!OldCall->use_empty())
8775 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8776 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8777 return EraseInstFromFunction(*OldCall);
8778 return 0;
8779 }
8780
Chris Lattner17be6352004-10-18 02:59:09 +00008781 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8782 // This instruction is not reachable, just remove it. We insert a store to
8783 // undef so that we know that this code is not reachable, despite the fact
8784 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008785 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008786 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008787 CS.getInstruction());
8788
8789 if (!CS.getInstruction()->use_empty())
8790 CS.getInstruction()->
8791 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8792
8793 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8794 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008795 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8796 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008797 }
Chris Lattner17be6352004-10-18 02:59:09 +00008798 return EraseInstFromFunction(*CS.getInstruction());
8799 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008800
Duncan Sandscdb6d922007-09-17 10:26:40 +00008801 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8802 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8803 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8804 return transformCallThroughTrampoline(CS);
8805
Chris Lattner6c266db2003-10-07 22:54:13 +00008806 const PointerType *PTy = cast<PointerType>(Callee->getType());
8807 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8808 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008809 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008810 // See if we can optimize any arguments passed through the varargs area of
8811 // the call.
8812 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008813 E = CS.arg_end(); I != E; ++I, ++ix) {
8814 CastInst *CI = dyn_cast<CastInst>(*I);
8815 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8816 *I = CI->getOperand(0);
8817 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008818 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008819 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008820 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008821
Duncan Sandsf0c33542007-12-19 21:13:37 +00008822 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008823 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008824 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008825 Changed = true;
8826 }
8827
Chris Lattner6c266db2003-10-07 22:54:13 +00008828 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008829}
8830
Chris Lattner9fe38862003-06-19 17:00:31 +00008831// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8832// attempt to move the cast to the arguments of the call/invoke.
8833//
8834bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8835 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8836 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008837 if (CE->getOpcode() != Instruction::BitCast ||
8838 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008839 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008840 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008841 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008842 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008843
8844 // Okay, this is a cast from a function to a different type. Unless doing so
8845 // would cause a type conversion of one of our arguments, change this call to
8846 // be a direct call with arguments casted to the appropriate types.
8847 //
8848 const FunctionType *FT = Callee->getFunctionType();
8849 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008850 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008851
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008852 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008853 return false; // TODO: Handle multiple return values.
8854
Chris Lattnerf78616b2004-01-14 06:06:08 +00008855 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008856 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008857 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008858 // Conversion is ok if changing from one pointer type to another or from
8859 // a pointer to an integer of the same size.
8860 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00008861 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00008862 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008863
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008864 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008865 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008866 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008867 return false; // Cannot transform this return value.
8868
Chris Lattner58d74912008-03-12 17:45:29 +00008869 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8870 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008871 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008872 return false; // Attribute not compatible with transformed value.
8873 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008874
Chris Lattnerf78616b2004-01-14 06:06:08 +00008875 // If the callsite is an invoke instruction, and the return value is used by
8876 // a PHI node in a successor, we cannot change the return type of the call
8877 // because there is no place to put the cast instruction (without breaking
8878 // the critical edge). Bail out in this case.
8879 if (!Caller->use_empty())
8880 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8881 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8882 UI != E; ++UI)
8883 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8884 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008885 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008886 return false;
8887 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008888
8889 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8890 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008891
Chris Lattner9fe38862003-06-19 17:00:31 +00008892 CallSite::arg_iterator AI = CS.arg_begin();
8893 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8894 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008895 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008896
8897 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008898 return false; // Cannot transform this parameter value.
8899
Chris Lattner58d74912008-03-12 17:45:29 +00008900 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8901 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008902
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008903 // Converting from one pointer type to another or between a pointer and an
8904 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008905 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008906 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8907 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008908 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008909 }
8910
8911 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008912 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008913 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008914
Chris Lattner58d74912008-03-12 17:45:29 +00008915 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8916 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008917 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008918 // won't be dropping them. Check that these extra arguments have attributes
8919 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008920 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8921 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008922 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008923 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008924 if (PAttrs & ParamAttr::VarArgsIncompatible)
8925 return false;
8926 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008927
Chris Lattner9fe38862003-06-19 17:00:31 +00008928 // Okay, we decided that this is a safe thing to do: go ahead and start
8929 // inserting cast instructions as necessary...
8930 std::vector<Value*> Args;
8931 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008932 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008933 attrVec.reserve(NumCommonArgs);
8934
8935 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008936 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008937
8938 // If the return value is not being used, the type may not be compatible
8939 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008940 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008941
8942 // Add the new return attributes.
8943 if (RAttrs)
8944 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008945
8946 AI = CS.arg_begin();
8947 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8948 const Type *ParamTy = FT->getParamType(i);
8949 if ((*AI)->getType() == ParamTy) {
8950 Args.push_back(*AI);
8951 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008952 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008953 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008954 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008955 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008956 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008957
8958 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008959 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008960 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008961 }
8962
8963 // If the function takes more arguments than the call was taking, add them
8964 // now...
8965 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8966 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8967
8968 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008969 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008970 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008971 cerr << "WARNING: While resolving call to function '"
8972 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008973 } else {
8974 // Add all of the arguments in their promoted form to the arg list...
8975 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8976 const Type *PTy = getPromotedType((*AI)->getType());
8977 if (PTy != (*AI)->getType()) {
8978 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008979 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8980 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008981 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008982 InsertNewInstBefore(Cast, *Caller);
8983 Args.push_back(Cast);
8984 } else {
8985 Args.push_back(*AI);
8986 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008987
Duncan Sandse1e520f2008-01-13 08:02:44 +00008988 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008989 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008990 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8991 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008992 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008993 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008994
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008995 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008996 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008997
Chris Lattner58d74912008-03-12 17:45:29 +00008998 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008999
Chris Lattner9fe38862003-06-19 17:00:31 +00009000 Instruction *NC;
9001 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009002 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009003 Args.begin(), Args.end(),
9004 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009005 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009006 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009007 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009008 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9009 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009010 CallInst *CI = cast<CallInst>(Caller);
9011 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009012 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009013 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009014 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009015 }
9016
Chris Lattner6934a042007-02-11 01:23:03 +00009017 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009018 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009019 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009020 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009021 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009022 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009023 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009024
9025 // If this is an invoke instruction, we should insert it after the first
9026 // non-phi, instruction in the normal successor block.
9027 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009028 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009029 InsertNewInstBefore(NC, *I);
9030 } else {
9031 // Otherwise, it's a call, just insert cast right after the call instr
9032 InsertNewInstBefore(NC, *Caller);
9033 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009034 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009035 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009036 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009037 }
9038 }
9039
9040 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9041 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009042 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009043 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009044 return true;
9045}
9046
Duncan Sandscdb6d922007-09-17 10:26:40 +00009047// transformCallThroughTrampoline - Turn a call to a function created by the
9048// init_trampoline intrinsic into a direct call to the underlying function.
9049//
9050Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9051 Value *Callee = CS.getCalledValue();
9052 const PointerType *PTy = cast<PointerType>(Callee->getType());
9053 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009054 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009055
9056 // If the call already has the 'nest' attribute somewhere then give up -
9057 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009058 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009059 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009060
9061 IntrinsicInst *Tramp =
9062 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9063
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009064 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009065 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9066 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9067
Chris Lattner58d74912008-03-12 17:45:29 +00009068 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9069 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009070 unsigned NestIdx = 1;
9071 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009072 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009073
9074 // Look for a parameter marked with the 'nest' attribute.
9075 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9076 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009077 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009078 // Record the parameter type and any other attributes.
9079 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009080 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009081 break;
9082 }
9083
9084 if (NestTy) {
9085 Instruction *Caller = CS.getInstruction();
9086 std::vector<Value*> NewArgs;
9087 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9088
Chris Lattner58d74912008-03-12 17:45:29 +00009089 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9090 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009091
Duncan Sandscdb6d922007-09-17 10:26:40 +00009092 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009093 // mean appending it. Likewise for attributes.
9094
9095 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009096 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9097 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009098
Duncan Sandscdb6d922007-09-17 10:26:40 +00009099 {
9100 unsigned Idx = 1;
9101 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9102 do {
9103 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009104 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009105 Value *NestVal = Tramp->getOperand(3);
9106 if (NestVal->getType() != NestTy)
9107 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9108 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009109 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009110 }
9111
9112 if (I == E)
9113 break;
9114
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009115 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009116 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009117 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009118 NewAttrs.push_back
9119 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009120
9121 ++Idx, ++I;
9122 } while (1);
9123 }
9124
9125 // The trampoline may have been bitcast to a bogus type (FTy).
9126 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009127 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009128
Duncan Sandscdb6d922007-09-17 10:26:40 +00009129 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009130 NewTypes.reserve(FTy->getNumParams()+1);
9131
Duncan Sandscdb6d922007-09-17 10:26:40 +00009132 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009133 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009134 {
9135 unsigned Idx = 1;
9136 FunctionType::param_iterator I = FTy->param_begin(),
9137 E = FTy->param_end();
9138
9139 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009140 if (Idx == NestIdx)
9141 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009142 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009143
9144 if (I == E)
9145 break;
9146
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009147 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009148 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009149
9150 ++Idx, ++I;
9151 } while (1);
9152 }
9153
9154 // Replace the trampoline call with a direct call. Let the generic
9155 // code sort out any function type mismatches.
9156 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009157 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009158 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9159 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009160 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009161
9162 Instruction *NewCaller;
9163 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009164 NewCaller = InvokeInst::Create(NewCallee,
9165 II->getNormalDest(), II->getUnwindDest(),
9166 NewArgs.begin(), NewArgs.end(),
9167 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009168 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009169 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009170 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009171 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9172 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009173 if (cast<CallInst>(Caller)->isTailCall())
9174 cast<CallInst>(NewCaller)->setTailCall();
9175 cast<CallInst>(NewCaller)->
9176 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009177 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009178 }
9179 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9180 Caller->replaceAllUsesWith(NewCaller);
9181 Caller->eraseFromParent();
9182 RemoveFromWorkList(Caller);
9183 return 0;
9184 }
9185 }
9186
9187 // Replace the trampoline call with a direct call. Since there is no 'nest'
9188 // parameter, there is no need to adjust the argument list. Let the generic
9189 // code sort out any function type mismatches.
9190 Constant *NewCallee =
9191 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9192 CS.setCalledFunction(NewCallee);
9193 return CS.getInstruction();
9194}
9195
Chris Lattner7da52b22006-11-01 04:51:18 +00009196/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9197/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9198/// and a single binop.
9199Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9200 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009201 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9202 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009203 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009204 Value *LHSVal = FirstInst->getOperand(0);
9205 Value *RHSVal = FirstInst->getOperand(1);
9206
9207 const Type *LHSType = LHSVal->getType();
9208 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009209
9210 // Scan to see if all operands are the same opcode, all have one use, and all
9211 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009212 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009213 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009214 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009215 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009216 // types or GEP's with different index types.
9217 I->getOperand(0)->getType() != LHSType ||
9218 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009219 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009220
9221 // If they are CmpInst instructions, check their predicates
9222 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9223 if (cast<CmpInst>(I)->getPredicate() !=
9224 cast<CmpInst>(FirstInst)->getPredicate())
9225 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009226
9227 // Keep track of which operand needs a phi node.
9228 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9229 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009230 }
9231
Chris Lattner53738a42006-11-08 19:42:28 +00009232 // Otherwise, this is safe to transform, determine if it is profitable.
9233
9234 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9235 // Indexes are often folded into load/store instructions, so we don't want to
9236 // hide them behind a phi.
9237 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9238 return 0;
9239
Chris Lattner7da52b22006-11-01 04:51:18 +00009240 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009241 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009242 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009243 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009244 NewLHS = PHINode::Create(LHSType,
9245 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009246 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9247 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009248 InsertNewInstBefore(NewLHS, PN);
9249 LHSVal = NewLHS;
9250 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009251
9252 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009253 NewRHS = PHINode::Create(RHSType,
9254 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009255 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9256 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009257 InsertNewInstBefore(NewRHS, PN);
9258 RHSVal = NewRHS;
9259 }
9260
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009261 // Add all operands to the new PHIs.
9262 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9263 if (NewLHS) {
9264 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9265 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9266 }
9267 if (NewRHS) {
9268 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9269 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9270 }
9271 }
9272
Chris Lattner7da52b22006-11-01 04:51:18 +00009273 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009274 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009275 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009276 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009277 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009278 else {
9279 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009280 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009281 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009282}
9283
Chris Lattner76c73142006-11-01 07:13:54 +00009284/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9285/// of the block that defines it. This means that it must be obvious the value
9286/// of the load is not changed from the point of the load to the end of the
9287/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009288///
9289/// Finally, it is safe, but not profitable, to sink a load targetting a
9290/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9291/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009292static bool isSafeToSinkLoad(LoadInst *L) {
9293 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9294
9295 for (++BBI; BBI != E; ++BBI)
9296 if (BBI->mayWriteToMemory())
9297 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009298
9299 // Check for non-address taken alloca. If not address-taken already, it isn't
9300 // profitable to do this xform.
9301 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9302 bool isAddressTaken = false;
9303 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9304 UI != E; ++UI) {
9305 if (isa<LoadInst>(UI)) continue;
9306 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9307 // If storing TO the alloca, then the address isn't taken.
9308 if (SI->getOperand(1) == AI) continue;
9309 }
9310 isAddressTaken = true;
9311 break;
9312 }
9313
9314 if (!isAddressTaken)
9315 return false;
9316 }
9317
Chris Lattner76c73142006-11-01 07:13:54 +00009318 return true;
9319}
9320
Chris Lattner9fe38862003-06-19 17:00:31 +00009321
Chris Lattnerbac32862004-11-14 19:13:23 +00009322// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9323// operator and they all are only used by the PHI, PHI together their
9324// inputs, and do the operation once, to the result of the PHI.
9325Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9326 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9327
9328 // Scan the instruction, looking for input operations that can be folded away.
9329 // If all input operands to the phi are the same instruction (e.g. a cast from
9330 // the same type or "+42") we can pull the operation through the PHI, reducing
9331 // code size and simplifying code.
9332 Constant *ConstantOp = 0;
9333 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009334 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009335 if (isa<CastInst>(FirstInst)) {
9336 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009337 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009338 // Can fold binop, compare or shift here if the RHS is a constant,
9339 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009340 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009341 if (ConstantOp == 0)
9342 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009343 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9344 isVolatile = LI->isVolatile();
9345 // We can't sink the load if the loaded value could be modified between the
9346 // load and the PHI.
9347 if (LI->getParent() != PN.getIncomingBlock(0) ||
9348 !isSafeToSinkLoad(LI))
9349 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009350 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009351 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009352 return FoldPHIArgBinOpIntoPHI(PN);
9353 // Can't handle general GEPs yet.
9354 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009355 } else {
9356 return 0; // Cannot fold this operation.
9357 }
9358
9359 // Check to see if all arguments are the same operation.
9360 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9361 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9362 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009363 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009364 return 0;
9365 if (CastSrcTy) {
9366 if (I->getOperand(0)->getType() != CastSrcTy)
9367 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009368 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009369 // We can't sink the load if the loaded value could be modified between
9370 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009371 if (LI->isVolatile() != isVolatile ||
9372 LI->getParent() != PN.getIncomingBlock(i) ||
9373 !isSafeToSinkLoad(LI))
9374 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009375
9376 // If the PHI is volatile and its block has multiple successors, sinking
9377 // it would remove a load of the volatile value from the path through the
9378 // other successor.
9379 if (isVolatile &&
9380 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9381 return 0;
9382
9383
Chris Lattnerbac32862004-11-14 19:13:23 +00009384 } else if (I->getOperand(1) != ConstantOp) {
9385 return 0;
9386 }
9387 }
9388
9389 // Okay, they are all the same operation. Create a new PHI node of the
9390 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009391 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9392 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009393 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009394
9395 Value *InVal = FirstInst->getOperand(0);
9396 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009397
9398 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009399 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9400 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9401 if (NewInVal != InVal)
9402 InVal = 0;
9403 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9404 }
9405
9406 Value *PhiVal;
9407 if (InVal) {
9408 // The new PHI unions all of the same values together. This is really
9409 // common, so we handle it intelligently here for compile-time speed.
9410 PhiVal = InVal;
9411 delete NewPN;
9412 } else {
9413 InsertNewInstBefore(NewPN, PN);
9414 PhiVal = NewPN;
9415 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009416
Chris Lattnerbac32862004-11-14 19:13:23 +00009417 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009418 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009419 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009420 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009421 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009422 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009423 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009424 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009425 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9426
9427 // If this was a volatile load that we are merging, make sure to loop through
9428 // and mark all the input loads as non-volatile. If we don't do this, we will
9429 // insert a new volatile load and the old ones will not be deletable.
9430 if (isVolatile)
9431 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9432 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9433
9434 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009435}
Chris Lattnera1be5662002-05-02 17:06:02 +00009436
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009437/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9438/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009439static bool DeadPHICycle(PHINode *PN,
9440 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009441 if (PN->use_empty()) return true;
9442 if (!PN->hasOneUse()) return false;
9443
9444 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009445 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009446 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009447
9448 // Don't scan crazily complex things.
9449 if (PotentiallyDeadPHIs.size() == 16)
9450 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009451
9452 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9453 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009454
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009455 return false;
9456}
9457
Chris Lattnercf5008a2007-11-06 21:52:06 +00009458/// PHIsEqualValue - Return true if this phi node is always equal to
9459/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9460/// z = some value; x = phi (y, z); y = phi (x, z)
9461static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9462 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9463 // See if we already saw this PHI node.
9464 if (!ValueEqualPHIs.insert(PN))
9465 return true;
9466
9467 // Don't scan crazily complex things.
9468 if (ValueEqualPHIs.size() == 16)
9469 return false;
9470
9471 // Scan the operands to see if they are either phi nodes or are equal to
9472 // the value.
9473 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9474 Value *Op = PN->getIncomingValue(i);
9475 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9476 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9477 return false;
9478 } else if (Op != NonPhiInVal)
9479 return false;
9480 }
9481
9482 return true;
9483}
9484
9485
Chris Lattner473945d2002-05-06 18:06:38 +00009486// PHINode simplification
9487//
Chris Lattner7e708292002-06-25 16:13:24 +00009488Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009489 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009490 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009491
Owen Anderson7e057142006-07-10 22:03:18 +00009492 if (Value *V = PN.hasConstantValue())
9493 return ReplaceInstUsesWith(PN, V);
9494
Owen Anderson7e057142006-07-10 22:03:18 +00009495 // If all PHI operands are the same operation, pull them through the PHI,
9496 // reducing code size.
9497 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9498 PN.getIncomingValue(0)->hasOneUse())
9499 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9500 return Result;
9501
9502 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9503 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9504 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009505 if (PN.hasOneUse()) {
9506 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9507 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009508 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009509 PotentiallyDeadPHIs.insert(&PN);
9510 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9511 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9512 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009513
9514 // If this phi has a single use, and if that use just computes a value for
9515 // the next iteration of a loop, delete the phi. This occurs with unused
9516 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9517 // common case here is good because the only other things that catch this
9518 // are induction variable analysis (sometimes) and ADCE, which is only run
9519 // late.
9520 if (PHIUser->hasOneUse() &&
9521 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9522 PHIUser->use_back() == &PN) {
9523 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9524 }
9525 }
Owen Anderson7e057142006-07-10 22:03:18 +00009526
Chris Lattnercf5008a2007-11-06 21:52:06 +00009527 // We sometimes end up with phi cycles that non-obviously end up being the
9528 // same value, for example:
9529 // z = some value; x = phi (y, z); y = phi (x, z)
9530 // where the phi nodes don't necessarily need to be in the same block. Do a
9531 // quick check to see if the PHI node only contains a single non-phi value, if
9532 // so, scan to see if the phi cycle is actually equal to that value.
9533 {
9534 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9535 // Scan for the first non-phi operand.
9536 while (InValNo != NumOperandVals &&
9537 isa<PHINode>(PN.getIncomingValue(InValNo)))
9538 ++InValNo;
9539
9540 if (InValNo != NumOperandVals) {
9541 Value *NonPhiInVal = PN.getOperand(InValNo);
9542
9543 // Scan the rest of the operands to see if there are any conflicts, if so
9544 // there is no need to recursively scan other phis.
9545 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9546 Value *OpVal = PN.getIncomingValue(InValNo);
9547 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9548 break;
9549 }
9550
9551 // If we scanned over all operands, then we have one unique value plus
9552 // phi values. Scan PHI nodes to see if they all merge in each other or
9553 // the value.
9554 if (InValNo == NumOperandVals) {
9555 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9556 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9557 return ReplaceInstUsesWith(PN, NonPhiInVal);
9558 }
9559 }
9560 }
Chris Lattner60921c92003-12-19 05:58:40 +00009561 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009562}
9563
Reid Spencer17212df2006-12-12 09:18:51 +00009564static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9565 Instruction *InsertPoint,
9566 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009567 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9568 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009569 // We must cast correctly to the pointer type. Ensure that we
9570 // sign extend the integer value if it is smaller as this is
9571 // used for address computation.
9572 Instruction::CastOps opcode =
9573 (VTySize < PtrSize ? Instruction::SExt :
9574 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9575 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009576}
9577
Chris Lattnera1be5662002-05-02 17:06:02 +00009578
Chris Lattner7e708292002-06-25 16:13:24 +00009579Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009580 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009581 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009582 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009583 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009584 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009585
Chris Lattnere87597f2004-10-16 18:11:37 +00009586 if (isa<UndefValue>(GEP.getOperand(0)))
9587 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9588
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009589 bool HasZeroPointerIndex = false;
9590 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9591 HasZeroPointerIndex = C->isNullValue();
9592
9593 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009594 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009595
Chris Lattner28977af2004-04-05 01:30:19 +00009596 // Eliminate unneeded casts for indices.
9597 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009598
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009599 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009600 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9601 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009602 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009603 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009604 if (CI->getOpcode() == Instruction::ZExt ||
9605 CI->getOpcode() == Instruction::SExt) {
9606 const Type *SrcTy = CI->getOperand(0)->getType();
9607 // We can eliminate a cast from i32 to i64 iff the target
9608 // is a 32-bit pointer target.
9609 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9610 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009611 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009612 }
9613 }
9614 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009615 // If we are using a wider index than needed for this platform, shrink it
9616 // to what we need. If the incoming value needs a cast instruction,
9617 // insert it. This explicit cast can make subsequent optimizations more
9618 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009619 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009620 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009621 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009622 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009623 MadeChange = true;
9624 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009625 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9626 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009627 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009628 MadeChange = true;
9629 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009630 }
Chris Lattner28977af2004-04-05 01:30:19 +00009631 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009632 }
Chris Lattner28977af2004-04-05 01:30:19 +00009633 if (MadeChange) return &GEP;
9634
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009635 // If this GEP instruction doesn't move the pointer, and if the input operand
9636 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9637 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009638 if (GEP.hasAllZeroIndices()) {
9639 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9640 // If the bitcast is of an allocation, and the allocation will be
9641 // converted to match the type of the cast, don't touch this.
9642 if (isa<AllocationInst>(BCI->getOperand(0))) {
9643 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009644 if (Instruction *I = visitBitCast(*BCI)) {
9645 if (I != BCI) {
9646 I->takeName(BCI);
9647 BCI->getParent()->getInstList().insert(BCI, I);
9648 ReplaceInstUsesWith(*BCI, I);
9649 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009650 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009651 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009652 }
9653 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9654 }
9655 }
9656
Chris Lattner90ac28c2002-08-02 19:29:35 +00009657 // Combine Indices - If the source pointer to this getelementptr instruction
9658 // is a getelementptr instruction, combine the indices of the two
9659 // getelementptr instructions into a single instruction.
9660 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009661 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009662 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009663 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009664
9665 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009666 // Note that if our source is a gep chain itself that we wait for that
9667 // chain to be resolved before we perform this transformation. This
9668 // avoids us creating a TON of code in some cases.
9669 //
9670 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9671 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9672 return 0; // Wait until our source is folded to completion.
9673
Chris Lattner72588fc2007-02-15 22:48:32 +00009674 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009675
9676 // Find out whether the last index in the source GEP is a sequential idx.
9677 bool EndsWithSequential = false;
9678 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9679 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009680 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009681
Chris Lattner90ac28c2002-08-02 19:29:35 +00009682 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009683 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009684 // Replace: gep (gep %P, long B), long A, ...
9685 // With: T = long A+B; gep %P, T, ...
9686 //
Chris Lattner620ce142004-05-07 22:09:22 +00009687 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009688 if (SO1 == Constant::getNullValue(SO1->getType())) {
9689 Sum = GO1;
9690 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9691 Sum = SO1;
9692 } else {
9693 // If they aren't the same type, convert both to an integer of the
9694 // target's pointer size.
9695 if (SO1->getType() != GO1->getType()) {
9696 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009697 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009698 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009699 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009700 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009701 unsigned PS = TD->getPointerSizeInBits();
9702 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009703 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009704 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009705
Duncan Sands514ab342007-11-01 20:53:16 +00009706 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009707 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009708 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009709 } else {
9710 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009711 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9712 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009713 }
9714 }
9715 }
Chris Lattner620ce142004-05-07 22:09:22 +00009716 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9717 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9718 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009719 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009720 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009721 }
Chris Lattner28977af2004-04-05 01:30:19 +00009722 }
Chris Lattner620ce142004-05-07 22:09:22 +00009723
9724 // Recycle the GEP we already have if possible.
9725 if (SrcGEPOperands.size() == 2) {
9726 GEP.setOperand(0, SrcGEPOperands[0]);
9727 GEP.setOperand(1, Sum);
9728 return &GEP;
9729 } else {
9730 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9731 SrcGEPOperands.end()-1);
9732 Indices.push_back(Sum);
9733 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9734 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009735 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009736 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009737 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009738 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009739 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9740 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009741 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9742 }
9743
9744 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009745 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9746 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009747
Chris Lattner620ce142004-05-07 22:09:22 +00009748 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009749 // GEP of global variable. If all of the indices for this GEP are
9750 // constants, we can promote this to a constexpr instead of an instruction.
9751
9752 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009753 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009754 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9755 for (; I != E && isa<Constant>(*I); ++I)
9756 Indices.push_back(cast<Constant>(*I));
9757
9758 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009759 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9760 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009761
9762 // Replace all uses of the GEP with the new constexpr...
9763 return ReplaceInstUsesWith(GEP, CE);
9764 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009765 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009766 if (!isa<PointerType>(X->getType())) {
9767 // Not interesting. Source pointer must be a cast from pointer.
9768 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009769 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9770 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009771 //
9772 // This occurs when the program declares an array extern like "int X[];"
9773 //
9774 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9775 const PointerType *XTy = cast<PointerType>(X->getType());
9776 if (const ArrayType *XATy =
9777 dyn_cast<ArrayType>(XTy->getElementType()))
9778 if (const ArrayType *CATy =
9779 dyn_cast<ArrayType>(CPTy->getElementType()))
9780 if (CATy->getElementType() == XATy->getElementType()) {
9781 // At this point, we know that the cast source type is a pointer
9782 // to an array of the same type as the destination pointer
9783 // array. Because the array type is never stepped over (there
9784 // is a leading zero) we can fold the cast into this GEP.
9785 GEP.setOperand(0, X);
9786 return &GEP;
9787 }
9788 } else if (GEP.getNumOperands() == 2) {
9789 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009790 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9791 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009792 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9793 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9794 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009795 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9796 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009797 Value *Idx[2];
9798 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9799 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009800 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009801 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009802 // V and GEP are both pointer types --> BitCast
9803 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009804 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009805
9806 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009807 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009808 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009809 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009810
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009811 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009812 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009813 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009814
9815 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9816 // allow either a mul, shift, or constant here.
9817 Value *NewIdx = 0;
9818 ConstantInt *Scale = 0;
9819 if (ArrayEltSize == 1) {
9820 NewIdx = GEP.getOperand(1);
9821 Scale = ConstantInt::get(NewIdx->getType(), 1);
9822 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009823 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009824 Scale = CI;
9825 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9826 if (Inst->getOpcode() == Instruction::Shl &&
9827 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009828 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9829 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9830 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009831 NewIdx = Inst->getOperand(0);
9832 } else if (Inst->getOpcode() == Instruction::Mul &&
9833 isa<ConstantInt>(Inst->getOperand(1))) {
9834 Scale = cast<ConstantInt>(Inst->getOperand(1));
9835 NewIdx = Inst->getOperand(0);
9836 }
9837 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009838
Chris Lattner7835cdd2005-09-13 18:36:04 +00009839 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009840 // out, perform the transformation. Note, we don't know whether Scale is
9841 // signed or not. We'll use unsigned version of division/modulo
9842 // operation after making sure Scale doesn't have the sign bit set.
9843 if (Scale && Scale->getSExtValue() >= 0LL &&
9844 Scale->getZExtValue() % ArrayEltSize == 0) {
9845 Scale = ConstantInt::get(Scale->getType(),
9846 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009847 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009848 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009849 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009850 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009851 NewIdx = InsertNewInstBefore(Sc, GEP);
9852 }
9853
9854 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009855 Value *Idx[2];
9856 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9857 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009858 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009859 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009860 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9861 // The NewGEP must be pointer typed, so must the old one -> BitCast
9862 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009863 }
9864 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009865 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009866 }
9867
Chris Lattner8a2a3112001-12-14 16:52:21 +00009868 return 0;
9869}
9870
Chris Lattner0864acf2002-11-04 16:18:53 +00009871Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9872 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009873 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009874 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9875 const Type *NewTy =
9876 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009877 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009878
9879 // Create and insert the replacement instruction...
9880 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009881 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009882 else {
9883 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009884 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009885 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009886
9887 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009888
Chris Lattner0864acf2002-11-04 16:18:53 +00009889 // Scan to the end of the allocation instructions, to skip over a block of
9890 // allocas if possible...
9891 //
9892 BasicBlock::iterator It = New;
9893 while (isa<AllocationInst>(*It)) ++It;
9894
9895 // Now that I is pointing to the first non-allocation-inst in the block,
9896 // insert our getelementptr instruction...
9897 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009898 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009899 Value *Idx[2];
9900 Idx[0] = NullIdx;
9901 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009902 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9903 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009904
9905 // Now make everything use the getelementptr instead of the original
9906 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009907 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009908 } else if (isa<UndefValue>(AI.getArraySize())) {
9909 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009910 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009911 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009912
9913 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9914 // Note that we only do this for alloca's, because malloc should allocate and
9915 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009916 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009917 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009918 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9919
Chris Lattner0864acf2002-11-04 16:18:53 +00009920 return 0;
9921}
9922
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009923Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9924 Value *Op = FI.getOperand(0);
9925
Chris Lattner17be6352004-10-18 02:59:09 +00009926 // free undef -> unreachable.
9927 if (isa<UndefValue>(Op)) {
9928 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009929 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009930 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009931 return EraseInstFromFunction(FI);
9932 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009933
Chris Lattner6160e852004-02-28 04:57:37 +00009934 // If we have 'free null' delete the instruction. This can happen in stl code
9935 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009936 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009937 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009938
9939 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9940 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9941 FI.setOperand(0, CI->getOperand(0));
9942 return &FI;
9943 }
9944
9945 // Change free (gep X, 0,0,0,0) into free(X)
9946 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9947 if (GEPI->hasAllZeroIndices()) {
9948 AddToWorkList(GEPI);
9949 FI.setOperand(0, GEPI->getOperand(0));
9950 return &FI;
9951 }
9952 }
9953
9954 // Change free(malloc) into nothing, if the malloc has a single use.
9955 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9956 if (MI->hasOneUse()) {
9957 EraseInstFromFunction(FI);
9958 return EraseInstFromFunction(*MI);
9959 }
Chris Lattner6160e852004-02-28 04:57:37 +00009960
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009961 return 0;
9962}
9963
9964
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009965/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009966static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009967 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009968 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009969 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009970
Devang Patel99db6ad2007-10-18 19:52:32 +00009971 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9972 // Instead of loading constant c string, use corresponding integer value
9973 // directly if string length is small enough.
9974 const std::string &Str = CE->getOperand(0)->getStringValue();
9975 if (!Str.empty()) {
9976 unsigned len = Str.length();
9977 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9978 unsigned numBits = Ty->getPrimitiveSizeInBits();
9979 // Replace LI with immediate integer store.
9980 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009981 APInt StrVal(numBits, 0);
9982 APInt SingleChar(numBits, 0);
9983 if (TD->isLittleEndian()) {
9984 for (signed i = len-1; i >= 0; i--) {
9985 SingleChar = (uint64_t) Str[i];
9986 StrVal = (StrVal << 8) | SingleChar;
9987 }
9988 } else {
9989 for (unsigned i = 0; i < len; i++) {
9990 SingleChar = (uint64_t) Str[i];
9991 StrVal = (StrVal << 8) | SingleChar;
9992 }
9993 // Append NULL at the end.
9994 SingleChar = 0;
9995 StrVal = (StrVal << 8) | SingleChar;
9996 }
9997 Value *NL = ConstantInt::get(StrVal);
9998 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009999 }
10000 }
10001 }
10002
Chris Lattnerb89e0712004-07-13 01:49:43 +000010003 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010004 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010005 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010006
Reid Spencer42230162007-01-22 05:51:25 +000010007 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010008 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010009 // If the source is an array, the code below will not succeed. Check to
10010 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10011 // constants.
10012 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10013 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10014 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010015 Value *Idxs[2];
10016 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10017 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010018 SrcTy = cast<PointerType>(CastOp->getType());
10019 SrcPTy = SrcTy->getElementType();
10020 }
10021
Reid Spencer42230162007-01-22 05:51:25 +000010022 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010023 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010024 // Do not allow turning this into a load of an integer, which is then
10025 // casted to a pointer, this pessimizes pointer analysis a lot.
10026 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010027 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10028 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010029
Chris Lattnerf9527852005-01-31 04:50:46 +000010030 // Okay, we are casting from one integer or pointer type to another of
10031 // the same size. Instead of casting the pointer before the load, cast
10032 // the result of the loaded value.
10033 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10034 CI->getName(),
10035 LI.isVolatile()),LI);
10036 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010037 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010038 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010039 }
10040 }
10041 return 0;
10042}
10043
Chris Lattnerc10aced2004-09-19 18:43:46 +000010044/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010045/// from this value cannot trap. If it is not obviously safe to load from the
10046/// specified pointer, we do a quick local scan of the basic block containing
10047/// ScanFrom, to determine if the address is already accessed.
10048static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010049 // If it is an alloca it is always safe to load from.
10050 if (isa<AllocaInst>(V)) return true;
10051
Duncan Sands46318cd2007-09-19 10:25:38 +000010052 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010053 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010054 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010055 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010056
10057 // Otherwise, be a little bit agressive by scanning the local block where we
10058 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010059 // from/to. If so, the previous load or store would have already trapped,
10060 // so there is no harm doing an extra load (also, CSE will later eliminate
10061 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010062 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10063
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010064 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010065 --BBI;
10066
10067 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10068 if (LI->getOperand(0) == V) return true;
10069 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10070 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010071
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010072 }
Chris Lattner8a375202004-09-19 19:18:10 +000010073 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010074}
10075
Chris Lattner8d2e8882007-08-11 18:48:48 +000010076/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10077/// until we find the underlying object a pointer is referring to or something
10078/// we don't understand. Note that the returned pointer may be offset from the
10079/// input, because we ignore GEP indices.
10080static Value *GetUnderlyingObject(Value *Ptr) {
10081 while (1) {
10082 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10083 if (CE->getOpcode() == Instruction::BitCast ||
10084 CE->getOpcode() == Instruction::GetElementPtr)
10085 Ptr = CE->getOperand(0);
10086 else
10087 return Ptr;
10088 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10089 Ptr = BCI->getOperand(0);
10090 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10091 Ptr = GEP->getOperand(0);
10092 } else {
10093 return Ptr;
10094 }
10095 }
10096}
10097
Chris Lattner833b8a42003-06-26 05:06:25 +000010098Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10099 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010100
Dan Gohman9941f742007-07-20 16:34:21 +000010101 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010102 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10103 if (KnownAlign >
10104 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10105 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010106 LI.setAlignment(KnownAlign);
10107
Chris Lattner37366c12005-05-01 04:24:53 +000010108 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010109 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010110 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010111 return Res;
10112
10113 // None of the following transforms are legal for volatile loads.
10114 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010115
Chris Lattner62f254d2005-09-12 22:00:15 +000010116 if (&LI.getParent()->front() != &LI) {
10117 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010118 // If the instruction immediately before this is a store to the same
10119 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010120 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10121 if (SI->getOperand(1) == LI.getOperand(0))
10122 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010123 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10124 if (LIB->getOperand(0) == LI.getOperand(0))
10125 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010126 }
Chris Lattner37366c12005-05-01 04:24:53 +000010127
Christopher Lambb15147e2007-12-29 07:56:53 +000010128 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10129 const Value *GEPI0 = GEPI->getOperand(0);
10130 // TODO: Consider a target hook for valid address spaces for this xform.
10131 if (isa<ConstantPointerNull>(GEPI0) &&
10132 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010133 // Insert a new store to null instruction before the load to indicate
10134 // that this code is not reachable. We do this instead of inserting
10135 // an unreachable instruction directly because we cannot modify the
10136 // CFG.
10137 new StoreInst(UndefValue::get(LI.getType()),
10138 Constant::getNullValue(Op->getType()), &LI);
10139 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10140 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010141 }
Chris Lattner37366c12005-05-01 04:24:53 +000010142
Chris Lattnere87597f2004-10-16 18:11:37 +000010143 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010144 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010145 // TODO: Consider a target hook for valid address spaces for this xform.
10146 if (isa<UndefValue>(C) || (C->isNullValue() &&
10147 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010148 // Insert a new store to null instruction before the load to indicate that
10149 // this code is not reachable. We do this instead of inserting an
10150 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010151 new StoreInst(UndefValue::get(LI.getType()),
10152 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010153 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010154 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010155
Chris Lattnere87597f2004-10-16 18:11:37 +000010156 // Instcombine load (constant global) into the value loaded.
10157 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010158 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010159 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010160
Chris Lattnere87597f2004-10-16 18:11:37 +000010161 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010162 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010163 if (CE->getOpcode() == Instruction::GetElementPtr) {
10164 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010165 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010166 if (Constant *V =
10167 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010168 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010169 if (CE->getOperand(0)->isNullValue()) {
10170 // Insert a new store to null instruction before the load to indicate
10171 // that this code is not reachable. We do this instead of inserting
10172 // an unreachable instruction directly because we cannot modify the
10173 // CFG.
10174 new StoreInst(UndefValue::get(LI.getType()),
10175 Constant::getNullValue(Op->getType()), &LI);
10176 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10177 }
10178
Reid Spencer3da59db2006-11-27 01:05:10 +000010179 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010180 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010181 return Res;
10182 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010183 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010184 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010185
10186 // If this load comes from anywhere in a constant global, and if the global
10187 // is all undef or zero, we know what it loads.
10188 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10189 if (GV->isConstant() && GV->hasInitializer()) {
10190 if (GV->getInitializer()->isNullValue())
10191 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10192 else if (isa<UndefValue>(GV->getInitializer()))
10193 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10194 }
10195 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010196
Chris Lattner37366c12005-05-01 04:24:53 +000010197 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010198 // Change select and PHI nodes to select values instead of addresses: this
10199 // helps alias analysis out a lot, allows many others simplifications, and
10200 // exposes redundancy in the code.
10201 //
10202 // Note that we cannot do the transformation unless we know that the
10203 // introduced loads cannot trap! Something like this is valid as long as
10204 // the condition is always false: load (select bool %C, int* null, int* %G),
10205 // but it would not be valid if we transformed it to load from null
10206 // unconditionally.
10207 //
10208 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10209 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010210 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10211 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010212 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010213 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010214 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010215 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010216 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010217 }
10218
Chris Lattner684fe212004-09-23 15:46:00 +000010219 // load (select (cond, null, P)) -> load P
10220 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10221 if (C->isNullValue()) {
10222 LI.setOperand(0, SI->getOperand(2));
10223 return &LI;
10224 }
10225
10226 // load (select (cond, P, null)) -> load P
10227 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10228 if (C->isNullValue()) {
10229 LI.setOperand(0, SI->getOperand(1));
10230 return &LI;
10231 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010232 }
10233 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010234 return 0;
10235}
10236
Reid Spencer55af2b52007-01-19 21:20:31 +000010237/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010238/// when possible.
10239static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10240 User *CI = cast<User>(SI.getOperand(1));
10241 Value *CastOp = CI->getOperand(0);
10242
10243 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10244 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10245 const Type *SrcPTy = SrcTy->getElementType();
10246
Reid Spencer42230162007-01-22 05:51:25 +000010247 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010248 // If the source is an array, the code below will not succeed. Check to
10249 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10250 // constants.
10251 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10252 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10253 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010254 Value* Idxs[2];
10255 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10256 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010257 SrcTy = cast<PointerType>(CastOp->getType());
10258 SrcPTy = SrcTy->getElementType();
10259 }
10260
Reid Spencer67f827c2007-01-20 23:35:48 +000010261 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10262 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10263 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010264
10265 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010266 // the same size. Instead of casting the pointer before
10267 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010268 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010269 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010270 Instruction::CastOps opcode = Instruction::BitCast;
10271 const Type* CastSrcTy = SIOp0->getType();
10272 const Type* CastDstTy = SrcPTy;
10273 if (isa<PointerType>(CastDstTy)) {
10274 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010275 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010276 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010277 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010278 opcode = Instruction::PtrToInt;
10279 }
10280 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010281 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010282 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010283 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010284 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010285 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010286 return new StoreInst(NewCast, CastOp);
10287 }
10288 }
10289 }
10290 return 0;
10291}
10292
Chris Lattner2f503e62005-01-31 05:36:43 +000010293Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10294 Value *Val = SI.getOperand(0);
10295 Value *Ptr = SI.getOperand(1);
10296
10297 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010298 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010299 ++NumCombined;
10300 return 0;
10301 }
Chris Lattner836692d2007-01-15 06:51:56 +000010302
10303 // If the RHS is an alloca with a single use, zapify the store, making the
10304 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010305 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010306 if (isa<AllocaInst>(Ptr)) {
10307 EraseInstFromFunction(SI);
10308 ++NumCombined;
10309 return 0;
10310 }
10311
10312 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10313 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10314 GEP->getOperand(0)->hasOneUse()) {
10315 EraseInstFromFunction(SI);
10316 ++NumCombined;
10317 return 0;
10318 }
10319 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010320
Dan Gohman9941f742007-07-20 16:34:21 +000010321 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010322 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10323 if (KnownAlign >
10324 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10325 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010326 SI.setAlignment(KnownAlign);
10327
Chris Lattner9ca96412006-02-08 03:25:32 +000010328 // Do really simple DSE, to catch cases where there are several consequtive
10329 // stores to the same location, separated by a few arithmetic operations. This
10330 // situation often occurs with bitfield accesses.
10331 BasicBlock::iterator BBI = &SI;
10332 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10333 --ScanInsts) {
10334 --BBI;
10335
10336 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10337 // Prev store isn't volatile, and stores to the same location?
10338 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10339 ++NumDeadStore;
10340 ++BBI;
10341 EraseInstFromFunction(*PrevSI);
10342 continue;
10343 }
10344 break;
10345 }
10346
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010347 // If this is a load, we have to stop. However, if the loaded value is from
10348 // the pointer we're loading and is producing the pointer we're storing,
10349 // then *this* store is dead (X = load P; store X -> P).
10350 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010351 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010352 EraseInstFromFunction(SI);
10353 ++NumCombined;
10354 return 0;
10355 }
10356 // Otherwise, this is a load from some other location. Stores before it
10357 // may not be dead.
10358 break;
10359 }
10360
Chris Lattner9ca96412006-02-08 03:25:32 +000010361 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010362 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010363 break;
10364 }
10365
10366
10367 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010368
10369 // store X, null -> turns into 'unreachable' in SimplifyCFG
10370 if (isa<ConstantPointerNull>(Ptr)) {
10371 if (!isa<UndefValue>(Val)) {
10372 SI.setOperand(0, UndefValue::get(Val->getType()));
10373 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010374 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010375 ++NumCombined;
10376 }
10377 return 0; // Do not modify these!
10378 }
10379
10380 // store undef, Ptr -> noop
10381 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010382 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010383 ++NumCombined;
10384 return 0;
10385 }
10386
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010387 // If the pointer destination is a cast, see if we can fold the cast into the
10388 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010389 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010390 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10391 return Res;
10392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010393 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010394 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10395 return Res;
10396
Chris Lattner408902b2005-09-12 23:23:25 +000010397
10398 // If this store is the last instruction in the basic block, and if the block
10399 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010400 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010401 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010402 if (BI->isUnconditional())
10403 if (SimplifyStoreAtEndOfBlock(SI))
10404 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010405
Chris Lattner2f503e62005-01-31 05:36:43 +000010406 return 0;
10407}
10408
Chris Lattner3284d1f2007-04-15 00:07:55 +000010409/// SimplifyStoreAtEndOfBlock - Turn things like:
10410/// if () { *P = v1; } else { *P = v2 }
10411/// into a phi node with a store in the successor.
10412///
Chris Lattner31755a02007-04-15 01:02:18 +000010413/// Simplify things like:
10414/// *P = v1; if () { *P = v2; }
10415/// into a phi node with a store in the successor.
10416///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010417bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10418 BasicBlock *StoreBB = SI.getParent();
10419
10420 // Check to see if the successor block has exactly two incoming edges. If
10421 // so, see if the other predecessor contains a store to the same location.
10422 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010423 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010424
10425 // Determine whether Dest has exactly two predecessors and, if so, compute
10426 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010427 pred_iterator PI = pred_begin(DestBB);
10428 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010429 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010430 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010431 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010432 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010433 return false;
10434
10435 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010436 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010437 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010438 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010439 }
Chris Lattner31755a02007-04-15 01:02:18 +000010440 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010441 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000010442
10443 // Bail out if all the relevant blocks aren't distinct (this can happen,
10444 // for example, if SI is in an infinite loop)
10445 if (StoreBB == DestBB || OtherBB == DestBB)
10446 return false;
10447
Chris Lattner31755a02007-04-15 01:02:18 +000010448 // Verify that the other block ends in a branch and is not otherwise empty.
10449 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010450 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010451 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010452 return false;
10453
Chris Lattner31755a02007-04-15 01:02:18 +000010454 // If the other block ends in an unconditional branch, check for the 'if then
10455 // else' case. there is an instruction before the branch.
10456 StoreInst *OtherStore = 0;
10457 if (OtherBr->isUnconditional()) {
10458 // If this isn't a store, or isn't a store to the same location, bail out.
10459 --BBI;
10460 OtherStore = dyn_cast<StoreInst>(BBI);
10461 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10462 return false;
10463 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010464 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010465 // destinations is StoreBB, then we have the if/then case.
10466 if (OtherBr->getSuccessor(0) != StoreBB &&
10467 OtherBr->getSuccessor(1) != StoreBB)
10468 return false;
10469
10470 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010471 // if/then triangle. See if there is a store to the same ptr as SI that
10472 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010473 for (;; --BBI) {
10474 // Check to see if we find the matching store.
10475 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10476 if (OtherStore->getOperand(1) != SI.getOperand(1))
10477 return false;
10478 break;
10479 }
Eli Friedman6903a242008-06-13 22:02:12 +000010480 // If we find something that may be using or overwriting the stored
10481 // value, or if we run out of instructions, we can't do the xform.
10482 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000010483 BBI == OtherBB->begin())
10484 return false;
10485 }
10486
10487 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000010488 // make sure nothing reads or overwrites the stored value in
10489 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010490 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10491 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000010492 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000010493 return false;
10494 }
10495 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010496
Chris Lattner31755a02007-04-15 01:02:18 +000010497 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010498 Value *MergedVal = OtherStore->getOperand(0);
10499 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010500 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010501 PN->reserveOperandSpace(2);
10502 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010503 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10504 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010505 }
10506
10507 // Advance to a place where it is safe to insert the new store and
10508 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010509 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010510 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10511 OtherStore->isVolatile()), *BBI);
10512
10513 // Nuke the old stores.
10514 EraseInstFromFunction(SI);
10515 EraseInstFromFunction(*OtherStore);
10516 ++NumCombined;
10517 return true;
10518}
10519
Chris Lattner2f503e62005-01-31 05:36:43 +000010520
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010521Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10522 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010523 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010524 BasicBlock *TrueDest;
10525 BasicBlock *FalseDest;
10526 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10527 !isa<Constant>(X)) {
10528 // Swap Destinations and condition...
10529 BI.setCondition(X);
10530 BI.setSuccessor(0, FalseDest);
10531 BI.setSuccessor(1, TrueDest);
10532 return &BI;
10533 }
10534
Reid Spencere4d87aa2006-12-23 06:05:41 +000010535 // Cannonicalize fcmp_one -> fcmp_oeq
10536 FCmpInst::Predicate FPred; Value *Y;
10537 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10538 TrueDest, FalseDest)))
10539 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10540 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10541 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010542 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010543 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10544 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010545 // Swap Destinations and condition...
10546 BI.setCondition(NewSCC);
10547 BI.setSuccessor(0, FalseDest);
10548 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010549 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010550 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010551 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010552 return &BI;
10553 }
10554
10555 // Cannonicalize icmp_ne -> icmp_eq
10556 ICmpInst::Predicate IPred;
10557 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10558 TrueDest, FalseDest)))
10559 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10560 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10561 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10562 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010563 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010564 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10565 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010566 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010567 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010568 BI.setSuccessor(0, FalseDest);
10569 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010570 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010571 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010572 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010573 return &BI;
10574 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010575
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010576 return 0;
10577}
Chris Lattner0864acf2002-11-04 16:18:53 +000010578
Chris Lattner46238a62004-07-03 00:26:11 +000010579Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10580 Value *Cond = SI.getCondition();
10581 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10582 if (I->getOpcode() == Instruction::Add)
10583 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10584 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10585 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010586 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010587 AddRHS));
10588 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010589 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010590 return &SI;
10591 }
10592 }
10593 return 0;
10594}
10595
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010596Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10597 // See if we are trying to extract a known value. If so, use that instead.
Matthijs Kooijman710eb232008-06-16 12:57:37 +000010598 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +000010599 EV.idx_end(), &EV))
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010600 return ReplaceInstUsesWith(EV, Elt);
10601
10602 // No changes
10603 return 0;
10604}
10605
Chris Lattner220b0cf2006-03-05 00:22:33 +000010606/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10607/// is to leave as a vector operation.
10608static bool CheapToScalarize(Value *V, bool isConstant) {
10609 if (isa<ConstantAggregateZero>(V))
10610 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010611 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010612 if (isConstant) return true;
10613 // If all elts are the same, we can extract.
10614 Constant *Op0 = C->getOperand(0);
10615 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10616 if (C->getOperand(i) != Op0)
10617 return false;
10618 return true;
10619 }
10620 Instruction *I = dyn_cast<Instruction>(V);
10621 if (!I) return false;
10622
10623 // Insert element gets simplified to the inserted element or is deleted if
10624 // this is constant idx extract element and its a constant idx insertelt.
10625 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10626 isa<ConstantInt>(I->getOperand(2)))
10627 return true;
10628 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10629 return true;
10630 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10631 if (BO->hasOneUse() &&
10632 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10633 CheapToScalarize(BO->getOperand(1), isConstant)))
10634 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010635 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10636 if (CI->hasOneUse() &&
10637 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10638 CheapToScalarize(CI->getOperand(1), isConstant)))
10639 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010640
10641 return false;
10642}
10643
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010644/// Read and decode a shufflevector mask.
10645///
10646/// It turns undef elements into values that are larger than the number of
10647/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010648static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10649 unsigned NElts = SVI->getType()->getNumElements();
10650 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10651 return std::vector<unsigned>(NElts, 0);
10652 if (isa<UndefValue>(SVI->getOperand(2)))
10653 return std::vector<unsigned>(NElts, 2*NElts);
10654
10655 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010656 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000010657 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10658 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000010659 Result.push_back(NElts*2); // undef -> 8
10660 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000010661 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010662 return Result;
10663}
10664
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010665/// FindScalarElement - Given a vector and an element number, see if the scalar
10666/// value is already around as a register, for example if it were inserted then
10667/// extracted from the vector.
10668static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010669 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10670 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010671 unsigned Width = PTy->getNumElements();
10672 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010673 return UndefValue::get(PTy->getElementType());
10674
10675 if (isa<UndefValue>(V))
10676 return UndefValue::get(PTy->getElementType());
10677 else if (isa<ConstantAggregateZero>(V))
10678 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010679 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010680 return CP->getOperand(EltNo);
10681 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10682 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010683 if (!isa<ConstantInt>(III->getOperand(2)))
10684 return 0;
10685 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010686
10687 // If this is an insert to the element we are looking for, return the
10688 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010689 if (EltNo == IIElt)
10690 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010691
10692 // Otherwise, the insertelement doesn't modify the value, recurse on its
10693 // vector input.
10694 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010695 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010696 unsigned InEl = getShuffleMask(SVI)[EltNo];
10697 if (InEl < Width)
10698 return FindScalarElement(SVI->getOperand(0), InEl);
10699 else if (InEl < Width*2)
10700 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10701 else
10702 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010703 }
10704
10705 // Otherwise, we don't know.
10706 return 0;
10707}
10708
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010709Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010710 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010711 if (isa<UndefValue>(EI.getOperand(0)))
10712 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10713
Dan Gohman07a96762007-07-16 14:29:03 +000010714 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010715 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10716 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10717
Reid Spencer9d6565a2007-02-15 02:26:10 +000010718 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010719 // If vector val is constant with all elements the same, replace EI with
10720 // that element. When the elements are not identical, we cannot replace yet
10721 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010722 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010723 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010724 if (C->getOperand(i) != op0) {
10725 op0 = 0;
10726 break;
10727 }
10728 if (op0)
10729 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010730 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010731
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010732 // If extracting a specified index from the vector, see if we can recursively
10733 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010734 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010735 unsigned IndexVal = IdxC->getZExtValue();
10736 unsigned VectorWidth =
10737 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10738
10739 // If this is extracting an invalid index, turn this into undef, to avoid
10740 // crashing the code below.
10741 if (IndexVal >= VectorWidth)
10742 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10743
Chris Lattner867b99f2006-10-05 06:55:50 +000010744 // This instruction only demands the single element from the input vector.
10745 // If the input vector has a single use, simplify it based on this use
10746 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010747 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010748 uint64_t UndefElts;
10749 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010750 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010751 UndefElts)) {
10752 EI.setOperand(0, V);
10753 return &EI;
10754 }
10755 }
10756
Reid Spencerb83eb642006-10-20 07:07:24 +000010757 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010758 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010759
10760 // If the this extractelement is directly using a bitcast from a vector of
10761 // the same number of elements, see if we can find the source element from
10762 // it. In this case, we will end up needing to bitcast the scalars.
10763 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10764 if (const VectorType *VT =
10765 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10766 if (VT->getNumElements() == VectorWidth)
10767 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10768 return new BitCastInst(Elt, EI.getType());
10769 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010770 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010771
Chris Lattner73fa49d2006-05-25 22:53:38 +000010772 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010773 if (I->hasOneUse()) {
10774 // Push extractelement into predecessor operation if legal and
10775 // profitable to do so
10776 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010777 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10778 if (CheapToScalarize(BO, isConstantElt)) {
10779 ExtractElementInst *newEI0 =
10780 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10781 EI.getName()+".lhs");
10782 ExtractElementInst *newEI1 =
10783 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10784 EI.getName()+".rhs");
10785 InsertNewInstBefore(newEI0, EI);
10786 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010787 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010788 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010789 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010790 unsigned AS =
10791 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010792 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10793 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010794 GetElementPtrInst *GEP =
10795 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010796 InsertNewInstBefore(GEP, EI);
10797 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010798 }
10799 }
10800 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10801 // Extracting the inserted element?
10802 if (IE->getOperand(2) == EI.getOperand(1))
10803 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10804 // If the inserted and extracted elements are constants, they must not
10805 // be the same value, extract from the pre-inserted value instead.
10806 if (isa<Constant>(IE->getOperand(2)) &&
10807 isa<Constant>(EI.getOperand(1))) {
10808 AddUsesToWorkList(EI);
10809 EI.setOperand(0, IE->getOperand(0));
10810 return &EI;
10811 }
10812 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10813 // If this is extracting an element from a shufflevector, figure out where
10814 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010815 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10816 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010817 Value *Src;
10818 if (SrcIdx < SVI->getType()->getNumElements())
10819 Src = SVI->getOperand(0);
10820 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10821 SrcIdx -= SVI->getType()->getNumElements();
10822 Src = SVI->getOperand(1);
10823 } else {
10824 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010825 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010826 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010827 }
10828 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010829 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010830 return 0;
10831}
10832
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010833/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10834/// elements from either LHS or RHS, return the shuffle mask and true.
10835/// Otherwise, return false.
10836static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10837 std::vector<Constant*> &Mask) {
10838 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10839 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010840 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010841
10842 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010843 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010844 return true;
10845 } else if (V == LHS) {
10846 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010847 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010848 return true;
10849 } else if (V == RHS) {
10850 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010851 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010852 return true;
10853 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10854 // If this is an insert of an extract from some other vector, include it.
10855 Value *VecOp = IEI->getOperand(0);
10856 Value *ScalarOp = IEI->getOperand(1);
10857 Value *IdxOp = IEI->getOperand(2);
10858
Chris Lattnerd929f062006-04-27 21:14:21 +000010859 if (!isa<ConstantInt>(IdxOp))
10860 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010861 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010862
10863 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10864 // Okay, we can handle this if the vector we are insertinting into is
10865 // transitively ok.
10866 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10867 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010868 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010869 return true;
10870 }
10871 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10872 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010873 EI->getOperand(0)->getType() == V->getType()) {
10874 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010875 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010876
10877 // This must be extracting from either LHS or RHS.
10878 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10879 // Okay, we can handle this if the vector we are insertinting into is
10880 // transitively ok.
10881 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10882 // If so, update the mask to reflect the inserted value.
10883 if (EI->getOperand(0) == LHS) {
10884 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010885 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010886 } else {
10887 assert(EI->getOperand(0) == RHS);
10888 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010889 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010890
10891 }
10892 return true;
10893 }
10894 }
10895 }
10896 }
10897 }
10898 // TODO: Handle shufflevector here!
10899
10900 return false;
10901}
10902
10903/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10904/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10905/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010906static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010907 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010908 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010909 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010910 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010911 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010912
10913 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010914 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010915 return V;
10916 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010917 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010918 return V;
10919 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10920 // If this is an insert of an extract from some other vector, include it.
10921 Value *VecOp = IEI->getOperand(0);
10922 Value *ScalarOp = IEI->getOperand(1);
10923 Value *IdxOp = IEI->getOperand(2);
10924
10925 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10926 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10927 EI->getOperand(0)->getType() == V->getType()) {
10928 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010929 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10930 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010931
10932 // Either the extracted from or inserted into vector must be RHSVec,
10933 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010934 if (EI->getOperand(0) == RHS || RHS == 0) {
10935 RHS = EI->getOperand(0);
10936 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010937 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010938 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010939 return V;
10940 }
10941
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010942 if (VecOp == RHS) {
10943 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010944 // Everything but the extracted element is replaced with the RHS.
10945 for (unsigned i = 0; i != NumElts; ++i) {
10946 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010947 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010948 }
10949 return V;
10950 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010951
10952 // If this insertelement is a chain that comes from exactly these two
10953 // vectors, return the vector and the effective shuffle.
10954 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10955 return EI->getOperand(0);
10956
Chris Lattnerefb47352006-04-15 01:39:45 +000010957 }
10958 }
10959 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010960 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010961
10962 // Otherwise, can't do anything fancy. Return an identity vector.
10963 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010964 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010965 return V;
10966}
10967
10968Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10969 Value *VecOp = IE.getOperand(0);
10970 Value *ScalarOp = IE.getOperand(1);
10971 Value *IdxOp = IE.getOperand(2);
10972
Chris Lattner599ded12007-04-09 01:11:16 +000010973 // Inserting an undef or into an undefined place, remove this.
10974 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10975 ReplaceInstUsesWith(IE, VecOp);
10976
Chris Lattnerefb47352006-04-15 01:39:45 +000010977 // If the inserted element was extracted from some other vector, and if the
10978 // indexes are constant, try to turn this into a shufflevector operation.
10979 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10980 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10981 EI->getOperand(0)->getType() == IE.getType()) {
10982 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010983 unsigned ExtractedIdx =
10984 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010985 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010986
10987 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10988 return ReplaceInstUsesWith(IE, VecOp);
10989
10990 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10991 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10992
10993 // If we are extracting a value from a vector, then inserting it right
10994 // back into the same place, just use the input vector.
10995 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10996 return ReplaceInstUsesWith(IE, VecOp);
10997
10998 // We could theoretically do this for ANY input. However, doing so could
10999 // turn chains of insertelement instructions into a chain of shufflevector
11000 // instructions, and right now we do not merge shufflevectors. As such,
11001 // only do this in a situation where it is clear that there is benefit.
11002 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11003 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11004 // the values of VecOp, except then one read from EIOp0.
11005 // Build a new shuffle mask.
11006 std::vector<Constant*> Mask;
11007 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011008 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011009 else {
11010 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011011 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011012 NumVectorElts));
11013 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011014 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011015 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011016 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011017 }
11018
11019 // If this insertelement isn't used by some other insertelement, turn it
11020 // (and any insertelements it points to), into one big shuffle.
11021 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11022 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011023 Value *RHS = 0;
11024 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11025 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11026 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011027 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011028 }
11029 }
11030 }
11031
11032 return 0;
11033}
11034
11035
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011036Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11037 Value *LHS = SVI.getOperand(0);
11038 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011039 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011040
11041 bool MadeChange = false;
11042
Chris Lattner867b99f2006-10-05 06:55:50 +000011043 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011044 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011045 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11046
Chris Lattnere4929dd2007-01-05 07:36:08 +000011047 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011048 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011049 if (isa<UndefValue>(SVI.getOperand(1))) {
11050 // Scan to see if there are any references to the RHS. If so, replace them
11051 // with undef element refs and set MadeChange to true.
11052 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11053 if (Mask[i] >= e && Mask[i] != 2*e) {
11054 Mask[i] = 2*e;
11055 MadeChange = true;
11056 }
11057 }
11058
11059 if (MadeChange) {
11060 // Remap any references to RHS to use LHS.
11061 std::vector<Constant*> Elts;
11062 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11063 if (Mask[i] == 2*e)
11064 Elts.push_back(UndefValue::get(Type::Int32Ty));
11065 else
11066 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11067 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011068 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011069 }
11070 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011071
Chris Lattner863bcff2006-05-25 23:48:38 +000011072 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11073 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11074 if (LHS == RHS || isa<UndefValue>(LHS)) {
11075 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011076 // shuffle(undef,undef,mask) -> undef.
11077 return ReplaceInstUsesWith(SVI, LHS);
11078 }
11079
Chris Lattner863bcff2006-05-25 23:48:38 +000011080 // Remap any references to RHS to use LHS.
11081 std::vector<Constant*> Elts;
11082 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011083 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011084 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011085 else {
11086 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11087 (Mask[i] < e && isa<UndefValue>(LHS)))
11088 Mask[i] = 2*e; // Turn into undef.
11089 else
11090 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011091 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011092 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011093 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011094 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011095 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011096 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011097 LHS = SVI.getOperand(0);
11098 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011099 MadeChange = true;
11100 }
11101
Chris Lattner7b2e27922006-05-26 00:29:06 +000011102 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011103 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011104
Chris Lattner863bcff2006-05-25 23:48:38 +000011105 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11106 if (Mask[i] >= e*2) continue; // Ignore undef values.
11107 // Is this an identity shuffle of the LHS value?
11108 isLHSID &= (Mask[i] == i);
11109
11110 // Is this an identity shuffle of the RHS value?
11111 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011112 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011113
Chris Lattner863bcff2006-05-25 23:48:38 +000011114 // Eliminate identity shuffles.
11115 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11116 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011117
Chris Lattner7b2e27922006-05-26 00:29:06 +000011118 // If the LHS is a shufflevector itself, see if we can combine it with this
11119 // one without producing an unusual shuffle. Here we are really conservative:
11120 // we are absolutely afraid of producing a shuffle mask not in the input
11121 // program, because the code gen may not be smart enough to turn a merged
11122 // shuffle into two specific shuffles: it may produce worse code. As such,
11123 // we only merge two shuffles if the result is one of the two input shuffle
11124 // masks. In this case, merging the shuffles just removes one instruction,
11125 // which we know is safe. This is good for things like turning:
11126 // (splat(splat)) -> splat.
11127 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11128 if (isa<UndefValue>(RHS)) {
11129 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11130
11131 std::vector<unsigned> NewMask;
11132 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11133 if (Mask[i] >= 2*e)
11134 NewMask.push_back(2*e);
11135 else
11136 NewMask.push_back(LHSMask[Mask[i]]);
11137
11138 // If the result mask is equal to the src shuffle or this shuffle mask, do
11139 // the replacement.
11140 if (NewMask == LHSMask || NewMask == Mask) {
11141 std::vector<Constant*> Elts;
11142 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11143 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011144 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011145 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011146 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011147 }
11148 }
11149 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11150 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011151 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011152 }
11153 }
11154 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011155
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011156 return MadeChange ? &SVI : 0;
11157}
11158
11159
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011160
Chris Lattnerea1c4542004-12-08 23:43:58 +000011161
11162/// TryToSinkInstruction - Try to move the specified instruction from its
11163/// current block into the beginning of DestBlock, which can only happen if it's
11164/// safe to move the instruction past all of the instructions between it and the
11165/// end of its block.
11166static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11167 assert(I->hasOneUse() && "Invariants didn't hold!");
11168
Chris Lattner108e9022005-10-27 17:13:11 +000011169 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011170 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11171 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011172
Chris Lattnerea1c4542004-12-08 23:43:58 +000011173 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011174 if (isa<AllocaInst>(I) && I->getParent() ==
11175 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011176 return false;
11177
Chris Lattner96a52a62004-12-09 07:14:34 +000011178 // We can only sink load instructions if there is nothing between the load and
11179 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011180 if (I->mayReadFromMemory()) {
11181 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011182 Scan != E; ++Scan)
11183 if (Scan->mayWriteToMemory())
11184 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011185 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011186
Dan Gohman02dea8b2008-05-23 21:05:58 +000011187 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011188
Chris Lattner4bc5f802005-08-08 19:11:57 +000011189 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011190 ++NumSunkInst;
11191 return true;
11192}
11193
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011194
11195/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11196/// all reachable code to the worklist.
11197///
11198/// This has a couple of tricks to make the code faster and more powerful. In
11199/// particular, we constant fold and DCE instructions as we go, to avoid adding
11200/// them to the worklist (this significantly speeds up instcombine on code where
11201/// many instructions are dead or constant). Additionally, if we find a branch
11202/// whose condition is a known constant, we only visit the reachable successors.
11203///
11204static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011205 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011206 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011207 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011208 std::vector<BasicBlock*> Worklist;
11209 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011210
Chris Lattner2c7718a2007-03-23 19:17:18 +000011211 while (!Worklist.empty()) {
11212 BB = Worklist.back();
11213 Worklist.pop_back();
11214
11215 // We have now visited this block! If we've already been here, ignore it.
11216 if (!Visited.insert(BB)) continue;
11217
11218 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11219 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011220
Chris Lattner2c7718a2007-03-23 19:17:18 +000011221 // DCE instruction if trivially dead.
11222 if (isInstructionTriviallyDead(Inst)) {
11223 ++NumDeadInst;
11224 DOUT << "IC: DCE: " << *Inst;
11225 Inst->eraseFromParent();
11226 continue;
11227 }
11228
11229 // ConstantProp instruction if trivially constant.
11230 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11231 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11232 Inst->replaceAllUsesWith(C);
11233 ++NumConstProp;
11234 Inst->eraseFromParent();
11235 continue;
11236 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011237
Chris Lattner2c7718a2007-03-23 19:17:18 +000011238 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011239 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011240
11241 // Recursively visit successors. If this is a branch or switch on a
11242 // constant, only visit the reachable successor.
11243 TerminatorInst *TI = BB->getTerminator();
11244 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11245 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11246 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011247 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011248 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011249 continue;
11250 }
11251 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11252 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11253 // See if this is an explicit destination.
11254 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11255 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011256 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011257 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011258 continue;
11259 }
11260
11261 // Otherwise it is the default destination.
11262 Worklist.push_back(SI->getSuccessor(0));
11263 continue;
11264 }
11265 }
11266
11267 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11268 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011269 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011270}
11271
Chris Lattnerec9c3582007-03-03 02:04:50 +000011272bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011273 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011274 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011275
11276 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11277 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011278
Chris Lattnerb3d59702005-07-07 20:40:38 +000011279 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011280 // Do a depth-first traversal of the function, populate the worklist with
11281 // the reachable instructions. Ignore blocks that are not reachable. Keep
11282 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011283 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011284 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011285
Chris Lattnerb3d59702005-07-07 20:40:38 +000011286 // Do a quick scan over the function. If we find any blocks that are
11287 // unreachable, remove any instructions inside of them. This prevents
11288 // the instcombine code from having to deal with some bad special cases.
11289 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11290 if (!Visited.count(BB)) {
11291 Instruction *Term = BB->getTerminator();
11292 while (Term != BB->begin()) { // Remove instrs bottom-up
11293 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011294
Bill Wendlingb7427032006-11-26 09:46:52 +000011295 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011296 ++NumDeadInst;
11297
11298 if (!I->use_empty())
11299 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11300 I->eraseFromParent();
11301 }
11302 }
11303 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011304
Chris Lattnerdbab3862007-03-02 21:28:56 +000011305 while (!Worklist.empty()) {
11306 Instruction *I = RemoveOneFromWorkList();
11307 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011308
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011309 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011310 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011311 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011312 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011313 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011314 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011315
Bill Wendlingb7427032006-11-26 09:46:52 +000011316 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011317
11318 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011319 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011320 continue;
11321 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011322
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011323 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011324 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011325 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011326
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011327 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011328 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011329 ReplaceInstUsesWith(*I, C);
11330
Chris Lattner62b14df2002-09-02 04:59:56 +000011331 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011332 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011333 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011334 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011335 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011336
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011337 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11338 // See if we can constant fold its operands.
11339 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11340 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11341 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11342 i->set(NewC);
11343 }
11344 }
11345 }
11346
Chris Lattnerea1c4542004-12-08 23:43:58 +000011347 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011348 // FIXME: Remove GetResultInst test when first class support for aggregates
11349 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011350 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011351 BasicBlock *BB = I->getParent();
11352 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11353 if (UserParent != BB) {
11354 bool UserIsSuccessor = false;
11355 // See if the user is one of our successors.
11356 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11357 if (*SI == UserParent) {
11358 UserIsSuccessor = true;
11359 break;
11360 }
11361
11362 // If the user is one of our immediate successors, and if that successor
11363 // only has us as a predecessors (we'd have to split the critical edge
11364 // otherwise), we can keep going.
11365 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11366 next(pred_begin(UserParent)) == pred_end(UserParent))
11367 // Okay, the CFG is simple enough, try to sink this instruction.
11368 Changed |= TryToSinkInstruction(I, UserParent);
11369 }
11370 }
11371
Chris Lattner8a2a3112001-12-14 16:52:21 +000011372 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011373#ifndef NDEBUG
11374 std::string OrigI;
11375#endif
11376 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011377 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011378 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011379 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011380 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011381 DOUT << "IC: Old = " << *I
11382 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011383
Chris Lattnerf523d062004-06-09 05:08:07 +000011384 // Everything uses the new instruction now.
11385 I->replaceAllUsesWith(Result);
11386
11387 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011388 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011389 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011390
Chris Lattner6934a042007-02-11 01:23:03 +000011391 // Move the name to the new instruction first.
11392 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011393
11394 // Insert the new instruction into the basic block...
11395 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011396 BasicBlock::iterator InsertPos = I;
11397
11398 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11399 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11400 ++InsertPos;
11401
11402 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011403
Chris Lattner00d51312004-05-01 23:27:23 +000011404 // Make sure that we reprocess all operands now that we reduced their
11405 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011406 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011407
Chris Lattnerf523d062004-06-09 05:08:07 +000011408 // Instructions can end up on the worklist more than once. Make sure
11409 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011410 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011411
11412 // Erase the old instruction.
11413 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011414 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011415#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011416 DOUT << "IC: Mod = " << OrigI
11417 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011418#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011419
Chris Lattner90ac28c2002-08-02 19:29:35 +000011420 // If the instruction was modified, it's possible that it is now dead.
11421 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011422 if (isInstructionTriviallyDead(I)) {
11423 // Make sure we process all operands now that we are reducing their
11424 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011425 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011426
Chris Lattner00d51312004-05-01 23:27:23 +000011427 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011428 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011429 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011430 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011431 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011432 AddToWorkList(I);
11433 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011434 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011435 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011436 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011437 }
11438 }
11439
Chris Lattnerec9c3582007-03-03 02:04:50 +000011440 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011441
11442 // Do an explicit clear, this shrinks the map if needed.
11443 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011444 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011445}
11446
Chris Lattnerec9c3582007-03-03 02:04:50 +000011447
11448bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011449 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11450
Chris Lattnerec9c3582007-03-03 02:04:50 +000011451 bool EverMadeChange = false;
11452
11453 // Iterate while there is work to do.
11454 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011455 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011456 EverMadeChange = true;
11457 return EverMadeChange;
11458}
11459
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011460FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011461 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011462}
Brian Gaeked0fde302003-11-11 22:41:34 +000011463