blob: e0e3f49be1882ae6ac46a5e81b9a93b8fb4e7e00 [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) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 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) {
Chris Lattner564a7272003-08-13 19:01:45 +00001658 // Now all of the instructions are in the current basic block, go ahead
1659 // and perform the reassociation.
1660 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1661
1662 // First move the selected RHS to the LHS of the root...
1663 Root.setOperand(0, LHSI->getOperand(1));
1664
1665 // Make what used to be the LHS of the root be the user of the root...
1666 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001667 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001668 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1669 return 0;
1670 }
Chris Lattner65725312004-04-16 18:08:07 +00001671 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001672 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001673 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001674 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001675 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001676
1677 // Now propagate the ExtraOperand down the chain of instructions until we
1678 // get to LHSI.
1679 while (TmpLHSI != LHSI) {
1680 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001681 // Move the instruction to immediately before the chain we are
1682 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001683 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001684 ARI = NextLHSI;
1685
Chris Lattner564a7272003-08-13 19:01:45 +00001686 Value *NextOp = NextLHSI->getOperand(1);
1687 NextLHSI->setOperand(1, ExtraOperand);
1688 TmpLHSI = NextLHSI;
1689 ExtraOperand = NextOp;
1690 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001691
Chris Lattner564a7272003-08-13 19:01:45 +00001692 // Now that the instructions are reassociated, have the functor perform
1693 // the transformation...
1694 return F.apply(Root);
1695 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001696
Chris Lattner564a7272003-08-13 19:01:45 +00001697 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1698 }
1699 return 0;
1700}
1701
Dan Gohman844731a2008-05-13 00:00:25 +00001702namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001703
Nick Lewycky02d639f2008-05-23 04:34:58 +00001704// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001705struct AddRHS {
1706 Value *RHS;
1707 AddRHS(Value *rhs) : RHS(rhs) {}
1708 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1709 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001710 return BinaryOperator::CreateShl(Add.getOperand(0),
1711 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001712 }
1713};
1714
1715// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1716// iff C1&C2 == 0
1717struct AddMaskingAnd {
1718 Constant *C2;
1719 AddMaskingAnd(Constant *c) : C2(c) {}
1720 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001721 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001722 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001723 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001724 }
1725 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001726 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001727 }
1728};
1729
Dan Gohman844731a2008-05-13 00:00:25 +00001730}
1731
Chris Lattner6e7ba452005-01-01 16:22:27 +00001732static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001733 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001734 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001735 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001736 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001737
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001738 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001739 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001740 }
1741
Chris Lattner2eefe512004-04-09 19:05:30 +00001742 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001743 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1744 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001745
Chris Lattner2eefe512004-04-09 19:05:30 +00001746 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1747 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001748 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1749 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001750 }
1751
1752 Value *Op0 = SO, *Op1 = ConstOperand;
1753 if (!ConstIsRHS)
1754 std::swap(Op0, Op1);
1755 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001756 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001757 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001758 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001759 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001760 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001761 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001762 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001763 abort();
1764 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001765 return IC->InsertNewInstBefore(New, I);
1766}
1767
1768// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1769// constant as the other operand, try to fold the binary operator into the
1770// select arguments. This also works for Cast instructions, which obviously do
1771// not have a second operand.
1772static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1773 InstCombiner *IC) {
1774 // Don't modify shared select instructions
1775 if (!SI->hasOneUse()) return 0;
1776 Value *TV = SI->getOperand(1);
1777 Value *FV = SI->getOperand(2);
1778
1779 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001780 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001781 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001782
Chris Lattner6e7ba452005-01-01 16:22:27 +00001783 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1784 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1785
Gabor Greif051a9502008-04-06 20:25:17 +00001786 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1787 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001788 }
1789 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001790}
1791
Chris Lattner4e998b22004-09-29 05:07:12 +00001792
1793/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1794/// node as operand #0, see if we can fold the instruction into the PHI (which
1795/// is only possible if all operands to the PHI are constants).
1796Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1797 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001798 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001799 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001800
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001801 // Check to see if all of the operands of the PHI are constants. If there is
1802 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001803 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001804 BasicBlock *NonConstBB = 0;
1805 for (unsigned i = 0; i != NumPHIValues; ++i)
1806 if (!isa<Constant>(PN->getIncomingValue(i))) {
1807 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001808 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001809 NonConstBB = PN->getIncomingBlock(i);
1810
1811 // If the incoming non-constant value is in I's block, we have an infinite
1812 // loop.
1813 if (NonConstBB == I.getParent())
1814 return 0;
1815 }
1816
1817 // If there is exactly one non-constant value, we can insert a copy of the
1818 // operation in that block. However, if this is a critical edge, we would be
1819 // inserting the computation one some other paths (e.g. inside a loop). Only
1820 // do this if the pred block is unconditionally branching into the phi block.
1821 if (NonConstBB) {
1822 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1823 if (!BI || !BI->isUnconditional()) return 0;
1824 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001825
1826 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001827 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001828 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001829 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001830 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001831
1832 // Next, add all of the operands to the PHI.
1833 if (I.getNumOperands() == 2) {
1834 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001835 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001836 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001837 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001838 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1839 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1840 else
1841 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001842 } else {
1843 assert(PN->getIncomingBlock(i) == NonConstBB);
1844 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001845 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001846 PN->getIncomingValue(i), C, "phitmp",
1847 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001848 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001849 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001850 CI->getPredicate(),
1851 PN->getIncomingValue(i), C, "phitmp",
1852 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001853 else
1854 assert(0 && "Unknown binop!");
1855
Chris Lattnerdbab3862007-03-02 21:28:56 +00001856 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001857 }
1858 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001859 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001860 } else {
1861 CastInst *CI = cast<CastInst>(&I);
1862 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001863 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001864 Value *InV;
1865 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001866 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001867 } else {
1868 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001869 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001870 I.getType(), "phitmp",
1871 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001872 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001873 }
1874 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001875 }
1876 }
1877 return ReplaceInstUsesWith(I, NewPN);
1878}
1879
Chris Lattner2454a2e2008-01-29 06:52:45 +00001880
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001881/// WillNotOverflowSignedAdd - Return true if we can prove that:
1882/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1883/// This basically requires proving that the add in the original type would not
1884/// overflow to change the sign bit or have a carry out.
1885bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1886 // There are different heuristics we can use for this. Here are some simple
1887 // ones.
1888
1889 // Add has the property that adding any two 2's complement numbers can only
1890 // have one carry bit which can change a sign. As such, if LHS and RHS each
1891 // have at least two sign bits, we know that the addition of the two values will
1892 // sign extend fine.
1893 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1894 return true;
1895
1896
1897 // If one of the operands only has one non-zero bit, and if the other operand
1898 // has a known-zero bit in a more significant place than it (not including the
1899 // sign bit) the ripple may go up to and fill the zero, but won't change the
1900 // sign. For example, (X & ~4) + 1.
1901
1902 // TODO: Implement.
1903
1904 return false;
1905}
1906
Chris Lattner2454a2e2008-01-29 06:52:45 +00001907
Chris Lattner7e708292002-06-25 16:13:24 +00001908Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001909 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001910 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001911
Chris Lattner66331a42004-04-10 22:01:55 +00001912 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001913 // X + undef -> undef
1914 if (isa<UndefValue>(RHS))
1915 return ReplaceInstUsesWith(I, RHS);
1916
Chris Lattner66331a42004-04-10 22:01:55 +00001917 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001918 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001919 if (RHSC->isNullValue())
1920 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001921 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001922 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1923 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001924 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001925 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001926
Chris Lattner66331a42004-04-10 22:01:55 +00001927 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001928 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001929 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001930 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001931 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001932 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001933
1934 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1935 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001936 if (!isa<VectorType>(I.getType())) {
1937 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1938 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1939 KnownZero, KnownOne))
1940 return &I;
1941 }
Chris Lattner66331a42004-04-10 22:01:55 +00001942 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001943
1944 if (isa<PHINode>(LHS))
1945 if (Instruction *NV = FoldOpIntoPhi(I))
1946 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001947
Chris Lattner4f637d42006-01-06 17:59:59 +00001948 ConstantInt *XorRHS = 0;
1949 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001950 if (isa<ConstantInt>(RHSC) &&
1951 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001952 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001953 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001954
Zhou Sheng4351c642007-04-02 08:20:41 +00001955 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001956 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1957 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001958 do {
1959 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001960 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1961 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001962 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1963 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001964 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001965 if (!MaskedValueIsZero(XorLHS,
1966 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001967 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001968 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001969 }
1970 }
1971 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001972 C0080Val = APIntOps::lshr(C0080Val, Size);
1973 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1974 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001975
Reid Spencer35c38852007-03-28 01:36:16 +00001976 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001977 // with funny bit widths then this switch statement should be removed. It
1978 // is just here to get the size of the "middle" type back up to something
1979 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001980 const Type *MiddleType = 0;
1981 switch (Size) {
1982 default: break;
1983 case 32: MiddleType = Type::Int32Ty; break;
1984 case 16: MiddleType = Type::Int16Ty; break;
1985 case 8: MiddleType = Type::Int8Ty; break;
1986 }
1987 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001988 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001989 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001990 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001991 }
1992 }
Chris Lattner66331a42004-04-10 22:01:55 +00001993 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001994
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001995 if (I.getType() == Type::Int1Ty)
1996 return BinaryOperator::CreateXor(LHS, RHS);
1997
Nick Lewycky7d26bd82008-05-23 04:39:38 +00001998 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001999 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002000 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002001
2002 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2003 if (RHSI->getOpcode() == Instruction::Sub)
2004 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2005 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2006 }
2007 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2008 if (LHSI->getOpcode() == Instruction::Sub)
2009 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2010 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2011 }
Robert Bocchino71698282004-07-27 21:02:21 +00002012 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002013
Chris Lattner5c4afb92002-05-08 22:46:53 +00002014 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002015 // -A + -B --> -(A + B)
2016 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002017 if (LHS->getType()->isIntOrIntVector()) {
2018 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002019 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002020 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002021 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002022 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002023 }
2024
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002025 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002026 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002027
2028 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002029 if (!isa<Constant>(RHS))
2030 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002031 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002032
Misha Brukmanfd939082005-04-21 23:48:37 +00002033
Chris Lattner50af16a2004-11-13 19:50:12 +00002034 ConstantInt *C2;
2035 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2036 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002037 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002038
2039 // X*C1 + X*C2 --> X * (C1+C2)
2040 ConstantInt *C1;
2041 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002043 }
2044
2045 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002046 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002047 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002048
Chris Lattnere617c9e2007-01-05 02:17:46 +00002049 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002050 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2051 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002052
Chris Lattnerad3448c2003-02-18 19:57:07 +00002053
Chris Lattner564a7272003-08-13 19:01:45 +00002054 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002055 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002056 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2057 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002058
2059 // A+B --> A|B iff A and B have no bits set in common.
2060 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2061 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2062 APInt LHSKnownOne(IT->getBitWidth(), 0);
2063 APInt LHSKnownZero(IT->getBitWidth(), 0);
2064 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2065 if (LHSKnownZero != 0) {
2066 APInt RHSKnownOne(IT->getBitWidth(), 0);
2067 APInt RHSKnownZero(IT->getBitWidth(), 0);
2068 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2069
2070 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002071 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002072 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002073 }
2074 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002075
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002076 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002077 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002078 Value *W, *X, *Y, *Z;
2079 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2080 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2081 if (W != Y) {
2082 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002083 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002084 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002085 std::swap(W, X);
2086 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002087 std::swap(Y, Z);
2088 std::swap(W, X);
2089 }
2090 }
2091
2092 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002093 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002094 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002095 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002096 }
2097 }
2098 }
2099
Chris Lattner6b032052003-10-02 15:11:26 +00002100 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002101 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002102 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002103 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002104
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002105 // (X & FF00) + xx00 -> (X+xx00) & FF00
2106 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002107 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002108 if (Anded == CRHS) {
2109 // See if all bits from the first bit set in the Add RHS up are included
2110 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002111 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002112
2113 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002114 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002115
2116 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002117 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002118
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002119 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2120 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002121 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002122 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002123 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002124 }
2125 }
2126 }
2127
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002128 // Try to fold constant add into select arguments.
2129 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002130 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002131 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002132 }
2133
Reid Spencer1628cec2006-10-26 06:15:43 +00002134 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002135 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002136 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002137 CastInst *CI = dyn_cast<CastInst>(LHS);
2138 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002139 if (!CI) {
2140 CI = dyn_cast<CastInst>(RHS);
2141 Other = LHS;
2142 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002143 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002144 (CI->getType()->getPrimitiveSizeInBits() ==
2145 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002146 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002147 unsigned AS =
2148 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002149 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2150 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002151 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002152 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002153 }
2154 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002155
Chris Lattner42790482007-12-20 01:56:58 +00002156 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002157 {
2158 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2159 Value *Other = RHS;
2160 if (!SI) {
2161 SI = dyn_cast<SelectInst>(RHS);
2162 Other = LHS;
2163 }
Chris Lattner42790482007-12-20 01:56:58 +00002164 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002165 Value *TV = SI->getTrueValue();
2166 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002167 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002168
2169 // Can we fold the add into the argument of the select?
2170 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002171 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2172 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002173 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002174 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2175 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002176 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002177 }
2178 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002179
2180 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2181 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2182 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2183 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002184
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002185 // Check for (add (sext x), y), see if we can merge this into an
2186 // integer add followed by a sext.
2187 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2188 // (add (sext x), cst) --> (sext (add x, cst'))
2189 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2190 Constant *CI =
2191 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2192 if (LHSConv->hasOneUse() &&
2193 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2194 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2195 // Insert the new, smaller add.
2196 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2197 CI, "addconv");
2198 InsertNewInstBefore(NewAdd, I);
2199 return new SExtInst(NewAdd, I.getType());
2200 }
2201 }
2202
2203 // (add (sext x), (sext y)) --> (sext (add int x, y))
2204 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2205 // Only do this if x/y have the same type, if at last one of them has a
2206 // single use (so we don't increase the number of sexts), and if the
2207 // integer add will not overflow.
2208 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2209 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2210 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2211 RHSConv->getOperand(0))) {
2212 // Insert the new integer add.
2213 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2214 RHSConv->getOperand(0),
2215 "addconv");
2216 InsertNewInstBefore(NewAdd, I);
2217 return new SExtInst(NewAdd, I.getType());
2218 }
2219 }
2220 }
2221
2222 // Check for (add double (sitofp x), y), see if we can merge this into an
2223 // integer add followed by a promotion.
2224 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2225 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2226 // ... if the constant fits in the integer value. This is useful for things
2227 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2228 // requires a constant pool load, and generally allows the add to be better
2229 // instcombined.
2230 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2231 Constant *CI =
2232 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2233 if (LHSConv->hasOneUse() &&
2234 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2235 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2236 // Insert the new integer add.
2237 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2238 CI, "addconv");
2239 InsertNewInstBefore(NewAdd, I);
2240 return new SIToFPInst(NewAdd, I.getType());
2241 }
2242 }
2243
2244 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2245 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2246 // Only do this if x/y have the same type, if at last one of them has a
2247 // single use (so we don't increase the number of int->fp conversions),
2248 // and if the integer add will not overflow.
2249 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2250 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2251 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2252 RHSConv->getOperand(0))) {
2253 // Insert the new integer add.
2254 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2255 RHSConv->getOperand(0),
2256 "addconv");
2257 InsertNewInstBefore(NewAdd, I);
2258 return new SIToFPInst(NewAdd, I.getType());
2259 }
2260 }
2261 }
2262
Chris Lattner7e708292002-06-25 16:13:24 +00002263 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002264}
2265
Chris Lattner7e708292002-06-25 16:13:24 +00002266Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002268
Chris Lattner233f7dc2002-08-12 21:17:25 +00002269 if (Op0 == Op1) // sub X, X -> 0
2270 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002271
Chris Lattner233f7dc2002-08-12 21:17:25 +00002272 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002273 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002274 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002275
Chris Lattnere87597f2004-10-16 18:11:37 +00002276 if (isa<UndefValue>(Op0))
2277 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2278 if (isa<UndefValue>(Op1))
2279 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2280
Chris Lattnerd65460f2003-11-05 01:06:05 +00002281 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2282 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002283 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002284 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002285
Chris Lattnerd65460f2003-11-05 01:06:05 +00002286 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002287 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002288 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002289 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002290
Chris Lattner76b7a062007-01-15 07:02:54 +00002291 // -(X >>u 31) -> (X >>s 31)
2292 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002293 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002294 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002295 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002296 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002297 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002298 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002299 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002300 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002301 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002302 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002303 }
2304 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002305 }
2306 else if (SI->getOpcode() == Instruction::AShr) {
2307 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2308 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002309 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002310 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002311 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002312 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002313 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002314 }
2315 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002316 }
2317 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002318 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002319
2320 // Try to fold constant sub into select arguments.
2321 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002322 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002323 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002324
2325 if (isa<PHINode>(Op0))
2326 if (Instruction *NV = FoldOpIntoPhi(I))
2327 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002328 }
2329
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002330 if (I.getType() == Type::Int1Ty)
2331 return BinaryOperator::CreateXor(Op0, Op1);
2332
Chris Lattner43d84d62005-04-07 16:15:25 +00002333 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2334 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002335 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002336 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002337 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002338 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002339 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002340 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2341 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2342 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002343 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002344 Op1I->getOperand(0));
2345 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002346 }
2347
Chris Lattnerfd059242003-10-15 16:48:29 +00002348 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002349 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2350 // is not used by anyone else...
2351 //
Chris Lattner0517e722004-02-02 20:09:56 +00002352 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002353 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002354 // Swap the two operands of the subexpr...
2355 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2356 Op1I->setOperand(0, IIOp1);
2357 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002358
Chris Lattnera2881962003-02-18 19:28:33 +00002359 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002360 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002361 }
2362
2363 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2364 //
2365 if (Op1I->getOpcode() == Instruction::And &&
2366 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2367 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2368
Chris Lattnerf523d062004-06-09 05:08:07 +00002369 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002370 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2371 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002372 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002373
Reid Spencerac5209e2006-10-16 23:08:08 +00002374 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002375 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002376 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002377 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002378 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002379 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002380 ConstantExpr::getNeg(DivRHS));
2381
Chris Lattnerad3448c2003-02-18 19:57:07 +00002382 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002383 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002384 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002385 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002386 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002387 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002388
2389 // X - ((X / Y) * Y) --> X % Y
2390 if (Op1I->getOpcode() == Instruction::Mul)
2391 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2392 if (Op0 == I->getOperand(0) &&
2393 Op1I->getOperand(1) == I->getOperand(1)) {
2394 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002395 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002396 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002397 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002398 }
Chris Lattner40371712002-05-09 01:29:19 +00002399 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002400 }
Chris Lattnera2881962003-02-18 19:28:33 +00002401
Chris Lattner9919e3d2006-12-02 00:13:08 +00002402 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002403 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002404 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002405 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2406 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2407 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2408 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002409 } else if (Op0I->getOpcode() == Instruction::Sub) {
2410 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002411 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002412 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002413 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002414
Chris Lattner50af16a2004-11-13 19:50:12 +00002415 ConstantInt *C1;
2416 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002417 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002418 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002419
Chris Lattner50af16a2004-11-13 19:50:12 +00002420 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2421 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002422 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002423 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002424 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002425}
2426
Chris Lattnera0141b92007-07-15 20:42:37 +00002427/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2428/// comparison only checks the sign bit. If it only checks the sign bit, set
2429/// TrueIfSigned if the result of the comparison is true when the input value is
2430/// signed.
2431static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2432 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002433 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002434 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2435 TrueIfSigned = true;
2436 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002437 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2438 TrueIfSigned = true;
2439 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002440 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2441 TrueIfSigned = false;
2442 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002443 case ICmpInst::ICMP_UGT:
2444 // True if LHS u> RHS and RHS == high-bit-mask - 1
2445 TrueIfSigned = true;
2446 return RHS->getValue() ==
2447 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2448 case ICmpInst::ICMP_UGE:
2449 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2450 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002451 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002452 default:
2453 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002454 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002455}
2456
Chris Lattner7e708292002-06-25 16:13:24 +00002457Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002458 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002459 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002460
Chris Lattnere87597f2004-10-16 18:11:37 +00002461 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2462 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463
Chris Lattner233f7dc2002-08-12 21:17:25 +00002464 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002465 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2466 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002467
2468 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002469 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002470 if (SI->getOpcode() == Instruction::Shl)
2471 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002473 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002474
Zhou Sheng843f07672007-04-19 05:39:12 +00002475 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002476 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2477 if (CI->equalsInt(1)) // X * 1 == X
2478 return ReplaceInstUsesWith(I, Op0);
2479 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002480 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002481
Zhou Sheng97b52c22007-03-29 01:57:21 +00002482 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002483 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002484 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002485 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002486 }
Robert Bocchino71698282004-07-27 21:02:21 +00002487 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002488 if (Op1F->isNullValue())
2489 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002490
Chris Lattnera2881962003-02-18 19:28:33 +00002491 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2492 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002493 // We need a better interface for long double here.
2494 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2495 if (Op1F->isExactlyValue(1.0))
2496 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002497 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002498
2499 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2500 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002501 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002502 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002503 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002504 Op1, "tmp");
2505 InsertNewInstBefore(Add, I);
2506 Value *C1C2 = ConstantExpr::getMul(Op1,
2507 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002508 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002509
2510 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002511
2512 // Try to fold constant mul into select arguments.
2513 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002514 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002515 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002516
2517 if (isa<PHINode>(Op0))
2518 if (Instruction *NV = FoldOpIntoPhi(I))
2519 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002520 }
2521
Chris Lattnera4f445b2003-03-10 23:23:04 +00002522 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2523 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002525
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002526 if (I.getType() == Type::Int1Ty)
2527 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2528
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002529 // If one of the operands of the multiply is a cast from a boolean value, then
2530 // we know the bool is either zero or one, so this is a 'masking' multiply.
2531 // See if we can simplify things based on how the boolean was originally
2532 // formed.
2533 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002534 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002535 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002536 BoolCast = CI;
2537 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002538 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002539 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002540 BoolCast = CI;
2541 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002542 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002543 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2544 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002545 bool TIS = false;
2546
Reid Spencere4d87aa2006-12-23 06:05:41 +00002547 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002548 // multiply into a shift/and combination.
2549 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002550 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2551 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002552 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002553 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002554 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002555 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002556 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002557 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002558 BoolCast->getOperand(0)->getName()+
2559 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002560
2561 // If the multiply type is not the same as the source type, sign extend
2562 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002563 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002564 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2565 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002566 Instruction::CastOps opcode =
2567 (SrcBits == DstBits ? Instruction::BitCast :
2568 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2569 V = InsertCastBefore(opcode, V, I.getType(), I);
2570 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002571
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002572 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002573 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002574 }
2575 }
2576 }
2577
Chris Lattner7e708292002-06-25 16:13:24 +00002578 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002579}
2580
Reid Spencer1628cec2006-10-26 06:15:43 +00002581/// This function implements the transforms on div instructions that work
2582/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2583/// used by the visitors to those instructions.
2584/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002585Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002586 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002587
Chris Lattner50b2ca42008-02-19 06:12:18 +00002588 // undef / X -> 0 for integer.
2589 // undef / X -> undef for FP (the undef could be a snan).
2590 if (isa<UndefValue>(Op0)) {
2591 if (Op0->getType()->isFPOrFPVector())
2592 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002593 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002594 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002595
2596 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002597 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002598 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002599
Chris Lattner25feae52008-01-28 00:58:18 +00002600 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2601 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002602 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002603 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2604 // the same basic block, then we replace the select with Y, and the
2605 // condition of the select with false (if the cond value is in the same BB).
2606 // If the select has uses other than the div, this allows them to be
2607 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2608 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002609 if (ST->isNullValue()) {
2610 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2611 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002612 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002613 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2614 I.setOperand(1, SI->getOperand(2));
2615 else
2616 UpdateValueUsesWith(SI, SI->getOperand(2));
2617 return &I;
2618 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002619
Chris Lattner25feae52008-01-28 00:58:18 +00002620 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2621 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002622 if (ST->isNullValue()) {
2623 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2624 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002625 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002626 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2627 I.setOperand(1, SI->getOperand(1));
2628 else
2629 UpdateValueUsesWith(SI, SI->getOperand(1));
2630 return &I;
2631 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002632 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002633
Reid Spencer1628cec2006-10-26 06:15:43 +00002634 return 0;
2635}
Misha Brukmanfd939082005-04-21 23:48:37 +00002636
Reid Spencer1628cec2006-10-26 06:15:43 +00002637/// This function implements the transforms common to both integer division
2638/// instructions (udiv and sdiv). It is called by the visitors to those integer
2639/// division instructions.
2640/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002641Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2643
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002644 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002645 if (Op0 == Op1) {
2646 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2647 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2648 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2649 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2650 }
2651
2652 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2653 return ReplaceInstUsesWith(I, CI);
2654 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002655
Reid Spencer1628cec2006-10-26 06:15:43 +00002656 if (Instruction *Common = commonDivTransforms(I))
2657 return Common;
2658
2659 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2660 // div X, 1 == X
2661 if (RHS->equalsInt(1))
2662 return ReplaceInstUsesWith(I, Op0);
2663
2664 // (X / C1) / C2 -> X / (C1*C2)
2665 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2666 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2667 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002668 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2669 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2670 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002671 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002672 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002673 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002674
Reid Spencerbca0e382007-03-23 20:05:17 +00002675 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002676 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2677 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2678 return R;
2679 if (isa<PHINode>(Op0))
2680 if (Instruction *NV = FoldOpIntoPhi(I))
2681 return NV;
2682 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002683 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002684
Chris Lattnera2881962003-02-18 19:28:33 +00002685 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002686 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002687 if (LHS->equalsInt(0))
2688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2689
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002690 // It can't be division by zero, hence it must be division by one.
2691 if (I.getType() == Type::Int1Ty)
2692 return ReplaceInstUsesWith(I, Op0);
2693
Reid Spencer1628cec2006-10-26 06:15:43 +00002694 return 0;
2695}
2696
2697Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2698 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2699
2700 // Handle the integer div common cases
2701 if (Instruction *Common = commonIDivTransforms(I))
2702 return Common;
2703
2704 // X udiv C^2 -> X >> C
2705 // Check to see if this is an unsigned division with an exact power of 2,
2706 // if so, convert to a right shift.
2707 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002708 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002709 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002710 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002711 }
2712
2713 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002714 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002715 if (RHSI->getOpcode() == Instruction::Shl &&
2716 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002717 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002718 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002719 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002720 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002721 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002722 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002723 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002724 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002725 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002726 }
2727 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002728 }
2729
Reid Spencer1628cec2006-10-26 06:15:43 +00002730 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2731 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002732 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002733 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002734 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002735 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002736 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002737 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002738 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002739 // Construct the "on true" case of the select
2740 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002741 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002742 Op0, TC, SI->getName()+".t");
2743 TSI = InsertNewInstBefore(TSI, I);
2744
2745 // Construct the "on false" case of the select
2746 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002747 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002748 Op0, FC, SI->getName()+".f");
2749 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002750
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002751 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002752 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002753 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002754 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002755 return 0;
2756}
2757
Reid Spencer1628cec2006-10-26 06:15:43 +00002758Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2759 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2760
2761 // Handle the integer div common cases
2762 if (Instruction *Common = commonIDivTransforms(I))
2763 return Common;
2764
2765 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2766 // sdiv X, -1 == -X
2767 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002768 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002769
2770 // -X/C -> X/-C
2771 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002772 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002773 }
2774
2775 // If the sign bits of both operands are zero (i.e. we can prove they are
2776 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002777 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002778 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002779 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002780 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002781 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002782 }
2783 }
2784
2785 return 0;
2786}
2787
2788Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2789 return commonDivTransforms(I);
2790}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002791
Reid Spencer0a783f72006-11-02 01:53:59 +00002792/// This function implements the transforms on rem instructions that work
2793/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2794/// is used by the visitors to those instructions.
2795/// @brief Transforms common to all three rem instructions
2796Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002797 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002798
Chris Lattner50b2ca42008-02-19 06:12:18 +00002799 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002800 if (Constant *LHS = dyn_cast<Constant>(Op0))
2801 if (LHS->isNullValue())
2802 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2803
Chris Lattner50b2ca42008-02-19 06:12:18 +00002804 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2805 if (I.getType()->isFPOrFPVector())
2806 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002807 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002808 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002809 if (isa<UndefValue>(Op1))
2810 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002811
2812 // Handle cases involving: rem X, (select Cond, Y, Z)
2813 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2814 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2815 // the same basic block, then we replace the select with Y, and the
2816 // condition of the select with false (if the cond value is in the same
2817 // BB). If the select has uses other than the div, this allows them to be
2818 // simplified also.
2819 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2820 if (ST->isNullValue()) {
2821 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2822 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002823 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002824 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2825 I.setOperand(1, SI->getOperand(2));
2826 else
2827 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002828 return &I;
2829 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002830 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2831 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2832 if (ST->isNullValue()) {
2833 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2834 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002835 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002836 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2837 I.setOperand(1, SI->getOperand(1));
2838 else
2839 UpdateValueUsesWith(SI, SI->getOperand(1));
2840 return &I;
2841 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002842 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002843
Reid Spencer0a783f72006-11-02 01:53:59 +00002844 return 0;
2845}
2846
2847/// This function implements the transforms common to both integer remainder
2848/// instructions (urem and srem). It is called by the visitors to those integer
2849/// remainder instructions.
2850/// @brief Common integer remainder transforms
2851Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2853
2854 if (Instruction *common = commonRemTransforms(I))
2855 return common;
2856
Chris Lattner857e8cd2004-12-12 21:48:58 +00002857 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002858 // X % 0 == undef, we don't need to preserve faults!
2859 if (RHS->equalsInt(0))
2860 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2861
Chris Lattnera2881962003-02-18 19:28:33 +00002862 if (RHS->equalsInt(1)) // X % 1 == 0
2863 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2864
Chris Lattner97943922006-02-28 05:49:21 +00002865 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2866 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2867 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2868 return R;
2869 } else if (isa<PHINode>(Op0I)) {
2870 if (Instruction *NV = FoldOpIntoPhi(I))
2871 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002872 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002873
2874 // See if we can fold away this rem instruction.
2875 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2876 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2877 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2878 KnownZero, KnownOne))
2879 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002880 }
Chris Lattnera2881962003-02-18 19:28:33 +00002881 }
2882
Reid Spencer0a783f72006-11-02 01:53:59 +00002883 return 0;
2884}
2885
2886Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2887 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2888
2889 if (Instruction *common = commonIRemTransforms(I))
2890 return common;
2891
2892 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2893 // X urem C^2 -> X and C
2894 // Check to see if this is an unsigned remainder with an exact power of 2,
2895 // if so, convert to a bitwise and.
2896 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002897 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002898 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002899 }
2900
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002901 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002902 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2903 if (RHSI->getOpcode() == Instruction::Shl &&
2904 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002905 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002906 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002907 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002908 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002909 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002910 }
2911 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002912 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002913
Reid Spencer0a783f72006-11-02 01:53:59 +00002914 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2915 // where C1&C2 are powers of two.
2916 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2917 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2918 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2919 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002920 if ((STO->getValue().isPowerOf2()) &&
2921 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002922 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002923 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002924 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002925 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002926 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002927 }
2928 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002929 }
2930
Chris Lattner3f5b8772002-05-06 16:14:14 +00002931 return 0;
2932}
2933
Reid Spencer0a783f72006-11-02 01:53:59 +00002934Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2936
Dan Gohmancff55092007-11-05 23:16:33 +00002937 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002938 if (Instruction *common = commonIRemTransforms(I))
2939 return common;
2940
2941 if (Value *RHSNeg = dyn_castNegVal(Op1))
2942 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002943 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002944 // X % -Y -> X % Y
2945 AddUsesToWorkList(I);
2946 I.setOperand(1, RHSNeg);
2947 return &I;
2948 }
2949
Dan Gohmancff55092007-11-05 23:16:33 +00002950 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002951 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002952 if (I.getType()->isInteger()) {
2953 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2954 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2955 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002956 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002957 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002958 }
2959
2960 return 0;
2961}
2962
2963Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002964 return commonRemTransforms(I);
2965}
2966
Chris Lattner8b170942002-08-09 23:47:40 +00002967// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002968static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002969 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002970 if (!isSigned)
2971 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2972 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002973}
2974
2975// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002976static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002977 if (!isSigned)
2978 return C->getValue() == 1; // unsigned
2979
2980 // Calculate 1111111111000000000000
2981 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2982 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002983}
2984
Chris Lattner457dd822004-06-09 07:59:58 +00002985// isOneBitSet - Return true if there is exactly one bit set in the specified
2986// constant.
2987static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002988 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002989}
2990
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002991// isHighOnes - Return true if the constant is of the form 1+0+.
2992// This is the same as lowones(~X).
2993static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002994 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002995}
2996
Reid Spencere4d87aa2006-12-23 06:05:41 +00002997/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002998/// are carefully arranged to allow folding of expressions such as:
2999///
3000/// (A < B) | (A > B) --> (A != B)
3001///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003002/// Note that this is only valid if the first and second predicates have the
3003/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003004///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003005/// Three bits are used to represent the condition, as follows:
3006/// 0 A > B
3007/// 1 A == B
3008/// 2 A < B
3009///
3010/// <=> Value Definition
3011/// 000 0 Always false
3012/// 001 1 A > B
3013/// 010 2 A == B
3014/// 011 3 A >= B
3015/// 100 4 A < B
3016/// 101 5 A != B
3017/// 110 6 A <= B
3018/// 111 7 Always true
3019///
3020static unsigned getICmpCode(const ICmpInst *ICI) {
3021 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003022 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003023 case ICmpInst::ICMP_UGT: return 1; // 001
3024 case ICmpInst::ICMP_SGT: return 1; // 001
3025 case ICmpInst::ICMP_EQ: return 2; // 010
3026 case ICmpInst::ICMP_UGE: return 3; // 011
3027 case ICmpInst::ICMP_SGE: return 3; // 011
3028 case ICmpInst::ICMP_ULT: return 4; // 100
3029 case ICmpInst::ICMP_SLT: return 4; // 100
3030 case ICmpInst::ICMP_NE: return 5; // 101
3031 case ICmpInst::ICMP_ULE: return 6; // 110
3032 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003033 // True -> 7
3034 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003035 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003036 return 0;
3037 }
3038}
3039
Reid Spencere4d87aa2006-12-23 06:05:41 +00003040/// getICmpValue - This is the complement of getICmpCode, which turns an
3041/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003042/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003043/// of predicate to use in new icmp instructions.
3044static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3045 switch (code) {
3046 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003047 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003048 case 1:
3049 if (sign)
3050 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3051 else
3052 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3053 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3054 case 3:
3055 if (sign)
3056 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3057 else
3058 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3059 case 4:
3060 if (sign)
3061 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3062 else
3063 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3064 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3065 case 6:
3066 if (sign)
3067 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3068 else
3069 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003070 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003071 }
3072}
3073
Reid Spencere4d87aa2006-12-23 06:05:41 +00003074static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3075 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3076 (ICmpInst::isSignedPredicate(p1) &&
3077 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3078 (ICmpInst::isSignedPredicate(p2) &&
3079 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3080}
3081
3082namespace {
3083// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3084struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003085 InstCombiner &IC;
3086 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003087 ICmpInst::Predicate pred;
3088 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3089 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3090 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003091 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003092 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3093 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003094 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3095 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003096 return false;
3097 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003098 Instruction *apply(Instruction &Log) const {
3099 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3100 if (ICI->getOperand(0) != LHS) {
3101 assert(ICI->getOperand(1) == LHS);
3102 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003103 }
3104
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003105 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003106 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003107 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003108 unsigned Code;
3109 switch (Log.getOpcode()) {
3110 case Instruction::And: Code = LHSCode & RHSCode; break;
3111 case Instruction::Or: Code = LHSCode | RHSCode; break;
3112 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003113 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003114 }
3115
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003116 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3117 ICmpInst::isSignedPredicate(ICI->getPredicate());
3118
3119 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003120 if (Instruction *I = dyn_cast<Instruction>(RV))
3121 return I;
3122 // Otherwise, it's a constant boolean value...
3123 return IC.ReplaceInstUsesWith(Log, RV);
3124 }
3125};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003126} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003127
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003128// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3129// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003130// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003131Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003132 ConstantInt *OpRHS,
3133 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003134 BinaryOperator &TheAnd) {
3135 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003136 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003137 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003138 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003139
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003140 switch (Op->getOpcode()) {
3141 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003142 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003143 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003144 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003145 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003146 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003147 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003148 }
3149 break;
3150 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003151 if (Together == AndRHS) // (X | C) & C --> C
3152 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003153
Chris Lattner6e7ba452005-01-01 16:22:27 +00003154 if (Op->hasOneUse() && Together != OpRHS) {
3155 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003156 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003157 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003158 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003159 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003160 }
3161 break;
3162 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003163 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003164 // Adding a one to a single bit bit-field should be turned into an XOR
3165 // of the bit. First thing to check is to see if this AND is with a
3166 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003167 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003168
3169 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003170 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003171 // Ok, at this point, we know that we are masking the result of the
3172 // ADD down to exactly one bit. If the constant we are adding has
3173 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003174 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003175
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003176 // Check to see if any bits below the one bit set in AndRHSV are set.
3177 if ((AddRHS & (AndRHSV-1)) == 0) {
3178 // If not, the only thing that can effect the output of the AND is
3179 // the bit specified by AndRHSV. If that bit is set, the effect of
3180 // the XOR is to toggle the bit. If it is clear, then the ADD has
3181 // no effect.
3182 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3183 TheAnd.setOperand(0, X);
3184 return &TheAnd;
3185 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003186 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003187 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003188 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003189 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003190 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003191 }
3192 }
3193 }
3194 }
3195 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003196
3197 case Instruction::Shl: {
3198 // We know that the AND will not produce any of the bits shifted in, so if
3199 // the anded constant includes them, clear them now!
3200 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003201 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003202 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003203 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3204 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003205
Zhou Sheng290bec52007-03-29 08:15:12 +00003206 if (CI->getValue() == ShlMask) {
3207 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3209 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003210 TheAnd.setOperand(1, CI);
3211 return &TheAnd;
3212 }
3213 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003214 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003215 case Instruction::LShr:
3216 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003217 // We know that the AND will not produce any of the bits shifted in, so if
3218 // the anded constant includes them, clear them now! This only applies to
3219 // unsigned shifts, because a signed shr may bring in set bits!
3220 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003221 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003222 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003223 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3224 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003225
Zhou Sheng290bec52007-03-29 08:15:12 +00003226 if (CI->getValue() == ShrMask) {
3227 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003228 return ReplaceInstUsesWith(TheAnd, Op);
3229 } else if (CI != AndRHS) {
3230 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3231 return &TheAnd;
3232 }
3233 break;
3234 }
3235 case Instruction::AShr:
3236 // Signed shr.
3237 // See if this is shifting in some sign extension, then masking it out
3238 // with an and.
3239 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003240 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003241 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003242 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3243 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003244 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003245 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003246 // Make the argument unsigned.
3247 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003248 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003249 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003250 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003251 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003252 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003253 }
3254 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003255 }
3256 return 0;
3257}
3258
Chris Lattner8b170942002-08-09 23:47:40 +00003259
Chris Lattnera96879a2004-09-29 17:40:11 +00003260/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3261/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003262/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3263/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003264/// insert new instructions.
3265Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003266 bool isSigned, bool Inside,
3267 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003268 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003269 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003270 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003271
Chris Lattnera96879a2004-09-29 17:40:11 +00003272 if (Inside) {
3273 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003274 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003275
Reid Spencere4d87aa2006-12-23 06:05:41 +00003276 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003277 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003278 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003279 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3280 return new ICmpInst(pred, V, Hi);
3281 }
3282
3283 // Emit V-Lo <u Hi-Lo
3284 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003285 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003286 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003287 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3288 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003289 }
3290
3291 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003292 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003293
Reid Spencere4e40032007-03-21 23:19:50 +00003294 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003295 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003296 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003297 ICmpInst::Predicate pred = (isSigned ?
3298 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3299 return new ICmpInst(pred, V, Hi);
3300 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003301
Reid Spencere4e40032007-03-21 23:19:50 +00003302 // Emit V-Lo >u Hi-1-Lo
3303 // Note that Hi has already had one subtracted from it, above.
3304 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003305 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003306 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003307 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3308 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003309}
3310
Chris Lattner7203e152005-09-18 07:22:02 +00003311// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3312// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3313// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3314// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003315static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003316 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003317 uint32_t BitWidth = Val->getType()->getBitWidth();
3318 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003319
3320 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003321 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003322 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003323 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003324 return true;
3325}
3326
Chris Lattner7203e152005-09-18 07:22:02 +00003327/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3328/// where isSub determines whether the operator is a sub. If we can fold one of
3329/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003330///
3331/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3332/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3333/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3334///
3335/// return (A +/- B).
3336///
3337Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003338 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003339 Instruction &I) {
3340 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3341 if (!LHSI || LHSI->getNumOperands() != 2 ||
3342 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3343
3344 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3345
3346 switch (LHSI->getOpcode()) {
3347 default: return 0;
3348 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003349 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003350 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003351 if ((Mask->getValue().countLeadingZeros() +
3352 Mask->getValue().countPopulation()) ==
3353 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003354 break;
3355
3356 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3357 // part, we don't need any explicit masks to take them out of A. If that
3358 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003359 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003360 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003361 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003362 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003363 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003364 break;
3365 }
3366 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003367 return 0;
3368 case Instruction::Or:
3369 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003370 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003371 if ((Mask->getValue().countLeadingZeros() +
3372 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003373 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003374 break;
3375 return 0;
3376 }
3377
3378 Instruction *New;
3379 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003380 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003381 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003382 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003383 return InsertNewInstBefore(New, I);
3384}
3385
Chris Lattner7e708292002-06-25 16:13:24 +00003386Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003387 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003388 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003389
Chris Lattnere87597f2004-10-16 18:11:37 +00003390 if (isa<UndefValue>(Op1)) // X & undef -> 0
3391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3392
Chris Lattner6e7ba452005-01-01 16:22:27 +00003393 // and X, X = X
3394 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003395 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003396
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003397 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003398 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003399 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003400 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3401 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3402 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003403 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003404 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003405 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003406 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003407 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003408 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003409 } else if (isa<ConstantAggregateZero>(Op1)) {
3410 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003411 }
3412 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003413
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003414 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003415 const APInt& AndRHSMask = AndRHS->getValue();
3416 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003417
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003418 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003419 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003420 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003421 Value *Op0LHS = Op0I->getOperand(0);
3422 Value *Op0RHS = Op0I->getOperand(1);
3423 switch (Op0I->getOpcode()) {
3424 case Instruction::Xor:
3425 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003426 // If the mask is only needed on one incoming arm, push it up.
3427 if (Op0I->hasOneUse()) {
3428 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3429 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003430 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003431 Op0RHS->getName()+".masked");
3432 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003433 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003434 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003435 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003436 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003437 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3438 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003439 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003440 Op0LHS->getName()+".masked");
3441 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003442 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003443 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3444 }
3445 }
3446
Chris Lattner6e7ba452005-01-01 16:22:27 +00003447 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003448 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003449 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3450 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3451 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3452 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003453 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003454 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003455 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003456 break;
3457
3458 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003459 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3460 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3461 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3462 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003463 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003464
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003465 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3466 // has 1's for all bits that the subtraction with A might affect.
3467 if (Op0I->hasOneUse()) {
3468 uint32_t BitWidth = AndRHSMask.getBitWidth();
3469 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3470 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3471
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003472 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003473 if (!(A && A->isZero()) && // avoid infinite recursion.
3474 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003475 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3476 InsertNewInstBefore(NewNeg, I);
3477 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3478 }
3479 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003480 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003481
3482 case Instruction::Shl:
3483 case Instruction::LShr:
3484 // (1 << x) & 1 --> zext(x == 0)
3485 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003486 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003487 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3488 Constant::getNullValue(I.getType()));
3489 InsertNewInstBefore(NewICmp, I);
3490 return new ZExtInst(NewICmp, I.getType());
3491 }
3492 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003493 }
3494
Chris Lattner58403262003-07-23 19:25:52 +00003495 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003496 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003497 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003498 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003499 // If this is an integer truncation or change from signed-to-unsigned, and
3500 // if the source is an and/or with immediate, transform it. This
3501 // frequently occurs for bitfield accesses.
3502 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003503 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003504 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003505 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003506 if (CastOp->getOpcode() == Instruction::And) {
3507 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003508 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3509 // This will fold the two constants together, which may allow
3510 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003511 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003512 CastOp->getOperand(0), I.getType(),
3513 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003514 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003515 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003516 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003517 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003518 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003519 } else if (CastOp->getOpcode() == Instruction::Or) {
3520 // Change: and (cast (or X, C1) to T), C2
3521 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003522 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003523 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3524 return ReplaceInstUsesWith(I, AndRHS);
3525 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003526 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003527 }
Chris Lattner06782f82003-07-23 19:36:21 +00003528 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003529
3530 // Try to fold constant and into select arguments.
3531 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003532 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003533 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003534 if (isa<PHINode>(Op0))
3535 if (Instruction *NV = FoldOpIntoPhi(I))
3536 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003537 }
3538
Chris Lattner8d969642003-03-10 23:06:50 +00003539 Value *Op0NotVal = dyn_castNotVal(Op0);
3540 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003541
Chris Lattner5b62aa72004-06-18 06:07:51 +00003542 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3543 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3544
Misha Brukmancb6267b2004-07-30 12:50:08 +00003545 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003546 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003547 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003548 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003549 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003550 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003551 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003552
3553 {
Chris Lattner003b6202007-06-15 05:58:24 +00003554 Value *A = 0, *B = 0, *C = 0, *D = 0;
3555 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003556 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3557 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003558
3559 // (A|B) & ~(A&B) -> A^B
3560 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3561 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003563 }
3564 }
3565
3566 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003567 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3568 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003569
3570 // ~(A&B) & (A|B) -> A^B
3571 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3572 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003573 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003574 }
3575 }
Chris Lattner64daab52006-04-01 08:03:55 +00003576
3577 if (Op0->hasOneUse() &&
3578 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3579 if (A == Op1) { // (A^B)&A -> A&(A^B)
3580 I.swapOperands(); // Simplify below
3581 std::swap(Op0, Op1);
3582 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3583 cast<BinaryOperator>(Op0)->swapOperands();
3584 I.swapOperands(); // Simplify below
3585 std::swap(Op0, Op1);
3586 }
3587 }
3588 if (Op1->hasOneUse() &&
3589 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3590 if (B == Op0) { // B&(A^B) -> B&(B^A)
3591 cast<BinaryOperator>(Op1)->swapOperands();
3592 std::swap(A, B);
3593 }
3594 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003595 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003596 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003597 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003598 }
3599 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003600 }
3601
Nick Lewycky9ee863e2008-07-09 07:29:11 +00003602
3603 { // (icmp ugt/ult A, C) & (icmp B, C) --> (icmp (A|B), C)
3604 // where C is a power of 2
3605 Value *A, *B;
3606 ConstantInt *C1, *C2;
3607 ICmpInst::Predicate LHSCC, RHSCC;
3608 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3609 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3610 if (C1 == C2 && LHSCC == RHSCC && C1->getValue().isPowerOf2() &&
3611 (LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_UGT)) {
3612 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3613 InsertNewInstBefore(NewOr, I);
3614 return new ICmpInst(LHSCC, NewOr, C1);
3615 }
3616 }
3617
Reid Spencere4d87aa2006-12-23 06:05:41 +00003618 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3619 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3620 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003621 return R;
3622
Chris Lattner955f3312004-09-28 21:48:02 +00003623 Value *LHSVal, *RHSVal;
3624 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 ICmpInst::Predicate LHSCC, RHSCC;
3626 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3627 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3628 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3629 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3630 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3631 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3632 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003633 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3634
3635 // Don't try to fold ICMP_SLT + ICMP_ULT.
3636 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3637 ICmpInst::isSignedPredicate(LHSCC) ==
3638 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003639 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003640 ICmpInst::Predicate GT;
3641 if (ICmpInst::isSignedPredicate(LHSCC) ||
3642 (ICmpInst::isEquality(LHSCC) &&
3643 ICmpInst::isSignedPredicate(RHSCC)))
3644 GT = ICmpInst::ICMP_SGT;
3645 else
3646 GT = ICmpInst::ICMP_UGT;
3647
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3649 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003650 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003651 std::swap(LHS, RHS);
3652 std::swap(LHSCst, RHSCst);
3653 std::swap(LHSCC, RHSCC);
3654 }
3655
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003657 // comparing a value against two constants and and'ing the result
3658 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003659 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3660 // (from the FoldICmpLogical check above), that the two constants
3661 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003662 assert(LHSCst != RHSCst && "Compares not folded above?");
3663
3664 switch (LHSCC) {
3665 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003667 switch (RHSCC) {
3668 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3670 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3671 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003672 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3674 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3675 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003676 return ReplaceInstUsesWith(I, LHS);
3677 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678 case ICmpInst::ICMP_NE:
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_ULT:
3682 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3683 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3684 break; // (X != 13 & X u< 15) -> no change
3685 case ICmpInst::ICMP_SLT:
3686 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3687 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3688 break; // (X != 13 & X s< 15) -> no change
3689 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3690 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3691 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003692 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693 case ICmpInst::ICMP_NE:
3694 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003695 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003696 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003697 LHSVal->getName()+".off");
3698 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003699 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3700 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003701 }
3702 break; // (X != 13 & X != 15) -> no change
3703 }
3704 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003705 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003706 switch (RHSCC) {
3707 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003708 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3709 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003710 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003711 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3712 break;
3713 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3714 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003715 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003716 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3717 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003718 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003719 break;
3720 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003721 switch (RHSCC) {
3722 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003723 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3724 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003725 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003726 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3727 break;
3728 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3729 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003730 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003731 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3732 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003733 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003734 break;
3735 case ICmpInst::ICMP_UGT:
3736 switch (RHSCC) {
3737 default: assert(0 && "Unknown integer condition code!");
Eli Friedman5c1f1722008-06-21 23:36:13 +00003738 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003739 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3740 return ReplaceInstUsesWith(I, RHS);
3741 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3742 break;
3743 case ICmpInst::ICMP_NE:
3744 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3745 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3746 break; // (X u> 13 & X != 15) -> no change
3747 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3748 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3749 true, I);
3750 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3751 break;
3752 }
3753 break;
3754 case ICmpInst::ICMP_SGT:
3755 switch (RHSCC) {
3756 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003757 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003758 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3759 return ReplaceInstUsesWith(I, RHS);
3760 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3761 break;
3762 case ICmpInst::ICMP_NE:
3763 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3764 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3765 break; // (X s> 13 & X != 15) -> no change
3766 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3767 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3768 true, I);
3769 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3770 break;
3771 }
3772 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003773 }
3774 }
3775 }
3776
Chris Lattner6fc205f2006-05-05 06:39:07 +00003777 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003778 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3779 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3780 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3781 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003782 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003783 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003784 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3785 I.getType(), TD) &&
3786 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3787 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003788 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003789 Op1C->getOperand(0),
3790 I.getName());
3791 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003792 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003793 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003794 }
Chris Lattnere511b742006-11-14 07:46:50 +00003795
3796 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003797 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3798 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3799 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003800 SI0->getOperand(1) == SI1->getOperand(1) &&
3801 (SI0->hasOneUse() || SI1->hasOneUse())) {
3802 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003803 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003804 SI1->getOperand(0),
3805 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003806 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003807 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003808 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003809 }
3810
Chris Lattner99c65742007-10-24 05:38:08 +00003811 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3812 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3813 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3814 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3815 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3816 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3817 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3818 // If either of the constants are nans, then the whole thing returns
3819 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003820 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003821 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3822 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3823 RHS->getOperand(0));
3824 }
3825 }
3826 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003827
Chris Lattner7e708292002-06-25 16:13:24 +00003828 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003829}
3830
Chris Lattnerafe91a52006-06-15 19:07:26 +00003831/// CollectBSwapParts - Look to see if the specified value defines a single byte
3832/// in the result. If it does, and if the specified byte hasn't been filled in
3833/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003834static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003835 Instruction *I = dyn_cast<Instruction>(V);
3836 if (I == 0) return true;
3837
3838 // If this is an or instruction, it is an inner node of the bswap.
3839 if (I->getOpcode() == Instruction::Or)
3840 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3841 CollectBSwapParts(I->getOperand(1), ByteValues);
3842
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003843 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003844 // If this is a shift by a constant int, and it is "24", then its operand
3845 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003846 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003847 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003848 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003849 8*(ByteValues.size()-1))
3850 return true;
3851
3852 unsigned DestNo;
3853 if (I->getOpcode() == Instruction::Shl) {
3854 // X << 24 defines the top byte with the lowest of the input bytes.
3855 DestNo = ByteValues.size()-1;
3856 } else {
3857 // X >>u 24 defines the low byte with the highest of the input bytes.
3858 DestNo = 0;
3859 }
3860
3861 // If the destination byte value is already defined, the values are or'd
3862 // together, which isn't a bswap (unless it's an or of the same bits).
3863 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3864 return true;
3865 ByteValues[DestNo] = I->getOperand(0);
3866 return false;
3867 }
3868
3869 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3870 // don't have this.
3871 Value *Shift = 0, *ShiftLHS = 0;
3872 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3873 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3874 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3875 return true;
3876 Instruction *SI = cast<Instruction>(Shift);
3877
3878 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003879 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3880 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003881 return true;
3882
3883 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3884 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003885 if (AndAmt->getValue().getActiveBits() > 64)
3886 return true;
3887 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003888 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003889 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003890 break;
3891 // Unknown mask for bswap.
3892 if (DestByte == ByteValues.size()) return true;
3893
Reid Spencerb83eb642006-10-20 07:07:24 +00003894 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003895 unsigned SrcByte;
3896 if (SI->getOpcode() == Instruction::Shl)
3897 SrcByte = DestByte - ShiftBytes;
3898 else
3899 SrcByte = DestByte + ShiftBytes;
3900
3901 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3902 if (SrcByte != ByteValues.size()-DestByte-1)
3903 return true;
3904
3905 // If the destination byte value is already defined, the values are or'd
3906 // together, which isn't a bswap (unless it's an or of the same bits).
3907 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3908 return true;
3909 ByteValues[DestByte] = SI->getOperand(0);
3910 return false;
3911}
3912
3913/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3914/// If so, insert the new bswap intrinsic and return it.
3915Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003916 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3917 if (!ITy || ITy->getBitWidth() % 16)
3918 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003919
3920 /// ByteValues - For each byte of the result, we keep track of which value
3921 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003922 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003923 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003924
3925 // Try to find all the pieces corresponding to the bswap.
3926 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3927 CollectBSwapParts(I.getOperand(1), ByteValues))
3928 return 0;
3929
3930 // Check to see if all of the bytes come from the same value.
3931 Value *V = ByteValues[0];
3932 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3933
3934 // Check to make sure that all of the bytes come from the same value.
3935 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3936 if (ByteValues[i] != V)
3937 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003938 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003939 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003940 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003941 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003942}
3943
3944
Chris Lattner7e708292002-06-25 16:13:24 +00003945Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003946 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003947 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003948
Chris Lattner42593e62007-03-24 23:56:43 +00003949 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003950 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003951
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003952 // or X, X = X
3953 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003954 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003955
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003956 // See if we can simplify any instructions used by the instruction whose sole
3957 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003958 if (!isa<VectorType>(I.getType())) {
3959 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3960 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3961 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3962 KnownZero, KnownOne))
3963 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003964 } else if (isa<ConstantAggregateZero>(Op1)) {
3965 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3966 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3967 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3968 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003969 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003970
3971
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003972
Chris Lattner3f5b8772002-05-06 16:14:14 +00003973 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003974 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003975 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003976 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3977 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003978 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003979 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003980 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003981 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003982 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003983 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003984
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003985 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3986 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003987 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003988 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003989 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003990 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003991 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003992 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003993
3994 // Try to fold constant and into select arguments.
3995 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003996 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003997 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003998 if (isa<PHINode>(Op0))
3999 if (Instruction *NV = FoldOpIntoPhi(I))
4000 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004001 }
4002
Chris Lattner4f637d42006-01-06 17:59:59 +00004003 Value *A = 0, *B = 0;
4004 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004005
4006 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4007 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4008 return ReplaceInstUsesWith(I, Op1);
4009 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4010 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4011 return ReplaceInstUsesWith(I, Op0);
4012
Chris Lattner6423d4c2006-07-10 20:25:24 +00004013 // (A | B) | C and A | (B | C) -> bswap if possible.
4014 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004015 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004016 match(Op1, m_Or(m_Value(), m_Value())) ||
4017 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4018 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004019 if (Instruction *BSwap = MatchBSwap(I))
4020 return BSwap;
4021 }
4022
Chris Lattner6e4c6492005-05-09 04:58:36 +00004023 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4024 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004025 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004026 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004027 InsertNewInstBefore(NOr, I);
4028 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004029 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004030 }
4031
4032 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4033 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004034 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004035 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004036 InsertNewInstBefore(NOr, I);
4037 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004038 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004039 }
4040
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004041 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004042 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004043 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4044 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004045 Value *V1 = 0, *V2 = 0, *V3 = 0;
4046 C1 = dyn_cast<ConstantInt>(C);
4047 C2 = dyn_cast<ConstantInt>(D);
4048 if (C1 && C2) { // (A & C1)|(B & C2)
4049 // If we have: ((V + N) & C1) | (V & C2)
4050 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4051 // replace with V+N.
4052 if (C1->getValue() == ~C2->getValue()) {
4053 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4054 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4055 // Add commutes, try both ways.
4056 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4057 return ReplaceInstUsesWith(I, A);
4058 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4059 return ReplaceInstUsesWith(I, A);
4060 }
4061 // Or commutes, try both ways.
4062 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4063 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4064 // Add commutes, try both ways.
4065 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4066 return ReplaceInstUsesWith(I, B);
4067 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4068 return ReplaceInstUsesWith(I, B);
4069 }
4070 }
Chris Lattner044e5332007-04-08 08:01:49 +00004071 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004072 }
4073
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004074 // Check to see if we have any common things being and'ed. If so, find the
4075 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004076 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4077 if (A == B) // (A & C)|(A & D) == A & (C|D)
4078 V1 = A, V2 = C, V3 = D;
4079 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4080 V1 = A, V2 = B, V3 = C;
4081 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4082 V1 = C, V2 = A, V3 = D;
4083 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4084 V1 = C, V2 = A, V3 = B;
4085
4086 if (V1) {
4087 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004088 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4089 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004090 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004091 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004092 }
Chris Lattnere511b742006-11-14 07:46:50 +00004093
4094 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004095 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4096 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4097 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004098 SI0->getOperand(1) == SI1->getOperand(1) &&
4099 (SI0->hasOneUse() || SI1->hasOneUse())) {
4100 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004101 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004102 SI1->getOperand(0),
4103 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004104 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004105 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004106 }
4107 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004108
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004109 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4110 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004111 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004112 } else {
4113 A = 0;
4114 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004115 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004116 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4117 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004118 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004119
Misha Brukmancb6267b2004-07-30 12:50:08 +00004120 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004121 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004122 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004123 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004124 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004125 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004126 }
Chris Lattnera2881962003-02-18 19:28:33 +00004127
Reid Spencere4d87aa2006-12-23 06:05:41 +00004128 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4129 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4130 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004131 return R;
4132
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004133 Value *LHSVal, *RHSVal;
4134 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004135 ICmpInst::Predicate LHSCC, RHSCC;
4136 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4137 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4138 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4139 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4140 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4141 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4142 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004143 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4144 // We can't fold (ugt x, C) | (sgt x, C2).
4145 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004146 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004147 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004148 bool NeedsSwap;
4149 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004150 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004151 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004152 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004153
4154 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004155 std::swap(LHS, RHS);
4156 std::swap(LHSCst, RHSCst);
4157 std::swap(LHSCC, RHSCC);
4158 }
4159
Reid Spencere4d87aa2006-12-23 06:05:41 +00004160 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004161 // comparing a value against two constants and or'ing the result
4162 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004163 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4164 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004165 // equal.
4166 assert(LHSCst != RHSCst && "Compares not folded above?");
4167
4168 switch (LHSCC) {
4169 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004170 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004171 switch (RHSCC) {
4172 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004173 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004174 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4175 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004176 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004177 LHSVal->getName()+".off");
4178 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004179 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004180 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004181 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004182 break; // (X == 13 | X == 15) -> no change
4183 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4184 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004185 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004186 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4187 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4188 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004189 return ReplaceInstUsesWith(I, RHS);
4190 }
4191 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004192 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004193 switch (RHSCC) {
4194 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004195 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4196 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4197 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004198 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004199 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4200 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4201 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004202 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004203 }
4204 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004205 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004206 switch (RHSCC) {
4207 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004208 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004209 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004210 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004211 // If RHSCst is [us]MAXINT, it is always false. Not handling
4212 // this can cause overflow.
4213 if (RHSCst->isMaxValue(false))
4214 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004215 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4216 false, I);
4217 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4218 break;
4219 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4220 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004221 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004222 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4223 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004224 }
4225 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004226 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004227 switch (RHSCC) {
4228 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004229 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4230 break;
4231 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004232 // If RHSCst is [us]MAXINT, it is always false. Not handling
4233 // this can cause overflow.
4234 if (RHSCst->isMaxValue(true))
4235 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004236 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4237 false, I);
4238 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4239 break;
4240 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4241 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4242 return ReplaceInstUsesWith(I, RHS);
4243 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4244 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004245 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004246 break;
4247 case ICmpInst::ICMP_UGT:
4248 switch (RHSCC) {
4249 default: assert(0 && "Unknown integer condition code!");
4250 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4251 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4252 return ReplaceInstUsesWith(I, LHS);
4253 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4254 break;
4255 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4256 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004257 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004258 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4259 break;
4260 }
4261 break;
4262 case ICmpInst::ICMP_SGT:
4263 switch (RHSCC) {
4264 default: assert(0 && "Unknown integer condition code!");
4265 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4266 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4267 return ReplaceInstUsesWith(I, LHS);
4268 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4269 break;
4270 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4271 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004272 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004273 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4274 break;
4275 }
4276 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004277 }
4278 }
4279 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004280
4281 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004282 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004283 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004284 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004285 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4286 !isa<ICmpInst>(Op1C->getOperand(0))) {
4287 const Type *SrcTy = Op0C->getOperand(0)->getType();
4288 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4289 // Only do this if the casts both really cause code to be
4290 // generated.
4291 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4292 I.getType(), TD) &&
4293 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4294 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004295 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004296 Op1C->getOperand(0),
4297 I.getName());
4298 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004299 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004300 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004301 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004302 }
Chris Lattner99c65742007-10-24 05:38:08 +00004303 }
4304
4305
4306 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4307 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4308 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4309 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004310 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4311 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004312 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4313 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4314 // If either of the constants are nans, then the whole thing returns
4315 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004316 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004317 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4318
4319 // Otherwise, no need to compare the two constants, compare the
4320 // rest.
4321 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4322 RHS->getOperand(0));
4323 }
4324 }
4325 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004326
Chris Lattner7e708292002-06-25 16:13:24 +00004327 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004328}
4329
Dan Gohman844731a2008-05-13 00:00:25 +00004330namespace {
4331
Chris Lattnerc317d392004-02-16 01:20:27 +00004332// XorSelf - Implements: X ^ X --> 0
4333struct XorSelf {
4334 Value *RHS;
4335 XorSelf(Value *rhs) : RHS(rhs) {}
4336 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4337 Instruction *apply(BinaryOperator &Xor) const {
4338 return &Xor;
4339 }
4340};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004341
Dan Gohman844731a2008-05-13 00:00:25 +00004342}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004343
Chris Lattner7e708292002-06-25 16:13:24 +00004344Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004345 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004346 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004347
Evan Chengd34af782008-03-25 20:07:13 +00004348 if (isa<UndefValue>(Op1)) {
4349 if (isa<UndefValue>(Op0))
4350 // Handle undef ^ undef -> 0 special case. This is a common
4351 // idiom (misuse).
4352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004353 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004354 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004355
Chris Lattnerc317d392004-02-16 01:20:27 +00004356 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4357 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004358 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004359 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004360 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004361
4362 // See if we can simplify any instructions used by the instruction whose sole
4363 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004364 if (!isa<VectorType>(I.getType())) {
4365 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4366 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4367 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4368 KnownZero, KnownOne))
4369 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004370 } else if (isa<ConstantAggregateZero>(Op1)) {
4371 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004372 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004373
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004374 // Is this a ~ operation?
4375 if (Value *NotOp = dyn_castNotVal(&I)) {
4376 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4377 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4378 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4379 if (Op0I->getOpcode() == Instruction::And ||
4380 Op0I->getOpcode() == Instruction::Or) {
4381 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4382 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4383 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004384 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004385 Op0I->getOperand(1)->getName()+".not");
4386 InsertNewInstBefore(NotY, I);
4387 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004388 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004389 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004390 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004391 }
4392 }
4393 }
4394 }
4395
4396
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004397 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004398 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4399 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4400 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004401 return new ICmpInst(ICI->getInversePredicate(),
4402 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004403
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004404 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4405 return new FCmpInst(FCI->getInversePredicate(),
4406 FCI->getOperand(0), FCI->getOperand(1));
4407 }
4408
Nick Lewycky517e1f52008-05-31 19:01:33 +00004409 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4410 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4411 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4412 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4413 Instruction::CastOps Opcode = Op0C->getOpcode();
4414 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4415 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4416 Op0C->getDestTy())) {
4417 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4418 CI->getOpcode(), CI->getInversePredicate(),
4419 CI->getOperand(0), CI->getOperand(1)), I);
4420 NewCI->takeName(CI);
4421 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4422 }
4423 }
4424 }
4425 }
4426 }
4427
Reid Spencere4d87aa2006-12-23 06:05:41 +00004428 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004429 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004430 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4431 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004432 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4433 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004434 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004435 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004436 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004437
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004438 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004439 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004440 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004441 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004442 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004443 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004444 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004445 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004446 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004447 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004448 // (X + C) ^ signbit -> (X + C + signbit)
4449 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004450 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004451
Chris Lattner7c4049c2004-01-12 19:35:11 +00004452 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004453 } else if (Op0I->getOpcode() == Instruction::Or) {
4454 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004455 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004456 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4457 // Anything in both C1 and C2 is known to be zero, remove it from
4458 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004459 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004460 NewRHS = ConstantExpr::getAnd(NewRHS,
4461 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004462 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004463 I.setOperand(0, Op0I->getOperand(0));
4464 I.setOperand(1, NewRHS);
4465 return &I;
4466 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004467 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004468 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004469 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004470
4471 // Try to fold constant and into select arguments.
4472 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004473 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004474 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004475 if (isa<PHINode>(Op0))
4476 if (Instruction *NV = FoldOpIntoPhi(I))
4477 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004478 }
4479
Chris Lattner8d969642003-03-10 23:06:50 +00004480 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004481 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004482 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004483
Chris Lattner8d969642003-03-10 23:06:50 +00004484 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004485 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004486 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004487
Chris Lattner318bf792007-03-18 22:51:34 +00004488
4489 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4490 if (Op1I) {
4491 Value *A, *B;
4492 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4493 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004494 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004495 I.swapOperands();
4496 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004497 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004498 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004499 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004500 }
Chris Lattner318bf792007-03-18 22:51:34 +00004501 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4502 if (Op0 == A) // A^(A^B) == B
4503 return ReplaceInstUsesWith(I, B);
4504 else if (Op0 == B) // A^(B^A) == B
4505 return ReplaceInstUsesWith(I, A);
4506 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004507 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004508 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004509 std::swap(A, B);
4510 }
Chris Lattner318bf792007-03-18 22:51:34 +00004511 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004512 I.swapOperands(); // Simplified below.
4513 std::swap(Op0, Op1);
4514 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004515 }
Chris Lattner318bf792007-03-18 22:51:34 +00004516 }
4517
4518 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4519 if (Op0I) {
4520 Value *A, *B;
4521 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4522 if (A == Op1) // (B|A)^B == (A|B)^B
4523 std::swap(A, B);
4524 if (B == Op1) { // (A|B)^B == A & ~B
4525 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004526 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4527 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004528 }
Chris Lattner318bf792007-03-18 22:51:34 +00004529 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4530 if (Op1 == A) // (A^B)^A == B
4531 return ReplaceInstUsesWith(I, B);
4532 else if (Op1 == B) // (B^A)^A == B
4533 return ReplaceInstUsesWith(I, A);
4534 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4535 if (A == Op1) // (A&B)^A -> (B&A)^A
4536 std::swap(A, B);
4537 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004538 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004539 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004540 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4541 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004542 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004543 }
Chris Lattner318bf792007-03-18 22:51:34 +00004544 }
4545
4546 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4547 if (Op0I && Op1I && Op0I->isShift() &&
4548 Op0I->getOpcode() == Op1I->getOpcode() &&
4549 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4550 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4551 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004552 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004553 Op1I->getOperand(0),
4554 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004555 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004556 Op1I->getOperand(1));
4557 }
4558
4559 if (Op0I && Op1I) {
4560 Value *A, *B, *C, *D;
4561 // (A & B)^(A | B) -> A ^ B
4562 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4563 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4564 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004565 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004566 }
4567 // (A | B)^(A & B) -> A ^ B
4568 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4569 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4570 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004571 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004572 }
4573
4574 // (A & B)^(C & D)
4575 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4576 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4577 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4578 // (X & Y)^(X & Y) -> (Y^Z) & X
4579 Value *X = 0, *Y = 0, *Z = 0;
4580 if (A == C)
4581 X = A, Y = B, Z = D;
4582 else if (A == D)
4583 X = A, Y = B, Z = C;
4584 else if (B == C)
4585 X = B, Y = A, Z = D;
4586 else if (B == D)
4587 X = B, Y = A, Z = C;
4588
4589 if (X) {
4590 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004591 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4592 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004593 }
4594 }
4595 }
4596
Reid Spencere4d87aa2006-12-23 06:05:41 +00004597 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4598 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4599 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004600 return R;
4601
Chris Lattner6fc205f2006-05-05 06:39:07 +00004602 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004603 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004604 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004605 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4606 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004607 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004608 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004609 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4610 I.getType(), TD) &&
4611 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4612 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004613 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004614 Op1C->getOperand(0),
4615 I.getName());
4616 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004617 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004618 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004619 }
Chris Lattner99c65742007-10-24 05:38:08 +00004620 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004621
Chris Lattner7e708292002-06-25 16:13:24 +00004622 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004623}
4624
Chris Lattnera96879a2004-09-29 17:40:11 +00004625/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4626/// overflowed for this type.
4627static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004628 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004629 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004630
Reid Spencere4e40032007-03-21 23:19:50 +00004631 if (IsSigned)
4632 if (In2->getValue().isNegative())
4633 return Result->getValue().sgt(In1->getValue());
4634 else
4635 return Result->getValue().slt(In1->getValue());
4636 else
4637 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004638}
4639
Chris Lattner574da9b2005-01-13 20:14:25 +00004640/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4641/// code necessary to compute the offset from the base pointer (without adding
4642/// in the base pointer). Return the result as a signed integer of intptr size.
4643static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4644 TargetData &TD = IC.getTargetData();
4645 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004646 const Type *IntPtrTy = TD.getIntPtrType();
4647 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004648
4649 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004650 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004651 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004652
Gabor Greif177dd3f2008-06-12 21:37:33 +00004653 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4654 ++i, ++GTI) {
4655 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004656 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004657 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4658 if (OpC->isZero()) continue;
4659
4660 // Handle a struct index, which adds its field offset to the pointer.
4661 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4662 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4663
4664 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4665 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004666 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004667 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004668 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004669 ConstantInt::get(IntPtrTy, Size),
4670 GEP->getName()+".offs"), I);
4671 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004672 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004673
4674 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4675 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4676 Scale = ConstantExpr::getMul(OC, Scale);
4677 if (Constant *RC = dyn_cast<Constant>(Result))
4678 Result = ConstantExpr::getAdd(RC, Scale);
4679 else {
4680 // Emit an add instruction.
4681 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004682 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004683 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004684 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004685 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004686 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004687 // Convert to correct type.
4688 if (Op->getType() != IntPtrTy) {
4689 if (Constant *OpC = dyn_cast<Constant>(Op))
4690 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4691 else
4692 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4693 Op->getName()+".c"), I);
4694 }
4695 if (Size != 1) {
4696 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4697 if (Constant *OpC = dyn_cast<Constant>(Op))
4698 Op = ConstantExpr::getMul(OpC, Scale);
4699 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004700 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004701 GEP->getName()+".idx"), I);
4702 }
4703
4704 // Emit an add instruction.
4705 if (isa<Constant>(Op) && isa<Constant>(Result))
4706 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4707 cast<Constant>(Result));
4708 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004709 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004710 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004711 }
4712 return Result;
4713}
4714
Chris Lattner10c0d912008-04-22 02:53:33 +00004715
4716/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4717/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4718/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4719/// complex, and scales are involved. The above expression would also be legal
4720/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4721/// later form is less amenable to optimization though, and we are allowed to
4722/// generate the first by knowing that pointer arithmetic doesn't overflow.
4723///
4724/// If we can't emit an optimized form for this expression, this returns null.
4725///
4726static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4727 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004728 TargetData &TD = IC.getTargetData();
4729 gep_type_iterator GTI = gep_type_begin(GEP);
4730
4731 // Check to see if this gep only has a single variable index. If so, and if
4732 // any constant indices are a multiple of its scale, then we can compute this
4733 // in terms of the scale of the variable index. For example, if the GEP
4734 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4735 // because the expression will cross zero at the same point.
4736 unsigned i, e = GEP->getNumOperands();
4737 int64_t Offset = 0;
4738 for (i = 1; i != e; ++i, ++GTI) {
4739 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4740 // Compute the aggregate offset of constant indices.
4741 if (CI->isZero()) continue;
4742
4743 // Handle a struct index, which adds its field offset to the pointer.
4744 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4745 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4746 } else {
4747 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4748 Offset += Size*CI->getSExtValue();
4749 }
4750 } else {
4751 // Found our variable index.
4752 break;
4753 }
4754 }
4755
4756 // If there are no variable indices, we must have a constant offset, just
4757 // evaluate it the general way.
4758 if (i == e) return 0;
4759
4760 Value *VariableIdx = GEP->getOperand(i);
4761 // Determine the scale factor of the variable element. For example, this is
4762 // 4 if the variable index is into an array of i32.
4763 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4764
4765 // Verify that there are no other variable indices. If so, emit the hard way.
4766 for (++i, ++GTI; i != e; ++i, ++GTI) {
4767 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4768 if (!CI) return 0;
4769
4770 // Compute the aggregate offset of constant indices.
4771 if (CI->isZero()) continue;
4772
4773 // Handle a struct index, which adds its field offset to the pointer.
4774 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4775 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4776 } else {
4777 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4778 Offset += Size*CI->getSExtValue();
4779 }
4780 }
4781
4782 // Okay, we know we have a single variable index, which must be a
4783 // pointer/array/vector index. If there is no offset, life is simple, return
4784 // the index.
4785 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4786 if (Offset == 0) {
4787 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4788 // we don't need to bother extending: the extension won't affect where the
4789 // computation crosses zero.
4790 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4791 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4792 VariableIdx->getNameStart(), &I);
4793 return VariableIdx;
4794 }
4795
4796 // Otherwise, there is an index. The computation we will do will be modulo
4797 // the pointer size, so get it.
4798 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4799
4800 Offset &= PtrSizeMask;
4801 VariableScale &= PtrSizeMask;
4802
4803 // To do this transformation, any constant index must be a multiple of the
4804 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4805 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4806 // multiple of the variable scale.
4807 int64_t NewOffs = Offset / (int64_t)VariableScale;
4808 if (Offset != NewOffs*(int64_t)VariableScale)
4809 return 0;
4810
4811 // Okay, we can do this evaluation. Start by converting the index to intptr.
4812 const Type *IntPtrTy = TD.getIntPtrType();
4813 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004814 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004815 true /*SExt*/,
4816 VariableIdx->getNameStart(), &I);
4817 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004818 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004819}
4820
4821
Reid Spencere4d87aa2006-12-23 06:05:41 +00004822/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004823/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004824Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4825 ICmpInst::Predicate Cond,
4826 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004827 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004828
Chris Lattner10c0d912008-04-22 02:53:33 +00004829 // Look through bitcasts.
4830 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4831 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004832
Chris Lattner574da9b2005-01-13 20:14:25 +00004833 Value *PtrBase = GEPLHS->getOperand(0);
4834 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004835 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004836 // This transformation (ignoring the base and scales) is valid because we
4837 // know pointers can't overflow. See if we can output an optimized form.
4838 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4839
4840 // If not, synthesize the offset the hard way.
4841 if (Offset == 0)
4842 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004843 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4844 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004845 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004846 // If the base pointers are different, but the indices are the same, just
4847 // compare the base pointer.
4848 if (PtrBase != GEPRHS->getOperand(0)) {
4849 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004850 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004851 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004852 if (IndicesTheSame)
4853 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4854 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4855 IndicesTheSame = false;
4856 break;
4857 }
4858
4859 // If all indices are the same, just compare the base pointers.
4860 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004861 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4862 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004863
4864 // Otherwise, the base pointers are different and the indices are
4865 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004866 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004867 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004868
Chris Lattnere9d782b2005-01-13 22:25:21 +00004869 // If one of the GEPs has all zero indices, recurse.
4870 bool AllZeros = true;
4871 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4872 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4873 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4874 AllZeros = false;
4875 break;
4876 }
4877 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004878 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4879 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004880
4881 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004882 AllZeros = true;
4883 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4884 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4885 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4886 AllZeros = false;
4887 break;
4888 }
4889 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004890 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004891
Chris Lattner4401c9c2005-01-14 00:20:05 +00004892 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4893 // If the GEPs only differ by one index, compare it.
4894 unsigned NumDifferences = 0; // Keep track of # differences.
4895 unsigned DiffOperand = 0; // The operand that differs.
4896 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4897 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004898 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4899 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004900 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004901 NumDifferences = 2;
4902 break;
4903 } else {
4904 if (NumDifferences++) break;
4905 DiffOperand = i;
4906 }
4907 }
4908
4909 if (NumDifferences == 0) // SAME GEP?
4910 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004911 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004912 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004913
Chris Lattner4401c9c2005-01-14 00:20:05 +00004914 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004915 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4916 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004917 // Make sure we do a signed comparison here.
4918 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004919 }
4920 }
4921
Reid Spencere4d87aa2006-12-23 06:05:41 +00004922 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004923 // the result to fold to a constant!
4924 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4925 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4926 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4927 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4928 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004929 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004930 }
4931 }
4932 return 0;
4933}
4934
Chris Lattnera5406232008-05-19 20:18:56 +00004935/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4936///
4937Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4938 Instruction *LHSI,
4939 Constant *RHSC) {
4940 if (!isa<ConstantFP>(RHSC)) return 0;
4941 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4942
4943 // Get the width of the mantissa. We don't want to hack on conversions that
4944 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004945 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004946 if (MantissaWidth == -1) return 0; // Unknown.
4947
4948 // Check to see that the input is converted from an integer type that is small
4949 // enough that preserves all bits. TODO: check here for "known" sign bits.
4950 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4951 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4952
4953 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4954 if (isa<UIToFPInst>(LHSI))
4955 ++InputSize;
4956
4957 // If the conversion would lose info, don't hack on this.
4958 if ((int)InputSize > MantissaWidth)
4959 return 0;
4960
4961 // Otherwise, we can potentially simplify the comparison. We know that it
4962 // will always come through as an integer value and we know the constant is
4963 // not a NAN (it would have been previously simplified).
4964 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4965
4966 ICmpInst::Predicate Pred;
4967 switch (I.getPredicate()) {
4968 default: assert(0 && "Unexpected predicate!");
4969 case FCmpInst::FCMP_UEQ:
4970 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4971 case FCmpInst::FCMP_UGT:
4972 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4973 case FCmpInst::FCMP_UGE:
4974 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4975 case FCmpInst::FCMP_ULT:
4976 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4977 case FCmpInst::FCMP_ULE:
4978 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4979 case FCmpInst::FCMP_UNE:
4980 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4981 case FCmpInst::FCMP_ORD:
4982 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4983 case FCmpInst::FCMP_UNO:
4984 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4985 }
4986
4987 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4988
4989 // Now we know that the APFloat is a normal number, zero or inf.
4990
Chris Lattner85162782008-05-20 03:50:52 +00004991 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004992 // comparing an i8 to 300.0.
4993 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4994
4995 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4996 // and large values.
4997 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4998 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4999 APFloat::rmNearestTiesToEven);
5000 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005001 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5002 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00005003 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5004 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5005 }
5006
5007 // See if the RHS value is < SignedMin.
5008 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5009 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5010 APFloat::rmNearestTiesToEven);
5011 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005012 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5013 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00005014 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5015 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5016 }
5017
5018 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5019 // it may still be fractional. See if it is fractional by casting the FP
5020 // value to the integer value and back, checking for equality. Don't do this
5021 // for zero, because -0.0 is not fractional.
5022 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5023 if (!RHS.isZero() &&
5024 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5025 // If we had a comparison against a fractional value, we have to adjust
5026 // the compare predicate and sometimes the value. RHSC is rounded towards
5027 // zero at this point.
5028 switch (Pred) {
5029 default: assert(0 && "Unexpected integer comparison!");
5030 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5031 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5032 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5033 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5034 case ICmpInst::ICMP_SLE:
5035 // (float)int <= 4.4 --> int <= 4
5036 // (float)int <= -4.4 --> int < -4
5037 if (RHS.isNegative())
5038 Pred = ICmpInst::ICMP_SLT;
5039 break;
5040 case ICmpInst::ICMP_SLT:
5041 // (float)int < -4.4 --> int < -4
5042 // (float)int < 4.4 --> int <= 4
5043 if (!RHS.isNegative())
5044 Pred = ICmpInst::ICMP_SLE;
5045 break;
5046 case ICmpInst::ICMP_SGT:
5047 // (float)int > 4.4 --> int > 4
5048 // (float)int > -4.4 --> int >= -4
5049 if (RHS.isNegative())
5050 Pred = ICmpInst::ICMP_SGE;
5051 break;
5052 case ICmpInst::ICMP_SGE:
5053 // (float)int >= -4.4 --> int >= -4
5054 // (float)int >= 4.4 --> int > 4
5055 if (!RHS.isNegative())
5056 Pred = ICmpInst::ICMP_SGT;
5057 break;
5058 }
5059 }
5060
5061 // Lower this FP comparison into an appropriate integer version of the
5062 // comparison.
5063 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5064}
5065
Reid Spencere4d87aa2006-12-23 06:05:41 +00005066Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5067 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005068 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005069
Chris Lattner58e97462007-01-14 19:42:17 +00005070 // Fold trivial predicates.
5071 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5072 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5073 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5074 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5075
5076 // Simplify 'fcmp pred X, X'
5077 if (Op0 == Op1) {
5078 switch (I.getPredicate()) {
5079 default: assert(0 && "Unknown predicate!");
5080 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5081 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5082 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5083 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5084 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5085 case FCmpInst::FCMP_OLT: // True if ordered and less than
5086 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5087 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5088
5089 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5090 case FCmpInst::FCMP_ULT: // True if unordered or less than
5091 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5092 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5093 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5094 I.setPredicate(FCmpInst::FCMP_UNO);
5095 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5096 return &I;
5097
5098 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5099 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5100 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5101 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5102 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5103 I.setPredicate(FCmpInst::FCMP_ORD);
5104 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5105 return &I;
5106 }
5107 }
5108
Reid Spencere4d87aa2006-12-23 06:05:41 +00005109 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005110 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005111
Reid Spencere4d87aa2006-12-23 06:05:41 +00005112 // Handle fcmp with constant RHS
5113 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005114 // If the constant is a nan, see if we can fold the comparison based on it.
5115 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5116 if (CFP->getValueAPF().isNaN()) {
5117 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5118 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005119 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5120 "Comparison must be either ordered or unordered!");
5121 // True if unordered.
5122 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005123 }
5124 }
5125
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5127 switch (LHSI->getOpcode()) {
5128 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005129 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5130 // block. If in the same block, we're encouraging jump threading. If
5131 // not, we are just pessimizing the code by making an i1 phi.
5132 if (LHSI->getParent() == I.getParent())
5133 if (Instruction *NV = FoldOpIntoPhi(I))
5134 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005135 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005136 case Instruction::SIToFP:
5137 case Instruction::UIToFP:
5138 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5139 return NV;
5140 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005141 case Instruction::Select:
5142 // If either operand of the select is a constant, we can fold the
5143 // comparison into the select arms, which will cause one to be
5144 // constant folded and the select turned into a bitwise or.
5145 Value *Op1 = 0, *Op2 = 0;
5146 if (LHSI->hasOneUse()) {
5147 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5148 // Fold the known value into the constant operand.
5149 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5150 // Insert a new FCmp of the other select operand.
5151 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5152 LHSI->getOperand(2), RHSC,
5153 I.getName()), I);
5154 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5155 // Fold the known value into the constant operand.
5156 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5157 // Insert a new FCmp of the other select operand.
5158 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5159 LHSI->getOperand(1), RHSC,
5160 I.getName()), I);
5161 }
5162 }
5163
5164 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005165 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005166 break;
5167 }
5168 }
5169
5170 return Changed ? &I : 0;
5171}
5172
5173Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5174 bool Changed = SimplifyCompare(I);
5175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5176 const Type *Ty = Op0->getType();
5177
5178 // icmp X, X
5179 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005180 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005181 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182
5183 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005184 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005185
Reid Spencere4d87aa2006-12-23 06:05:41 +00005186 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005187 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005188 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5189 isa<ConstantPointerNull>(Op0)) &&
5190 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005191 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005192 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005193 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005194
Reid Spencere4d87aa2006-12-23 06:05:41 +00005195 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005196 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005197 switch (I.getPredicate()) {
5198 default: assert(0 && "Invalid icmp instruction!");
5199 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005200 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005201 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005202 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005203 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005204 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005205 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005206
Reid Spencere4d87aa2006-12-23 06:05:41 +00005207 case ICmpInst::ICMP_UGT:
5208 case ICmpInst::ICMP_SGT:
5209 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005210 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005211 case ICmpInst::ICMP_ULT:
5212 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005213 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005214 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005215 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005216 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005217 case ICmpInst::ICMP_UGE:
5218 case ICmpInst::ICMP_SGE:
5219 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005220 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005221 case ICmpInst::ICMP_ULE:
5222 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005223 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005224 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005225 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005226 }
5227 }
Chris Lattner8b170942002-08-09 23:47:40 +00005228 }
5229
Chris Lattner2be51ae2004-06-09 04:24:29 +00005230 // See if we are doing a comparison between a constant and an instruction that
5231 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005232 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005233 Value *A, *B;
5234
Chris Lattnerb6566012008-01-05 01:18:20 +00005235 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5236 if (I.isEquality() && CI->isNullValue() &&
5237 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5238 // (icmp cond A B) if cond is equality
5239 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005240 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005241
Reid Spencere4d87aa2006-12-23 06:05:41 +00005242 switch (I.getPredicate()) {
5243 default: break;
5244 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5245 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005246 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005247 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5248 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5249 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5250 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005251 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5252 if (CI->isMinValue(true))
5253 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5254 ConstantInt::getAllOnesValue(Op0->getType()));
5255
Reid Spencere4d87aa2006-12-23 06:05:41 +00005256 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005257
Reid Spencere4d87aa2006-12-23 06:05:41 +00005258 case ICmpInst::ICMP_SLT:
5259 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005260 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005261 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5262 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5263 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5264 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5265 break;
5266
5267 case ICmpInst::ICMP_UGT:
5268 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005269 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005270 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5271 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5272 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5273 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005274
5275 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5276 if (CI->isMaxValue(true))
5277 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5278 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005279 break;
5280
5281 case ICmpInst::ICMP_SGT:
5282 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005283 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005284 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5285 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5286 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5287 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5288 break;
5289
5290 case ICmpInst::ICMP_ULE:
5291 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005292 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005293 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5294 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5295 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5296 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5297 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005298
Reid Spencere4d87aa2006-12-23 06:05:41 +00005299 case ICmpInst::ICMP_SLE:
5300 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005301 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005302 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5303 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5304 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5305 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5306 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005307
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 case ICmpInst::ICMP_UGE:
5309 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005310 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005311 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5312 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5313 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5314 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5315 break;
5316
5317 case ICmpInst::ICMP_SGE:
5318 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005319 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005320 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5321 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5322 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5323 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5324 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005325 }
5326
Reid Spencere4d87aa2006-12-23 06:05:41 +00005327 // If we still have a icmp le or icmp ge instruction, turn it into the
5328 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005329 // already been handled above, this requires little checking.
5330 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005331 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005332 default: break;
5333 case ICmpInst::ICMP_ULE:
5334 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5335 case ICmpInst::ICMP_SLE:
5336 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5337 case ICmpInst::ICMP_UGE:
5338 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5339 case ICmpInst::ICMP_SGE:
5340 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005341 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005342
5343 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005344 // in the input. If this comparison is a normal comparison, it demands all
5345 // bits, if it is a sign bit comparison, it only demands the sign bit.
5346
5347 bool UnusedBit;
5348 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5349
Reid Spencer0460fb32007-03-22 20:36:03 +00005350 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5351 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005352 if (SimplifyDemandedBits(Op0,
5353 isSignBit ? APInt::getSignBit(BitWidth)
5354 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005355 KnownZero, KnownOne, 0))
5356 return &I;
5357
5358 // Given the known and unknown bits, compute a range that the LHS could be
5359 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005360 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005361 // Compute the Min, Max and RHS values based on the known bits. For the
5362 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005363 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5364 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005365 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005366 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5367 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005368 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005369 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5370 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005371 }
5372 switch (I.getPredicate()) { // LE/GE have been folded already.
5373 default: assert(0 && "Unknown icmp opcode!");
5374 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005375 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005376 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005377 break;
5378 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005379 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005380 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005381 break;
5382 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005383 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005384 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005385 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005386 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005387 break;
5388 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005389 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005390 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005391 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005392 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005393 break;
5394 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005395 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005396 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005397 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005398 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005399 break;
5400 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005401 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005402 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005403 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005404 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005405 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005406 }
5407 }
5408
Reid Spencere4d87aa2006-12-23 06:05:41 +00005409 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005410 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005411 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005412 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005413 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5414 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005415 }
5416
Chris Lattner01deb9d2007-04-03 17:43:25 +00005417 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005418 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5419 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5420 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005421 case Instruction::GetElementPtr:
5422 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005423 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005424 bool isAllZeros = true;
5425 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5426 if (!isa<Constant>(LHSI->getOperand(i)) ||
5427 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5428 isAllZeros = false;
5429 break;
5430 }
5431 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005432 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005433 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5434 }
5435 break;
5436
Chris Lattner6970b662005-04-23 15:31:55 +00005437 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005438 // Only fold icmp into the PHI if the phi and fcmp are in the same
5439 // block. If in the same block, we're encouraging jump threading. If
5440 // not, we are just pessimizing the code by making an i1 phi.
5441 if (LHSI->getParent() == I.getParent())
5442 if (Instruction *NV = FoldOpIntoPhi(I))
5443 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005444 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005445 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005446 // If either operand of the select is a constant, we can fold the
5447 // comparison into the select arms, which will cause one to be
5448 // constant folded and the select turned into a bitwise or.
5449 Value *Op1 = 0, *Op2 = 0;
5450 if (LHSI->hasOneUse()) {
5451 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5452 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005453 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5454 // Insert a new ICmp of the other select operand.
5455 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5456 LHSI->getOperand(2), RHSC,
5457 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005458 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5459 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005460 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5461 // Insert a new ICmp of the other select operand.
5462 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5463 LHSI->getOperand(1), RHSC,
5464 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005465 }
5466 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005467
Chris Lattner6970b662005-04-23 15:31:55 +00005468 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005469 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005470 break;
5471 }
Chris Lattner4802d902007-04-06 18:57:34 +00005472 case Instruction::Malloc:
5473 // If we have (malloc != null), and if the malloc has a single use, we
5474 // can assume it is successful and remove the malloc.
5475 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5476 AddToWorkList(LHSI);
5477 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005478 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005479 }
5480 break;
5481 }
Chris Lattner6970b662005-04-23 15:31:55 +00005482 }
5483
Reid Spencere4d87aa2006-12-23 06:05:41 +00005484 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005485 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005486 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005487 return NI;
5488 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005489 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5490 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005491 return NI;
5492
Reid Spencere4d87aa2006-12-23 06:05:41 +00005493 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005494 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5495 // now.
5496 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5497 if (isa<PointerType>(Op0->getType()) &&
5498 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005499 // We keep moving the cast from the left operand over to the right
5500 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005501 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005502
Chris Lattner57d86372007-01-06 01:45:59 +00005503 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5504 // so eliminate it as well.
5505 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5506 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005507
Chris Lattnerde90b762003-11-03 04:25:02 +00005508 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005509 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005510 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005511 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005512 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005513 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005514 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005515 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005516 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005517 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005518 }
Chris Lattner57d86372007-01-06 01:45:59 +00005519 }
5520
5521 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005522 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005523 // This comes up when you have code like
5524 // int X = A < B;
5525 // if (X) ...
5526 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005527 // with a constant or another cast from the same type.
5528 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005529 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005530 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005531 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005532
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005533 // ~x < ~y --> y < x
5534 { Value *A, *B;
5535 if (match(Op0, m_Not(m_Value(A))) &&
5536 match(Op1, m_Not(m_Value(B))))
5537 return new ICmpInst(I.getPredicate(), B, A);
5538 }
5539
Chris Lattner65b72ba2006-09-18 04:22:48 +00005540 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005541 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005542
5543 // -x == -y --> x == y
5544 if (match(Op0, m_Neg(m_Value(A))) &&
5545 match(Op1, m_Neg(m_Value(B))))
5546 return new ICmpInst(I.getPredicate(), A, B);
5547
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005548 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5549 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5550 Value *OtherVal = A == Op1 ? B : A;
5551 return new ICmpInst(I.getPredicate(), OtherVal,
5552 Constant::getNullValue(A->getType()));
5553 }
5554
5555 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5556 // A^c1 == C^c2 --> A == C^(c1^c2)
5557 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5558 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5559 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005560 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005561 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005562 return new ICmpInst(I.getPredicate(), A,
5563 InsertNewInstBefore(Xor, I));
5564 }
5565
5566 // A^B == A^D -> B == D
5567 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5568 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5569 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5570 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5571 }
5572 }
5573
5574 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5575 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005576 // A == (A^B) -> B == 0
5577 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005578 return new ICmpInst(I.getPredicate(), OtherVal,
5579 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005580 }
5581 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005582 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583 return new ICmpInst(I.getPredicate(), B,
5584 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005585 }
5586 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005587 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 return new ICmpInst(I.getPredicate(), B,
5589 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005590 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005591
Chris Lattner9c2328e2006-11-14 06:06:06 +00005592 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5593 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5594 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5595 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5596 Value *X = 0, *Y = 0, *Z = 0;
5597
5598 if (A == C) {
5599 X = B; Y = D; Z = A;
5600 } else if (A == D) {
5601 X = B; Y = C; Z = A;
5602 } else if (B == C) {
5603 X = A; Y = D; Z = B;
5604 } else if (B == D) {
5605 X = A; Y = C; Z = B;
5606 }
5607
5608 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005609 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5610 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005611 I.setOperand(0, Op1);
5612 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5613 return &I;
5614 }
5615 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005616 }
Chris Lattner7e708292002-06-25 16:13:24 +00005617 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005618}
5619
Chris Lattner562ef782007-06-20 23:46:26 +00005620
5621/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5622/// and CmpRHS are both known to be integer constants.
5623Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5624 ConstantInt *DivRHS) {
5625 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5626 const APInt &CmpRHSV = CmpRHS->getValue();
5627
5628 // FIXME: If the operand types don't match the type of the divide
5629 // then don't attempt this transform. The code below doesn't have the
5630 // logic to deal with a signed divide and an unsigned compare (and
5631 // vice versa). This is because (x /s C1) <s C2 produces different
5632 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5633 // (x /u C1) <u C2. Simply casting the operands and result won't
5634 // work. :( The if statement below tests that condition and bails
5635 // if it finds it.
5636 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5637 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5638 return 0;
5639 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005640 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005641
5642 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5643 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5644 // C2 (CI). By solving for X we can turn this into a range check
5645 // instead of computing a divide.
5646 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5647
5648 // Determine if the product overflows by seeing if the product is
5649 // not equal to the divide. Make sure we do the same kind of divide
5650 // as in the LHS instruction that we're folding.
5651 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5652 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5653
5654 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005655 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005656
Chris Lattner1dbfd482007-06-21 18:11:19 +00005657 // Figure out the interval that is being checked. For example, a comparison
5658 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5659 // Compute this interval based on the constants involved and the signedness of
5660 // the compare/divide. This computes a half-open interval, keeping track of
5661 // whether either value in the interval overflows. After analysis each
5662 // overflow variable is set to 0 if it's corresponding bound variable is valid
5663 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5664 int LoOverflow = 0, HiOverflow = 0;
5665 ConstantInt *LoBound = 0, *HiBound = 0;
5666
5667
Chris Lattner562ef782007-06-20 23:46:26 +00005668 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005669 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005670 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005671 HiOverflow = LoOverflow = ProdOV;
5672 if (!HiOverflow)
5673 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005674 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005675 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005676 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005677 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5678 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005679 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005680 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5681 HiOverflow = LoOverflow = ProdOV;
5682 if (!HiOverflow)
5683 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005684 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005685 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005686 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5687 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005688 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005689 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005690 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005691 }
Dan Gohman76491272008-02-13 22:09:18 +00005692 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005693 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005694 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005695 LoBound = AddOne(DivRHS);
5696 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005697 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5698 HiOverflow = 1; // [INTMIN+1, overflow)
5699 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5700 }
Dan Gohman76491272008-02-13 22:09:18 +00005701 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005702 // e.g. X/-5 op 3 --> [-19, -14)
5703 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005704 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005705 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005706 HiBound = AddOne(Prod);
5707 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005708 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005709 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005710 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005711 HiBound = Subtract(Prod, DivRHS);
5712 }
5713
Chris Lattner1dbfd482007-06-21 18:11:19 +00005714 // Dividing by a negative swaps the condition. LT <-> GT
5715 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005716 }
5717
5718 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005719 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005720 default: assert(0 && "Unhandled icmp opcode!");
5721 case ICmpInst::ICMP_EQ:
5722 if (LoOverflow && HiOverflow)
5723 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5724 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005725 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005726 ICmpInst::ICMP_UGE, X, LoBound);
5727 else if (LoOverflow)
5728 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5729 ICmpInst::ICMP_ULT, X, HiBound);
5730 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005731 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005732 case ICmpInst::ICMP_NE:
5733 if (LoOverflow && HiOverflow)
5734 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5735 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005736 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005737 ICmpInst::ICMP_ULT, X, LoBound);
5738 else if (LoOverflow)
5739 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5740 ICmpInst::ICMP_UGE, X, HiBound);
5741 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005742 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005743 case ICmpInst::ICMP_ULT:
5744 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005745 if (LoOverflow == +1) // Low bound is greater than input range.
5746 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5747 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005748 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005749 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005750 case ICmpInst::ICMP_UGT:
5751 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005752 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005753 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005754 else if (HiOverflow == -1) // High bound less than input range.
5755 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5756 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005757 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5758 else
5759 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5760 }
5761}
5762
5763
Chris Lattner01deb9d2007-04-03 17:43:25 +00005764/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5765///
5766Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5767 Instruction *LHSI,
5768 ConstantInt *RHS) {
5769 const APInt &RHSV = RHS->getValue();
5770
5771 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005772 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005773 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5774 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5775 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005776 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5777 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005778 Value *CompareVal = LHSI->getOperand(0);
5779
5780 // If the sign bit of the XorCST is not set, there is no change to
5781 // the operation, just stop using the Xor.
5782 if (!XorCST->getValue().isNegative()) {
5783 ICI.setOperand(0, CompareVal);
5784 AddToWorkList(LHSI);
5785 return &ICI;
5786 }
5787
5788 // Was the old condition true if the operand is positive?
5789 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5790
5791 // If so, the new one isn't.
5792 isTrueIfPositive ^= true;
5793
5794 if (isTrueIfPositive)
5795 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5796 else
5797 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5798 }
5799 }
5800 break;
5801 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5802 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5803 LHSI->getOperand(0)->hasOneUse()) {
5804 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5805
5806 // If the LHS is an AND of a truncating cast, we can widen the
5807 // and/compare to be the input width without changing the value
5808 // produced, eliminating a cast.
5809 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5810 // We can do this transformation if either the AND constant does not
5811 // have its sign bit set or if it is an equality comparison.
5812 // Extending a relational comparison when we're checking the sign
5813 // bit would not work.
5814 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005815 (ICI.isEquality() ||
5816 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005817 uint32_t BitWidth =
5818 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5819 APInt NewCST = AndCST->getValue();
5820 NewCST.zext(BitWidth);
5821 APInt NewCI = RHSV;
5822 NewCI.zext(BitWidth);
5823 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005824 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005825 ConstantInt::get(NewCST),LHSI->getName());
5826 InsertNewInstBefore(NewAnd, ICI);
5827 return new ICmpInst(ICI.getPredicate(), NewAnd,
5828 ConstantInt::get(NewCI));
5829 }
5830 }
5831
5832 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5833 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5834 // happens a LOT in code produced by the C front-end, for bitfield
5835 // access.
5836 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5837 if (Shift && !Shift->isShift())
5838 Shift = 0;
5839
5840 ConstantInt *ShAmt;
5841 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5842 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5843 const Type *AndTy = AndCST->getType(); // Type of the and.
5844
5845 // We can fold this as long as we can't shift unknown bits
5846 // into the mask. This can only happen with signed shift
5847 // rights, as they sign-extend.
5848 if (ShAmt) {
5849 bool CanFold = Shift->isLogicalShift();
5850 if (!CanFold) {
5851 // To test for the bad case of the signed shr, see if any
5852 // of the bits shifted in could be tested after the mask.
5853 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5854 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5855
5856 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5857 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5858 AndCST->getValue()) == 0)
5859 CanFold = true;
5860 }
5861
5862 if (CanFold) {
5863 Constant *NewCst;
5864 if (Shift->getOpcode() == Instruction::Shl)
5865 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5866 else
5867 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5868
5869 // Check to see if we are shifting out any of the bits being
5870 // compared.
5871 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5872 // If we shifted bits out, the fold is not going to work out.
5873 // As a special case, check to see if this means that the
5874 // result is always true or false now.
5875 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5876 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5877 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5878 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5879 } else {
5880 ICI.setOperand(1, NewCst);
5881 Constant *NewAndCST;
5882 if (Shift->getOpcode() == Instruction::Shl)
5883 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5884 else
5885 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5886 LHSI->setOperand(1, NewAndCST);
5887 LHSI->setOperand(0, Shift->getOperand(0));
5888 AddToWorkList(Shift); // Shift is dead.
5889 AddUsesToWorkList(ICI);
5890 return &ICI;
5891 }
5892 }
5893 }
5894
5895 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5896 // preferable because it allows the C<<Y expression to be hoisted out
5897 // of a loop if Y is invariant and X is not.
5898 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5899 ICI.isEquality() && !Shift->isArithmeticShift() &&
5900 isa<Instruction>(Shift->getOperand(0))) {
5901 // Compute C << Y.
5902 Value *NS;
5903 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005904 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005905 Shift->getOperand(1), "tmp");
5906 } else {
5907 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005908 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005909 Shift->getOperand(1), "tmp");
5910 }
5911 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5912
5913 // Compute X & (C << Y).
5914 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005915 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005916 InsertNewInstBefore(NewAnd, ICI);
5917
5918 ICI.setOperand(0, NewAnd);
5919 return &ICI;
5920 }
5921 }
5922 break;
5923
Chris Lattnera0141b92007-07-15 20:42:37 +00005924 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5925 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5926 if (!ShAmt) break;
5927
5928 uint32_t TypeBits = RHSV.getBitWidth();
5929
5930 // Check that the shift amount is in range. If not, don't perform
5931 // undefined shifts. When the shift is visited it will be
5932 // simplified.
5933 if (ShAmt->uge(TypeBits))
5934 break;
5935
5936 if (ICI.isEquality()) {
5937 // If we are comparing against bits always shifted out, the
5938 // comparison cannot succeed.
5939 Constant *Comp =
5940 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5941 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5942 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5943 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5944 return ReplaceInstUsesWith(ICI, Cst);
5945 }
5946
5947 if (LHSI->hasOneUse()) {
5948 // Otherwise strength reduce the shift into an and.
5949 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5950 Constant *Mask =
5951 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005952
Chris Lattnera0141b92007-07-15 20:42:37 +00005953 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005954 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005955 Mask, LHSI->getName()+".mask");
5956 Value *And = InsertNewInstBefore(AndI, ICI);
5957 return new ICmpInst(ICI.getPredicate(), And,
5958 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005959 }
5960 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005961
5962 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5963 bool TrueIfSigned = false;
5964 if (LHSI->hasOneUse() &&
5965 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5966 // (X << 31) <s 0 --> (X&1) != 0
5967 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5968 (TypeBits-ShAmt->getZExtValue()-1));
5969 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005970 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005971 Mask, LHSI->getName()+".mask");
5972 Value *And = InsertNewInstBefore(AndI, ICI);
5973
5974 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5975 And, Constant::getNullValue(And->getType()));
5976 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005977 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005978 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005979
5980 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005981 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005982 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005983 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005984 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005985
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005986 // Check that the shift amount is in range. If not, don't perform
5987 // undefined shifts. When the shift is visited it will be
5988 // simplified.
5989 uint32_t TypeBits = RHSV.getBitWidth();
5990 if (ShAmt->uge(TypeBits))
5991 break;
5992
5993 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005994
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005995 // If we are comparing against bits always shifted out, the
5996 // comparison cannot succeed.
5997 APInt Comp = RHSV << ShAmtVal;
5998 if (LHSI->getOpcode() == Instruction::LShr)
5999 Comp = Comp.lshr(ShAmtVal);
6000 else
6001 Comp = Comp.ashr(ShAmtVal);
6002
6003 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6004 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6005 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6006 return ReplaceInstUsesWith(ICI, Cst);
6007 }
6008
6009 // Otherwise, check to see if the bits shifted out are known to be zero.
6010 // If so, we can compare against the unshifted value:
6011 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006012 if (LHSI->hasOneUse() &&
6013 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006014 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6015 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6016 ConstantExpr::getShl(RHS, ShAmt));
6017 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006018
Evan Chengf30752c2008-04-23 00:38:06 +00006019 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006020 // Otherwise strength reduce the shift into an and.
6021 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6022 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006023
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006024 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006025 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006026 Mask, LHSI->getName()+".mask");
6027 Value *And = InsertNewInstBefore(AndI, ICI);
6028 return new ICmpInst(ICI.getPredicate(), And,
6029 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006030 }
6031 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006032 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006033
6034 case Instruction::SDiv:
6035 case Instruction::UDiv:
6036 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6037 // Fold this div into the comparison, producing a range check.
6038 // Determine, based on the divide type, what the range is being
6039 // checked. If there is an overflow on the low or high side, remember
6040 // it, otherwise compute the range [low, hi) bounding the new value.
6041 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006042 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6043 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6044 DivRHS))
6045 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006046 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006047
6048 case Instruction::Add:
6049 // Fold: icmp pred (add, X, C1), C2
6050
6051 if (!ICI.isEquality()) {
6052 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6053 if (!LHSC) break;
6054 const APInt &LHSV = LHSC->getValue();
6055
6056 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6057 .subtract(LHSV);
6058
6059 if (ICI.isSignedPredicate()) {
6060 if (CR.getLower().isSignBit()) {
6061 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6062 ConstantInt::get(CR.getUpper()));
6063 } else if (CR.getUpper().isSignBit()) {
6064 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6065 ConstantInt::get(CR.getLower()));
6066 }
6067 } else {
6068 if (CR.getLower().isMinValue()) {
6069 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6070 ConstantInt::get(CR.getUpper()));
6071 } else if (CR.getUpper().isMinValue()) {
6072 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6073 ConstantInt::get(CR.getLower()));
6074 }
6075 }
6076 }
6077 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006078 }
6079
6080 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6081 if (ICI.isEquality()) {
6082 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6083
6084 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6085 // the second operand is a constant, simplify a bit.
6086 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6087 switch (BO->getOpcode()) {
6088 case Instruction::SRem:
6089 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6090 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6091 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6092 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6093 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006094 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006095 BO->getName());
6096 InsertNewInstBefore(NewRem, ICI);
6097 return new ICmpInst(ICI.getPredicate(), NewRem,
6098 Constant::getNullValue(BO->getType()));
6099 }
6100 }
6101 break;
6102 case Instruction::Add:
6103 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6104 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6105 if (BO->hasOneUse())
6106 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6107 Subtract(RHS, BOp1C));
6108 } else if (RHSV == 0) {
6109 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6110 // efficiently invertible, or if the add has just this one use.
6111 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6112
6113 if (Value *NegVal = dyn_castNegVal(BOp1))
6114 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6115 else if (Value *NegVal = dyn_castNegVal(BOp0))
6116 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6117 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006118 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006119 InsertNewInstBefore(Neg, ICI);
6120 Neg->takeName(BO);
6121 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6122 }
6123 }
6124 break;
6125 case Instruction::Xor:
6126 // For the xor case, we can xor two constants together, eliminating
6127 // the explicit xor.
6128 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6129 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6130 ConstantExpr::getXor(RHS, BOC));
6131
6132 // FALLTHROUGH
6133 case Instruction::Sub:
6134 // Replace (([sub|xor] A, B) != 0) with (A != B)
6135 if (RHSV == 0)
6136 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6137 BO->getOperand(1));
6138 break;
6139
6140 case Instruction::Or:
6141 // If bits are being or'd in that are not present in the constant we
6142 // are comparing against, then the comparison could never succeed!
6143 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6144 Constant *NotCI = ConstantExpr::getNot(RHS);
6145 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6146 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6147 isICMP_NE));
6148 }
6149 break;
6150
6151 case Instruction::And:
6152 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6153 // If bits are being compared against that are and'd out, then the
6154 // comparison can never succeed!
6155 if ((RHSV & ~BOC->getValue()) != 0)
6156 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6157 isICMP_NE));
6158
6159 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6160 if (RHS == BOC && RHSV.isPowerOf2())
6161 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6162 ICmpInst::ICMP_NE, LHSI,
6163 Constant::getNullValue(RHS->getType()));
6164
6165 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006166 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006167 Value *X = BO->getOperand(0);
6168 Constant *Zero = Constant::getNullValue(X->getType());
6169 ICmpInst::Predicate pred = isICMP_NE ?
6170 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6171 return new ICmpInst(pred, X, Zero);
6172 }
6173
6174 // ((X & ~7) == 0) --> X < 8
6175 if (RHSV == 0 && isHighOnes(BOC)) {
6176 Value *X = BO->getOperand(0);
6177 Constant *NegX = ConstantExpr::getNeg(BOC);
6178 ICmpInst::Predicate pred = isICMP_NE ?
6179 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6180 return new ICmpInst(pred, X, NegX);
6181 }
6182 }
6183 default: break;
6184 }
6185 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6186 // Handle icmp {eq|ne} <intrinsic>, intcst.
6187 if (II->getIntrinsicID() == Intrinsic::bswap) {
6188 AddToWorkList(II);
6189 ICI.setOperand(0, II->getOperand(1));
6190 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6191 return &ICI;
6192 }
6193 }
6194 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006195 // If the LHS is a cast from an integral value of the same size,
6196 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006197 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6198 Value *CastOp = Cast->getOperand(0);
6199 const Type *SrcTy = CastOp->getType();
6200 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6201 if (SrcTy->isInteger() &&
6202 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6203 // If this is an unsigned comparison, try to make the comparison use
6204 // smaller constant values.
6205 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6206 // X u< 128 => X s> -1
6207 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6208 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6209 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6210 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6211 // X u> 127 => X s< 0
6212 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6213 Constant::getNullValue(SrcTy));
6214 }
6215 }
6216 }
6217 }
6218 return 0;
6219}
6220
6221/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6222/// We only handle extending casts so far.
6223///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006224Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6225 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006226 Value *LHSCIOp = LHSCI->getOperand(0);
6227 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006228 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006229 Value *RHSCIOp;
6230
Chris Lattner8c756c12007-05-05 22:41:33 +00006231 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6232 // integer type is the same size as the pointer type.
6233 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6234 getTargetData().getPointerSizeInBits() ==
6235 cast<IntegerType>(DestTy)->getBitWidth()) {
6236 Value *RHSOp = 0;
6237 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006238 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006239 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6240 RHSOp = RHSC->getOperand(0);
6241 // If the pointer types don't match, insert a bitcast.
6242 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006243 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006244 }
6245
6246 if (RHSOp)
6247 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6248 }
6249
6250 // The code below only handles extension cast instructions, so far.
6251 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006252 if (LHSCI->getOpcode() != Instruction::ZExt &&
6253 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006254 return 0;
6255
Reid Spencere4d87aa2006-12-23 06:05:41 +00006256 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6257 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006258
Reid Spencere4d87aa2006-12-23 06:05:41 +00006259 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006260 // Not an extension from the same type?
6261 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006262 if (RHSCIOp->getType() != LHSCIOp->getType())
6263 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006264
Nick Lewycky4189a532008-01-28 03:48:02 +00006265 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006266 // and the other is a zext), then we can't handle this.
6267 if (CI->getOpcode() != LHSCI->getOpcode())
6268 return 0;
6269
Nick Lewycky4189a532008-01-28 03:48:02 +00006270 // Deal with equality cases early.
6271 if (ICI.isEquality())
6272 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6273
6274 // A signed comparison of sign extended values simplifies into a
6275 // signed comparison.
6276 if (isSignedCmp && isSignedExt)
6277 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6278
6279 // The other three cases all fold into an unsigned comparison.
6280 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006281 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006282
Reid Spencere4d87aa2006-12-23 06:05:41 +00006283 // If we aren't dealing with a constant on the RHS, exit early
6284 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6285 if (!CI)
6286 return 0;
6287
6288 // Compute the constant that would happen if we truncated to SrcTy then
6289 // reextended to DestTy.
6290 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6291 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6292
6293 // If the re-extended constant didn't change...
6294 if (Res2 == CI) {
6295 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6296 // For example, we might have:
6297 // %A = sext short %X to uint
6298 // %B = icmp ugt uint %A, 1330
6299 // It is incorrect to transform this into
6300 // %B = icmp ugt short %X, 1330
6301 // because %A may have negative value.
6302 //
6303 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6304 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006305 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006306 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6307 else
6308 return 0;
6309 }
6310
6311 // The re-extended constant changed so the constant cannot be represented
6312 // in the shorter type. Consequently, we cannot emit a simple comparison.
6313
6314 // First, handle some easy cases. We know the result cannot be equal at this
6315 // point so handle the ICI.isEquality() cases
6316 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006317 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006318 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006319 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006320
6321 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6322 // should have been folded away previously and not enter in here.
6323 Value *Result;
6324 if (isSignedCmp) {
6325 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006326 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006327 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006329 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006330 } else {
6331 // We're performing an unsigned comparison.
6332 if (isSignedExt) {
6333 // We're performing an unsigned comp with a sign extended value.
6334 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006335 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6337 NegOne, ICI.getName()), ICI);
6338 } else {
6339 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006340 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 }
6342 }
6343
6344 // Finally, return the value computed.
6345 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6346 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6347 return ReplaceInstUsesWith(ICI, Result);
6348 } else {
6349 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6350 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6351 "ICmp should be folded!");
6352 if (Constant *CI = dyn_cast<Constant>(Result))
6353 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6354 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006355 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006357}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006358
Reid Spencer832254e2007-02-02 02:16:23 +00006359Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6360 return commonShiftTransforms(I);
6361}
6362
6363Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6364 return commonShiftTransforms(I);
6365}
6366
6367Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006368 if (Instruction *R = commonShiftTransforms(I))
6369 return R;
6370
6371 Value *Op0 = I.getOperand(0);
6372
6373 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6374 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6375 if (CSI->isAllOnesValue())
6376 return ReplaceInstUsesWith(I, CSI);
6377
6378 // See if we can turn a signed shr into an unsigned shr.
6379 if (MaskedValueIsZero(Op0,
6380 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006381 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006382
6383 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006384}
6385
6386Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6387 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006388 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006389
6390 // shl X, 0 == X and shr X, 0 == X
6391 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006392 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006393 Op0 == Constant::getNullValue(Op0->getType()))
6394 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006395
Reid Spencere4d87aa2006-12-23 06:05:41 +00006396 if (isa<UndefValue>(Op0)) {
6397 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006398 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006399 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006400 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6401 }
6402 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006403 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6404 return ReplaceInstUsesWith(I, Op0);
6405 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006406 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006407 }
6408
Chris Lattner2eefe512004-04-09 19:05:30 +00006409 // Try to fold constant and into select arguments.
6410 if (isa<Constant>(Op0))
6411 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006412 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006413 return R;
6414
Reid Spencerb83eb642006-10-20 07:07:24 +00006415 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006416 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6417 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006418 return 0;
6419}
6420
Reid Spencerb83eb642006-10-20 07:07:24 +00006421Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006422 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006423 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006424
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006425 // See if we can simplify any instructions used by the instruction whose sole
6426 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006427 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6428 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6429 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006430 KnownZero, KnownOne))
6431 return &I;
6432
Chris Lattner4d5542c2006-01-06 07:12:35 +00006433 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6434 // of a signed value.
6435 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006436 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006437 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006438 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6439 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006440 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006441 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006442 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006443 }
6444
6445 // ((X*C1) << C2) == (X * (C1 << C2))
6446 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6447 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6448 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006449 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006450 ConstantExpr::getShl(BOOp, Op1));
6451
6452 // Try to fold constant and into select arguments.
6453 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6454 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6455 return R;
6456 if (isa<PHINode>(Op0))
6457 if (Instruction *NV = FoldOpIntoPhi(I))
6458 return NV;
6459
Chris Lattner8999dd32007-12-22 09:07:47 +00006460 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6461 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6462 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6463 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6464 // place. Don't try to do this transformation in this case. Also, we
6465 // require that the input operand is a shift-by-constant so that we have
6466 // confidence that the shifts will get folded together. We could do this
6467 // xform in more cases, but it is unlikely to be profitable.
6468 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6469 isa<ConstantInt>(TrOp->getOperand(1))) {
6470 // Okay, we'll do this xform. Make the shift of shift.
6471 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006472 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006473 I.getName());
6474 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6475
6476 // For logical shifts, the truncation has the effect of making the high
6477 // part of the register be zeros. Emulate this by inserting an AND to
6478 // clear the top bits as needed. This 'and' will usually be zapped by
6479 // other xforms later if dead.
6480 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6481 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6482 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6483
6484 // The mask we constructed says what the trunc would do if occurring
6485 // between the shifts. We want to know the effect *after* the second
6486 // shift. We know that it is a logical shift by a constant, so adjust the
6487 // mask as appropriate.
6488 if (I.getOpcode() == Instruction::Shl)
6489 MaskV <<= Op1->getZExtValue();
6490 else {
6491 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6492 MaskV = MaskV.lshr(Op1->getZExtValue());
6493 }
6494
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006495 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006496 TI->getName());
6497 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6498
6499 // Return the value truncated to the interesting size.
6500 return new TruncInst(And, I.getType());
6501 }
6502 }
6503
Chris Lattner4d5542c2006-01-06 07:12:35 +00006504 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006505 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6506 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6507 Value *V1, *V2;
6508 ConstantInt *CC;
6509 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006510 default: break;
6511 case Instruction::Add:
6512 case Instruction::And:
6513 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006514 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006515 // These operators commute.
6516 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006517 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6518 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006519 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006520 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006521 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006522 Op0BO->getName());
6523 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006524 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006525 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006526 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006527 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006528 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006529 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006530 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006531 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006532
Chris Lattner150f12a2005-09-18 06:30:59 +00006533 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006534 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006535 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006536 match(Op0BOOp1,
6537 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006538 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6539 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006540 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006541 Op0BO->getOperand(0), Op1,
6542 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006543 InsertNewInstBefore(YS, I); // (Y << C)
6544 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006545 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006546 V1->getName()+".mask");
6547 InsertNewInstBefore(XM, I); // X & (CC << C)
6548
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006549 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006550 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006551 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006552
Reid Spencera07cb7d2007-02-02 14:41:37 +00006553 // FALL THROUGH.
6554 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006555 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006556 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6557 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006558 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006559 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006560 Op0BO->getOperand(1), Op1,
6561 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006562 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006563 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006564 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006565 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006566 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006567 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006568 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006569 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006570 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006571
Chris Lattner13d4ab42006-05-31 21:14:00 +00006572 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006573 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6574 match(Op0BO->getOperand(0),
6575 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006576 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006577 cast<BinaryOperator>(Op0BO->getOperand(0))
6578 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006579 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006580 Op0BO->getOperand(1), Op1,
6581 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006582 InsertNewInstBefore(YS, I); // (Y << C)
6583 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006584 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006585 V1->getName()+".mask");
6586 InsertNewInstBefore(XM, I); // X & (CC << C)
6587
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006588 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006589 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006590
Chris Lattner11021cb2005-09-18 05:12:10 +00006591 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006592 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006593 }
6594
6595
6596 // If the operand is an bitwise operator with a constant RHS, and the
6597 // shift is the only use, we can pull it out of the shift.
6598 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6599 bool isValid = true; // Valid only for And, Or, Xor
6600 bool highBitSet = false; // Transform if high bit of constant set?
6601
6602 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006603 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006604 case Instruction::Add:
6605 isValid = isLeftShift;
6606 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006607 case Instruction::Or:
6608 case Instruction::Xor:
6609 highBitSet = false;
6610 break;
6611 case Instruction::And:
6612 highBitSet = true;
6613 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006614 }
6615
6616 // If this is a signed shift right, and the high bit is modified
6617 // by the logical operation, do not perform the transformation.
6618 // The highBitSet boolean indicates the value of the high bit of
6619 // the constant which would cause it to be modified for this
6620 // operation.
6621 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006622 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006623 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006624
6625 if (isValid) {
6626 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6627
6628 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006629 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006630 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006631 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006632
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006633 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006634 NewRHS);
6635 }
6636 }
6637 }
6638 }
6639
Chris Lattnerad0124c2006-01-06 07:52:12 +00006640 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006641 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6642 if (ShiftOp && !ShiftOp->isShift())
6643 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006644
Reid Spencerb83eb642006-10-20 07:07:24 +00006645 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006646 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006647 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6648 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006649 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6650 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6651 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006652
Zhou Sheng4351c642007-04-02 08:20:41 +00006653 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006654 if (AmtSum > TypeBits)
6655 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006656
6657 const IntegerType *Ty = cast<IntegerType>(I.getType());
6658
6659 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006660 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006661 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006662 ConstantInt::get(Ty, AmtSum));
6663 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6664 I.getOpcode() == Instruction::AShr) {
6665 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006666 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006667 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6668 I.getOpcode() == Instruction::LShr) {
6669 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6670 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006671 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006672 InsertNewInstBefore(Shift, I);
6673
Zhou Shenge9e03f62007-03-28 15:02:20 +00006674 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006675 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006676 }
6677
Chris Lattnerb87056f2007-02-05 00:57:54 +00006678 // Okay, if we get here, one shift must be left, and the other shift must be
6679 // right. See if the amounts are equal.
6680 if (ShiftAmt1 == ShiftAmt2) {
6681 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6682 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006683 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006684 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006685 }
6686 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6687 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006688 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006689 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006690 }
6691 // We can simplify ((X << C) >>s C) into a trunc + sext.
6692 // NOTE: we could do this for any C, but that would make 'unusual' integer
6693 // types. For now, just stick to ones well-supported by the code
6694 // generators.
6695 const Type *SExtType = 0;
6696 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006697 case 1 :
6698 case 8 :
6699 case 16 :
6700 case 32 :
6701 case 64 :
6702 case 128:
6703 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6704 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006705 default: break;
6706 }
6707 if (SExtType) {
6708 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6709 InsertNewInstBefore(NewTrunc, I);
6710 return new SExtInst(NewTrunc, Ty);
6711 }
6712 // Otherwise, we can't handle it yet.
6713 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006714 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006715
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006716 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006717 if (I.getOpcode() == Instruction::Shl) {
6718 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6719 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006720 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006721 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006722 InsertNewInstBefore(Shift, I);
6723
Reid Spencer55702aa2007-03-25 21:11:44 +00006724 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006725 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006726 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006727
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006728 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006729 if (I.getOpcode() == Instruction::LShr) {
6730 assert(ShiftOp->getOpcode() == Instruction::Shl);
6731 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006732 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006733 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006734
Reid Spencerd5e30f02007-03-26 17:18:58 +00006735 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006736 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006737 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006738
6739 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6740 } else {
6741 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006742 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006743
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006744 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006745 if (I.getOpcode() == Instruction::Shl) {
6746 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6747 ShiftOp->getOpcode() == Instruction::AShr);
6748 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006749 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006750 ConstantInt::get(Ty, ShiftDiff));
6751 InsertNewInstBefore(Shift, I);
6752
Reid Spencer55702aa2007-03-25 21:11:44 +00006753 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006754 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006755 }
6756
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006757 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006758 if (I.getOpcode() == Instruction::LShr) {
6759 assert(ShiftOp->getOpcode() == Instruction::Shl);
6760 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006761 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006762 InsertNewInstBefore(Shift, I);
6763
Reid Spencer68d27cf2007-03-26 23:45:51 +00006764 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006765 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006766 }
6767
6768 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006769 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006770 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006771 return 0;
6772}
6773
Chris Lattnera1be5662002-05-02 17:06:02 +00006774
Chris Lattnercfd65102005-10-29 04:36:15 +00006775/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6776/// expression. If so, decompose it, returning some value X, such that Val is
6777/// X*Scale+Offset.
6778///
6779static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006780 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006781 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006782 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006783 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006784 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006785 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006786 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6787 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6788 if (I->getOpcode() == Instruction::Shl) {
6789 // This is a value scaled by '1 << the shift amt'.
6790 Scale = 1U << RHS->getZExtValue();
6791 Offset = 0;
6792 return I->getOperand(0);
6793 } else if (I->getOpcode() == Instruction::Mul) {
6794 // This value is scaled by 'RHS'.
6795 Scale = RHS->getZExtValue();
6796 Offset = 0;
6797 return I->getOperand(0);
6798 } else if (I->getOpcode() == Instruction::Add) {
6799 // We have X+C. Check to see if we really have (X*C2)+C1,
6800 // where C1 is divisible by C2.
6801 unsigned SubScale;
6802 Value *SubVal =
6803 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6804 Offset += RHS->getZExtValue();
6805 Scale = SubScale;
6806 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006807 }
6808 }
6809 }
6810
6811 // Otherwise, we can't look past this.
6812 Scale = 1;
6813 Offset = 0;
6814 return Val;
6815}
6816
6817
Chris Lattnerb3f83972005-10-24 06:03:58 +00006818/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6819/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006820Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006821 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006822 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006823
Chris Lattnerb53c2382005-10-24 06:22:12 +00006824 // Remove any uses of AI that are dead.
6825 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006826
Chris Lattnerb53c2382005-10-24 06:22:12 +00006827 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6828 Instruction *User = cast<Instruction>(*UI++);
6829 if (isInstructionTriviallyDead(User)) {
6830 while (UI != E && *UI == User)
6831 ++UI; // If this instruction uses AI more than once, don't break UI.
6832
Chris Lattnerb53c2382005-10-24 06:22:12 +00006833 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006834 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006835 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006836 }
6837 }
6838
Chris Lattnerb3f83972005-10-24 06:03:58 +00006839 // Get the type really allocated and the type casted to.
6840 const Type *AllocElTy = AI.getAllocatedType();
6841 const Type *CastElTy = PTy->getElementType();
6842 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006843
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006844 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6845 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006846 if (CastElTyAlign < AllocElTyAlign) return 0;
6847
Chris Lattner39387a52005-10-24 06:35:18 +00006848 // If the allocation has multiple uses, only promote it if we are strictly
6849 // increasing the alignment of the resultant allocation. If we keep it the
6850 // same, we open the door to infinite loops of various kinds.
6851 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6852
Duncan Sands514ab342007-11-01 20:53:16 +00006853 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6854 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006855 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006856
Chris Lattner455fcc82005-10-29 03:19:53 +00006857 // See if we can satisfy the modulus by pulling a scale out of the array
6858 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006859 unsigned ArraySizeScale;
6860 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006861 Value *NumElements = // See if the array size is a decomposable linear expr.
6862 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6863
Chris Lattner455fcc82005-10-29 03:19:53 +00006864 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6865 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006866 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6867 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006868
Chris Lattner455fcc82005-10-29 03:19:53 +00006869 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6870 Value *Amt = 0;
6871 if (Scale == 1) {
6872 Amt = NumElements;
6873 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006874 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006875 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6876 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006877 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006878 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006879 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006880 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006881 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006882 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006883 }
6884
Jeff Cohen86796be2007-04-04 16:58:57 +00006885 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6886 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006887 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006888 Amt = InsertNewInstBefore(Tmp, AI);
6889 }
6890
Chris Lattnerb3f83972005-10-24 06:03:58 +00006891 AllocationInst *New;
6892 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006893 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006894 else
Chris Lattner6934a042007-02-11 01:23:03 +00006895 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006896 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006897 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006898
6899 // If the allocation has multiple uses, insert a cast and change all things
6900 // that used it to use the new cast. This will also hack on CI, but it will
6901 // die soon.
6902 if (!AI.hasOneUse()) {
6903 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006904 // New is the allocation instruction, pointer typed. AI is the original
6905 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6906 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006907 InsertNewInstBefore(NewCast, AI);
6908 AI.replaceAllUsesWith(NewCast);
6909 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006910 return ReplaceInstUsesWith(CI, New);
6911}
6912
Chris Lattner70074e02006-05-13 02:06:03 +00006913/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006914/// and return it as type Ty without inserting any new casts and without
6915/// changing the computed value. This is used by code that tries to decide
6916/// whether promoting or shrinking integer operations to wider or smaller types
6917/// will allow us to eliminate a truncate or extend.
6918///
6919/// This is a truncation operation if Ty is smaller than V->getType(), or an
6920/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00006921///
6922/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6923/// should return true if trunc(V) can be computed by computing V in the smaller
6924/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6925/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6926/// efficiently truncated.
6927///
6928/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6929/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6930/// the final result.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006931bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6932 unsigned CastOpc,
6933 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006934 // We can always evaluate constants in another type.
6935 if (isa<ConstantInt>(V))
6936 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006937
6938 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006939 if (!I) return false;
6940
6941 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006942
Chris Lattner951626b2007-08-02 06:11:14 +00006943 // If this is an extension or truncate, we can often eliminate it.
6944 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6945 // If this is a cast from the destination type, we can trivially eliminate
6946 // it, and this will remove a cast overall.
6947 if (I->getOperand(0)->getType() == Ty) {
6948 // If the first operand is itself a cast, and is eliminable, do not count
6949 // this as an eliminable cast. We would prefer to eliminate those two
6950 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00006951 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00006952 ++NumCastsRemoved;
6953 return true;
6954 }
6955 }
6956
6957 // We can't extend or shrink something that has multiple uses: doing so would
6958 // require duplicating the instruction in general, which isn't profitable.
6959 if (!I->hasOneUse()) return false;
6960
Chris Lattner70074e02006-05-13 02:06:03 +00006961 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006962 case Instruction::Add:
6963 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00006964 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006965 case Instruction::And:
6966 case Instruction::Or:
6967 case Instruction::Xor:
6968 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006969 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6970 NumCastsRemoved) &&
6971 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6972 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006973
Chris Lattner46b96052006-11-29 07:18:39 +00006974 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006975 // If we are truncating the result of this SHL, and if it's a shift of a
6976 // constant amount, we can always perform a SHL in a smaller type.
6977 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006978 uint32_t BitWidth = Ty->getBitWidth();
6979 if (BitWidth < OrigTy->getBitWidth() &&
6980 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006981 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6982 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006983 }
6984 break;
6985 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006986 // If this is a truncate of a logical shr, we can truncate it to a smaller
6987 // lshr iff we know that the bits we would otherwise be shifting in are
6988 // already zeros.
6989 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006990 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6991 uint32_t BitWidth = Ty->getBitWidth();
6992 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006993 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006994 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6995 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006996 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6997 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006998 }
6999 }
Chris Lattner46b96052006-11-29 07:18:39 +00007000 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007001 case Instruction::ZExt:
7002 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007003 case Instruction::Trunc:
7004 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007005 // can safely replace it. Note that replacing it does not reduce the number
7006 // of casts in the input.
7007 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007008 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007009 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007010 case Instruction::Select: {
7011 SelectInst *SI = cast<SelectInst>(I);
7012 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7013 NumCastsRemoved) &&
7014 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7015 NumCastsRemoved);
7016 }
Chris Lattner8114b712008-06-18 04:00:49 +00007017 case Instruction::PHI: {
7018 // We can change a phi if we can change all operands.
7019 PHINode *PN = cast<PHINode>(I);
7020 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7021 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7022 NumCastsRemoved))
7023 return false;
7024 return true;
7025 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007026 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007027 // TODO: Can handle more cases here.
7028 break;
7029 }
7030
7031 return false;
7032}
7033
7034/// EvaluateInDifferentType - Given an expression that
7035/// CanEvaluateInDifferentType returns true for, actually insert the code to
7036/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007037Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007038 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007039 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007040 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007041
7042 // Otherwise, it must be an instruction.
7043 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007044 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007045 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007046 case Instruction::Add:
7047 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007048 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007049 case Instruction::And:
7050 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007051 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007052 case Instruction::AShr:
7053 case Instruction::LShr:
7054 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007055 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007056 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007057 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner8114b712008-06-18 04:00:49 +00007058 LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007059 break;
7060 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007061 case Instruction::Trunc:
7062 case Instruction::ZExt:
7063 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007064 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007065 // just return the source. There's no need to insert it because it is not
7066 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007067 if (I->getOperand(0)->getType() == Ty)
7068 return I->getOperand(0);
7069
Chris Lattner8114b712008-06-18 04:00:49 +00007070 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007071 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007072 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007073 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007074 case Instruction::Select: {
7075 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7076 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7077 Res = SelectInst::Create(I->getOperand(0), True, False);
7078 break;
7079 }
Chris Lattner8114b712008-06-18 04:00:49 +00007080 case Instruction::PHI: {
7081 PHINode *OPN = cast<PHINode>(I);
7082 PHINode *NPN = PHINode::Create(Ty);
7083 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7084 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7085 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7086 }
7087 Res = NPN;
7088 break;
7089 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007090 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007091 // TODO: Can handle more cases here.
7092 assert(0 && "Unreachable!");
7093 break;
7094 }
7095
Chris Lattner8114b712008-06-18 04:00:49 +00007096 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007097 return InsertNewInstBefore(Res, *I);
7098}
7099
Reid Spencer3da59db2006-11-27 01:05:10 +00007100/// @brief Implement the transforms common to all CastInst visitors.
7101Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007102 Value *Src = CI.getOperand(0);
7103
Dan Gohman23d9d272007-05-11 21:10:54 +00007104 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007105 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007106 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007107 if (Instruction::CastOps opc =
7108 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7109 // The first cast (CSrc) is eliminable so we need to fix up or replace
7110 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007111 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007112 }
7113 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007114
Reid Spencer3da59db2006-11-27 01:05:10 +00007115 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007116 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7117 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7118 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007119
7120 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007121 if (isa<PHINode>(Src))
7122 if (Instruction *NV = FoldOpIntoPhi(CI))
7123 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007124
Reid Spencer3da59db2006-11-27 01:05:10 +00007125 return 0;
7126}
7127
Chris Lattnerd3e28342007-04-27 17:44:50 +00007128/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7129Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7130 Value *Src = CI.getOperand(0);
7131
Chris Lattnerd3e28342007-04-27 17:44:50 +00007132 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007133 // If casting the result of a getelementptr instruction with no offset, turn
7134 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007135 if (GEP->hasAllZeroIndices()) {
7136 // Changing the cast operand is usually not a good idea but it is safe
7137 // here because the pointer operand is being replaced with another
7138 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007139 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007140 CI.setOperand(0, GEP->getOperand(0));
7141 return &CI;
7142 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007143
7144 // If the GEP has a single use, and the base pointer is a bitcast, and the
7145 // GEP computes a constant offset, see if we can convert these three
7146 // instructions into fewer. This typically happens with unions and other
7147 // non-type-safe code.
7148 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7149 if (GEP->hasAllConstantIndices()) {
7150 // We are guaranteed to get a constant from EmitGEPOffset.
7151 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7152 int64_t Offset = OffsetV->getSExtValue();
7153
7154 // Get the base pointer input of the bitcast, and the type it points to.
7155 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7156 const Type *GEPIdxTy =
7157 cast<PointerType>(OrigBase->getType())->getElementType();
7158 if (GEPIdxTy->isSized()) {
7159 SmallVector<Value*, 8> NewIndices;
7160
Chris Lattnerc42e2262007-05-05 01:59:31 +00007161 // Start with the index over the outer type. Note that the type size
7162 // might be zero (even if the offset isn't zero) if the indexed type
7163 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007164 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007165 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007166 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007167 FirstIdx = Offset/TySize;
7168 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007169
Chris Lattnerc42e2262007-05-05 01:59:31 +00007170 // Handle silly modulus not returning values values [0..TySize).
7171 if (Offset < 0) {
7172 --FirstIdx;
7173 Offset += TySize;
7174 assert(Offset >= 0);
7175 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007176 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007177 }
7178
7179 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007180
7181 // Index into the types. If we fail, set OrigBase to null.
7182 while (Offset) {
7183 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7184 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007185 if (Offset < (int64_t)SL->getSizeInBytes()) {
7186 unsigned Elt = SL->getElementContainingOffset(Offset);
7187 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007188
Chris Lattner6b6aef82007-05-15 00:16:00 +00007189 Offset -= SL->getElementOffset(Elt);
7190 GEPIdxTy = STy->getElementType(Elt);
7191 } else {
7192 // Otherwise, we can't index into this, bail out.
7193 Offset = 0;
7194 OrigBase = 0;
7195 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007196 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7197 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007198 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007199 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7200 Offset %= EltSize;
7201 } else {
7202 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7203 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007204 GEPIdxTy = STy->getElementType();
7205 } else {
7206 // Otherwise, we can't index into this, bail out.
7207 Offset = 0;
7208 OrigBase = 0;
7209 }
7210 }
7211 if (OrigBase) {
7212 // If we were able to index down into an element, create the GEP
7213 // and bitcast the result. This eliminates one bitcast, potentially
7214 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007215 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7216 NewIndices.begin(),
7217 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007218 InsertNewInstBefore(NGEP, CI);
7219 NGEP->takeName(GEP);
7220
Chris Lattner9bc14642007-04-28 00:57:34 +00007221 if (isa<BitCastInst>(CI))
7222 return new BitCastInst(NGEP, CI.getType());
7223 assert(isa<PtrToIntInst>(CI));
7224 return new PtrToIntInst(NGEP, CI.getType());
7225 }
7226 }
7227 }
7228 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007229 }
7230
7231 return commonCastTransforms(CI);
7232}
7233
7234
7235
Chris Lattnerc739cd62007-03-03 05:27:34 +00007236/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7237/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007238/// cases.
7239/// @brief Implement the transforms common to CastInst with integer operands
7240Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7241 if (Instruction *Result = commonCastTransforms(CI))
7242 return Result;
7243
7244 Value *Src = CI.getOperand(0);
7245 const Type *SrcTy = Src->getType();
7246 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007247 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7248 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007249
Reid Spencer3da59db2006-11-27 01:05:10 +00007250 // See if we can simplify any instructions used by the LHS whose sole
7251 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007252 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7253 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007254 KnownZero, KnownOne))
7255 return &CI;
7256
7257 // If the source isn't an instruction or has more than one use then we
7258 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259 Instruction *SrcI = dyn_cast<Instruction>(Src);
7260 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007261 return 0;
7262
Chris Lattnerc739cd62007-03-03 05:27:34 +00007263 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007264 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007265 if (!isa<BitCastInst>(CI) &&
7266 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007267 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007268 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007269 // eliminates the cast, so it is always a win. If this is a zero-extension,
7270 // we need to do an AND to maintain the clear top-part of the computation,
7271 // so we require that the input have eliminated at least one cast. If this
7272 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007273 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007274 bool DoXForm;
7275 switch (CI.getOpcode()) {
7276 default:
7277 // All the others use floating point so we shouldn't actually
7278 // get here because of the check above.
7279 assert(0 && "Unknown cast type");
7280 case Instruction::Trunc:
7281 DoXForm = true;
7282 break;
7283 case Instruction::ZExt:
7284 DoXForm = NumCastsRemoved >= 1;
7285 break;
7286 case Instruction::SExt:
7287 DoXForm = NumCastsRemoved >= 2;
7288 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007289 }
7290
7291 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007292 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7293 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007294 assert(Res->getType() == DestTy);
7295 switch (CI.getOpcode()) {
7296 default: assert(0 && "Unknown cast type!");
7297 case Instruction::Trunc:
7298 case Instruction::BitCast:
7299 // Just replace this cast with the result.
7300 return ReplaceInstUsesWith(CI, Res);
7301 case Instruction::ZExt: {
7302 // We need to emit an AND to clear the high bits.
7303 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007304 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7305 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007306 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007307 }
7308 case Instruction::SExt:
7309 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007310 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007311 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7312 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007313 }
7314 }
7315 }
7316
7317 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7318 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7319
7320 switch (SrcI->getOpcode()) {
7321 case Instruction::Add:
7322 case Instruction::Mul:
7323 case Instruction::And:
7324 case Instruction::Or:
7325 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007326 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007327 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7328 // Don't insert two casts if they cannot be eliminated. We allow
7329 // two casts to be inserted if the sizes are the same. This could
7330 // only be converting signedness, which is a noop.
7331 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007332 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7333 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007334 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007335 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7336 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007337 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007338 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007339 }
7340 }
7341
7342 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7343 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7344 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007345 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007346 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007347 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007348 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007349 }
7350 break;
7351 case Instruction::SDiv:
7352 case Instruction::UDiv:
7353 case Instruction::SRem:
7354 case Instruction::URem:
7355 // If we are just changing the sign, rewrite.
7356 if (DestBitSize == SrcBitSize) {
7357 // Don't insert two casts if they cannot be eliminated. We allow
7358 // two casts to be inserted if the sizes are the same. This could
7359 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007360 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7361 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007362 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7363 Op0, DestTy, SrcI);
7364 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7365 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007366 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007367 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7368 }
7369 }
7370 break;
7371
7372 case Instruction::Shl:
7373 // Allow changing the sign of the source operand. Do not allow
7374 // changing the size of the shift, UNLESS the shift amount is a
7375 // constant. We must not change variable sized shifts to a smaller
7376 // size, because it is undefined to shift more bits out than exist
7377 // in the value.
7378 if (DestBitSize == SrcBitSize ||
7379 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007380 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7381 Instruction::BitCast : Instruction::Trunc);
7382 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007383 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007384 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007385 }
7386 break;
7387 case Instruction::AShr:
7388 // If this is a signed shr, and if all bits shifted in are about to be
7389 // truncated off, turn it into an unsigned shr to allow greater
7390 // simplifications.
7391 if (DestBitSize < SrcBitSize &&
7392 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007393 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007394 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7395 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007396 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007397 }
7398 }
7399 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007400 }
7401 return 0;
7402}
7403
Chris Lattner8a9f5712007-04-11 06:57:46 +00007404Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007405 if (Instruction *Result = commonIntCastTransforms(CI))
7406 return Result;
7407
7408 Value *Src = CI.getOperand(0);
7409 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007410 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7411 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007412
7413 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7414 switch (SrcI->getOpcode()) {
7415 default: break;
7416 case Instruction::LShr:
7417 // We can shrink lshr to something smaller if we know the bits shifted in
7418 // are already zeros.
7419 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007420 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007421
7422 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007423 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007424 Value* SrcIOp0 = SrcI->getOperand(0);
7425 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007426 if (ShAmt >= DestBitWidth) // All zeros.
7427 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7428
7429 // Okay, we can shrink this. Truncate the input, then return a new
7430 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007431 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7432 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7433 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007434 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007435 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007436 } else { // This is a variable shr.
7437
7438 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7439 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7440 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007441 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007442 Value *One = ConstantInt::get(SrcI->getType(), 1);
7443
Reid Spencer832254e2007-02-02 02:16:23 +00007444 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007445 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007446 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007447 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007448 SrcI->getOperand(0),
7449 "tmp"), CI);
7450 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007451 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007452 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007453 }
7454 break;
7455 }
7456 }
7457
7458 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007459}
7460
Evan Chengb98a10e2008-03-24 00:21:34 +00007461/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7462/// in order to eliminate the icmp.
7463Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7464 bool DoXform) {
7465 // If we are just checking for a icmp eq of a single bit and zext'ing it
7466 // to an integer, then shift the bit to the appropriate place and then
7467 // cast to integer to avoid the comparison.
7468 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7469 const APInt &Op1CV = Op1C->getValue();
7470
7471 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7472 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7473 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7474 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7475 if (!DoXform) return ICI;
7476
7477 Value *In = ICI->getOperand(0);
7478 Value *Sh = ConstantInt::get(In->getType(),
7479 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007480 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007481 In->getName()+".lobit"),
7482 CI);
7483 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007484 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007485 false/*ZExt*/, "tmp", &CI);
7486
7487 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7488 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007489 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007490 In->getName()+".not"),
7491 CI);
7492 }
7493
7494 return ReplaceInstUsesWith(CI, In);
7495 }
7496
7497
7498
7499 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7500 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7501 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7502 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7503 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7504 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7505 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7506 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7507 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7508 // This only works for EQ and NE
7509 ICI->isEquality()) {
7510 // If Op1C some other power of two, convert:
7511 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7512 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7513 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7514 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7515
7516 APInt KnownZeroMask(~KnownZero);
7517 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7518 if (!DoXform) return ICI;
7519
7520 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7521 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7522 // (X&4) == 2 --> false
7523 // (X&4) != 2 --> true
7524 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7525 Res = ConstantExpr::getZExt(Res, CI.getType());
7526 return ReplaceInstUsesWith(CI, Res);
7527 }
7528
7529 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7530 Value *In = ICI->getOperand(0);
7531 if (ShiftAmt) {
7532 // Perform a logical shr by shiftamt.
7533 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007535 ConstantInt::get(In->getType(), ShiftAmt),
7536 In->getName()+".lobit"), CI);
7537 }
7538
7539 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7540 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007541 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007542 InsertNewInstBefore(cast<Instruction>(In), CI);
7543 }
7544
7545 if (CI.getType() == In->getType())
7546 return ReplaceInstUsesWith(CI, In);
7547 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007548 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007549 }
7550 }
7551 }
7552
7553 return 0;
7554}
7555
Chris Lattner8a9f5712007-04-11 06:57:46 +00007556Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007557 // If one of the common conversion will work ..
7558 if (Instruction *Result = commonIntCastTransforms(CI))
7559 return Result;
7560
7561 Value *Src = CI.getOperand(0);
7562
7563 // If this is a cast of a cast
7564 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007565 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7566 // types and if the sizes are just right we can convert this into a logical
7567 // 'and' which will be much cheaper than the pair of casts.
7568 if (isa<TruncInst>(CSrc)) {
7569 // Get the sizes of the types involved
7570 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007571 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7572 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7573 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007574 // If we're actually extending zero bits and the trunc is a no-op
7575 if (MidSize < DstSize && SrcSize == DstSize) {
7576 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007577 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007578 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007579 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007580 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007581 // Unfortunately, if the type changed, we need to cast it back.
7582 if (And->getType() != CI.getType()) {
7583 And->setName(CSrc->getName()+".mask");
7584 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007585 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007586 }
7587 return And;
7588 }
7589 }
7590 }
7591
Evan Chengb98a10e2008-03-24 00:21:34 +00007592 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7593 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007594
Evan Chengb98a10e2008-03-24 00:21:34 +00007595 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7596 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7597 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7598 // of the (zext icmp) will be transformed.
7599 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7600 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7601 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7602 (transformZExtICmp(LHS, CI, false) ||
7603 transformZExtICmp(RHS, CI, false))) {
7604 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7605 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007606 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007607 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007608 }
7609
Reid Spencer3da59db2006-11-27 01:05:10 +00007610 return 0;
7611}
7612
Chris Lattner8a9f5712007-04-11 06:57:46 +00007613Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007614 if (Instruction *I = commonIntCastTransforms(CI))
7615 return I;
7616
Chris Lattner8a9f5712007-04-11 06:57:46 +00007617 Value *Src = CI.getOperand(0);
7618
7619 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7620 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7621 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7622 // If we are just checking for a icmp eq of a single bit and zext'ing it
7623 // to an integer, then shift the bit to the appropriate place and then
7624 // cast to integer to avoid the comparison.
7625 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7626 const APInt &Op1CV = Op1C->getValue();
7627
7628 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7629 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7630 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7631 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7632 Value *In = ICI->getOperand(0);
7633 Value *Sh = ConstantInt::get(In->getType(),
7634 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007635 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007636 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007637 CI);
7638 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007639 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007640 true/*SExt*/, "tmp", &CI);
7641
7642 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007643 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007644 In->getName()+".not"), CI);
7645
7646 return ReplaceInstUsesWith(CI, In);
7647 }
7648 }
7649 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007650
7651 // See if the value being truncated is already sign extended. If so, just
7652 // eliminate the trunc/sext pair.
7653 if (getOpcode(Src) == Instruction::Trunc) {
7654 Value *Op = cast<User>(Src)->getOperand(0);
7655 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7656 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7657 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7658 unsigned NumSignBits = ComputeNumSignBits(Op);
7659
7660 if (OpBits == DestBits) {
7661 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7662 // bits, it is already ready.
7663 if (NumSignBits > DestBits-MidBits)
7664 return ReplaceInstUsesWith(CI, Op);
7665 } else if (OpBits < DestBits) {
7666 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7667 // bits, just sext from i32.
7668 if (NumSignBits > OpBits-MidBits)
7669 return new SExtInst(Op, CI.getType(), "tmp");
7670 } else {
7671 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7672 // bits, just truncate to i32.
7673 if (NumSignBits > OpBits-MidBits)
7674 return new TruncInst(Op, CI.getType(), "tmp");
7675 }
7676 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007677
Chris Lattnerba417832007-04-11 06:12:58 +00007678 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007679}
7680
Chris Lattnerb7530652008-01-27 05:29:54 +00007681/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7682/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007683static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007684 APFloat F = CFP->getValueAPF();
7685 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007686 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007687 return 0;
7688}
7689
7690/// LookThroughFPExtensions - If this is an fp extension instruction, look
7691/// through it until we get the source value.
7692static Value *LookThroughFPExtensions(Value *V) {
7693 if (Instruction *I = dyn_cast<Instruction>(V))
7694 if (I->getOpcode() == Instruction::FPExt)
7695 return LookThroughFPExtensions(I->getOperand(0));
7696
7697 // If this value is a constant, return the constant in the smallest FP type
7698 // that can accurately represent it. This allows us to turn
7699 // (float)((double)X+2.0) into x+2.0f.
7700 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7701 if (CFP->getType() == Type::PPC_FP128Ty)
7702 return V; // No constant folding of this.
7703 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007704 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007705 return V;
7706 if (CFP->getType() == Type::DoubleTy)
7707 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007708 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007709 return V;
7710 // Don't try to shrink to various long double types.
7711 }
7712
7713 return V;
7714}
7715
7716Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7717 if (Instruction *I = commonCastTransforms(CI))
7718 return I;
7719
7720 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7721 // smaller than the destination type, we can eliminate the truncate by doing
7722 // the add as the smaller type. This applies to add/sub/mul/div as well as
7723 // many builtins (sqrt, etc).
7724 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7725 if (OpI && OpI->hasOneUse()) {
7726 switch (OpI->getOpcode()) {
7727 default: break;
7728 case Instruction::Add:
7729 case Instruction::Sub:
7730 case Instruction::Mul:
7731 case Instruction::FDiv:
7732 case Instruction::FRem:
7733 const Type *SrcTy = OpI->getType();
7734 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7735 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7736 if (LHSTrunc->getType() != SrcTy &&
7737 RHSTrunc->getType() != SrcTy) {
7738 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7739 // If the source types were both smaller than the destination type of
7740 // the cast, do this xform.
7741 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7742 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7743 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7744 CI.getType(), CI);
7745 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7746 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007747 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007748 }
7749 }
7750 break;
7751 }
7752 }
7753 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007754}
7755
7756Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7757 return commonCastTransforms(CI);
7758}
7759
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007760Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7761 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7762 // mantissa to accurately represent all values of X. For example, do not
7763 // do this with i64->float->i64.
7764 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7765 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7766 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007767 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007768 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7769
7770 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007771}
7772
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007773Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7774 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7775 // mantissa to accurately represent all values of X. For example, do not
7776 // do this with i64->float->i64.
7777 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7778 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7779 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007780 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007781 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7782
7783 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007784}
7785
7786Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7787 return commonCastTransforms(CI);
7788}
7789
7790Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7791 return commonCastTransforms(CI);
7792}
7793
7794Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007795 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007796}
7797
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007798Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7799 if (Instruction *I = commonCastTransforms(CI))
7800 return I;
7801
7802 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7803 if (!DestPointee->isSized()) return 0;
7804
7805 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7806 ConstantInt *Cst;
7807 Value *X;
7808 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7809 m_ConstantInt(Cst)))) {
7810 // If the source and destination operands have the same type, see if this
7811 // is a single-index GEP.
7812 if (X->getType() == CI.getType()) {
7813 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007814 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007815
7816 // Convert the constant to intptr type.
7817 APInt Offset = Cst->getValue();
7818 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7819
7820 // If Offset is evenly divisible by Size, we can do this xform.
7821 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7822 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007823 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007824 }
7825 }
7826 // TODO: Could handle other cases, e.g. where add is indexing into field of
7827 // struct etc.
7828 } else if (CI.getOperand(0)->hasOneUse() &&
7829 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7830 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7831 // "inttoptr+GEP" instead of "add+intptr".
7832
7833 // Get the size of the pointee type.
7834 uint64_t Size = TD->getABITypeSize(DestPointee);
7835
7836 // Convert the constant to intptr type.
7837 APInt Offset = Cst->getValue();
7838 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7839
7840 // If Offset is evenly divisible by Size, we can do this xform.
7841 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7842 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7843
7844 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7845 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007846 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007847 }
7848 }
7849 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007850}
7851
Chris Lattnerd3e28342007-04-27 17:44:50 +00007852Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007853 // If the operands are integer typed then apply the integer transforms,
7854 // otherwise just apply the common ones.
7855 Value *Src = CI.getOperand(0);
7856 const Type *SrcTy = Src->getType();
7857 const Type *DestTy = CI.getType();
7858
Chris Lattner42a75512007-01-15 02:27:26 +00007859 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007860 if (Instruction *Result = commonIntCastTransforms(CI))
7861 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007862 } else if (isa<PointerType>(SrcTy)) {
7863 if (Instruction *I = commonPointerCastTransforms(CI))
7864 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007865 } else {
7866 if (Instruction *Result = commonCastTransforms(CI))
7867 return Result;
7868 }
7869
7870
7871 // Get rid of casts from one type to the same type. These are useless and can
7872 // be replaced by the operand.
7873 if (DestTy == Src->getType())
7874 return ReplaceInstUsesWith(CI, Src);
7875
Reid Spencer3da59db2006-11-27 01:05:10 +00007876 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007877 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7878 const Type *DstElTy = DstPTy->getElementType();
7879 const Type *SrcElTy = SrcPTy->getElementType();
7880
Nate Begeman83ad90a2008-03-31 00:22:16 +00007881 // If the address spaces don't match, don't eliminate the bitcast, which is
7882 // required for changing types.
7883 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7884 return 0;
7885
Chris Lattnerd3e28342007-04-27 17:44:50 +00007886 // If we are casting a malloc or alloca to a pointer to a type of the same
7887 // size, rewrite the allocation instruction to allocate the "right" type.
7888 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7889 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7890 return V;
7891
Chris Lattnerd717c182007-05-05 22:32:24 +00007892 // If the source and destination are pointers, and this cast is equivalent
7893 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007894 // This can enhance SROA and other transforms that want type-safe pointers.
7895 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7896 unsigned NumZeros = 0;
7897 while (SrcElTy != DstElTy &&
7898 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7899 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7900 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7901 ++NumZeros;
7902 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007903
Chris Lattnerd3e28342007-04-27 17:44:50 +00007904 // If we found a path from the src to dest, create the getelementptr now.
7905 if (SrcElTy == DstElTy) {
7906 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007907 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7908 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007909 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007910 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007911
Reid Spencer3da59db2006-11-27 01:05:10 +00007912 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7913 if (SVI->hasOneUse()) {
7914 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7915 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007916 if (isa<VectorType>(DestTy) &&
7917 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007918 SVI->getType()->getNumElements()) {
7919 CastInst *Tmp;
7920 // If either of the operands is a cast from CI.getType(), then
7921 // evaluating the shuffle in the casted destination's type will allow
7922 // us to eliminate at least one cast.
7923 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7924 Tmp->getOperand(0)->getType() == DestTy) ||
7925 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7926 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007927 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7928 SVI->getOperand(0), DestTy, &CI);
7929 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7930 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007931 // Return a new shuffle vector. Use the same element ID's, as we
7932 // know the vector types match #elts.
7933 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007934 }
7935 }
7936 }
7937 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007938 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007939}
7940
Chris Lattnere576b912004-04-09 23:46:01 +00007941/// GetSelectFoldableOperands - We want to turn code that looks like this:
7942/// %C = or %A, %B
7943/// %D = select %cond, %C, %A
7944/// into:
7945/// %C = select %cond, %B, 0
7946/// %D = or %A, %C
7947///
7948/// Assuming that the specified instruction is an operand to the select, return
7949/// a bitmask indicating which operands of this instruction are foldable if they
7950/// equal the other incoming value of the select.
7951///
7952static unsigned GetSelectFoldableOperands(Instruction *I) {
7953 switch (I->getOpcode()) {
7954 case Instruction::Add:
7955 case Instruction::Mul:
7956 case Instruction::And:
7957 case Instruction::Or:
7958 case Instruction::Xor:
7959 return 3; // Can fold through either operand.
7960 case Instruction::Sub: // Can only fold on the amount subtracted.
7961 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007962 case Instruction::LShr:
7963 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007964 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007965 default:
7966 return 0; // Cannot fold
7967 }
7968}
7969
7970/// GetSelectFoldableConstant - For the same transformation as the previous
7971/// function, return the identity constant that goes into the select.
7972static Constant *GetSelectFoldableConstant(Instruction *I) {
7973 switch (I->getOpcode()) {
7974 default: assert(0 && "This cannot happen!"); abort();
7975 case Instruction::Add:
7976 case Instruction::Sub:
7977 case Instruction::Or:
7978 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007979 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007980 case Instruction::LShr:
7981 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007982 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007983 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007984 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007985 case Instruction::Mul:
7986 return ConstantInt::get(I->getType(), 1);
7987 }
7988}
7989
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007990/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7991/// have the same opcode and only one use each. Try to simplify this.
7992Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7993 Instruction *FI) {
7994 if (TI->getNumOperands() == 1) {
7995 // If this is a non-volatile load or a cast from the same type,
7996 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007997 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007998 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7999 return 0;
8000 } else {
8001 return 0; // unknown unary op.
8002 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008003
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008004 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008005 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8006 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008007 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008008 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008009 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008010 }
8011
Reid Spencer832254e2007-02-02 02:16:23 +00008012 // Only handle binary operators here.
8013 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008014 return 0;
8015
8016 // Figure out if the operations have any operands in common.
8017 Value *MatchOp, *OtherOpT, *OtherOpF;
8018 bool MatchIsOpZero;
8019 if (TI->getOperand(0) == FI->getOperand(0)) {
8020 MatchOp = TI->getOperand(0);
8021 OtherOpT = TI->getOperand(1);
8022 OtherOpF = FI->getOperand(1);
8023 MatchIsOpZero = true;
8024 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8025 MatchOp = TI->getOperand(1);
8026 OtherOpT = TI->getOperand(0);
8027 OtherOpF = FI->getOperand(0);
8028 MatchIsOpZero = false;
8029 } else if (!TI->isCommutative()) {
8030 return 0;
8031 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8032 MatchOp = TI->getOperand(0);
8033 OtherOpT = TI->getOperand(1);
8034 OtherOpF = FI->getOperand(0);
8035 MatchIsOpZero = true;
8036 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8037 MatchOp = TI->getOperand(1);
8038 OtherOpT = TI->getOperand(0);
8039 OtherOpF = FI->getOperand(1);
8040 MatchIsOpZero = true;
8041 } else {
8042 return 0;
8043 }
8044
8045 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008046 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8047 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008048 InsertNewInstBefore(NewSI, SI);
8049
8050 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8051 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008052 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008053 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008054 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008055 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008056 assert(0 && "Shouldn't get here");
8057 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008058}
8059
Chris Lattner3d69f462004-03-12 05:52:32 +00008060Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008061 Value *CondVal = SI.getCondition();
8062 Value *TrueVal = SI.getTrueValue();
8063 Value *FalseVal = SI.getFalseValue();
8064
8065 // select true, X, Y -> X
8066 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008067 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008068 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008069
8070 // select C, X, X -> X
8071 if (TrueVal == FalseVal)
8072 return ReplaceInstUsesWith(SI, TrueVal);
8073
Chris Lattnere87597f2004-10-16 18:11:37 +00008074 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8075 return ReplaceInstUsesWith(SI, FalseVal);
8076 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8077 return ReplaceInstUsesWith(SI, TrueVal);
8078 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8079 if (isa<Constant>(TrueVal))
8080 return ReplaceInstUsesWith(SI, TrueVal);
8081 else
8082 return ReplaceInstUsesWith(SI, FalseVal);
8083 }
8084
Reid Spencer4fe16d62007-01-11 18:21:29 +00008085 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008086 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008087 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008088 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008089 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008090 } else {
8091 // Change: A = select B, false, C --> A = and !B, C
8092 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008093 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008094 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008095 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008096 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008097 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008098 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008099 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008100 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008101 } else {
8102 // Change: A = select B, C, true --> A = or !B, C
8103 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008104 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008105 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008106 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008107 }
8108 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008109
8110 // select a, b, a -> a&b
8111 // select a, a, b -> a|b
8112 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008113 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008114 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008115 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008116 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008117
Chris Lattner2eefe512004-04-09 19:05:30 +00008118 // Selecting between two integer constants?
8119 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8120 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008121 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008122 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008123 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008124 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008125 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008126 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008127 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008128 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008129 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008130 }
Chris Lattnerba417832007-04-11 06:12:58 +00008131
8132 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008133
Reid Spencere4d87aa2006-12-23 06:05:41 +00008134 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008135
Reid Spencere4d87aa2006-12-23 06:05:41 +00008136 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008137 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008138 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008139 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008140 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008141 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008142 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008143 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008144 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008145 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008146 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008147 InsertNewInstBefore(SRA, SI);
8148
Reid Spencer3da59db2006-11-27 01:05:10 +00008149 // Finally, convert to the type of the select RHS. We figure out
8150 // if this requires a SExt, Trunc or BitCast based on the sizes.
8151 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008152 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8153 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 if (SRASize < SISize)
8155 opc = Instruction::SExt;
8156 else if (SRASize > SISize)
8157 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008158 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008159 }
8160 }
8161
8162
8163 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008164 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008165 // non-constant value, eliminate this whole mess. This corresponds to
8166 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008167 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008168 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008169 cast<Constant>(IC->getOperand(1))->isNullValue())
8170 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8171 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008172 isa<ConstantInt>(ICA->getOperand(1)) &&
8173 (ICA->getOperand(1) == TrueValC ||
8174 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008175 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8176 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008177 // know whether we have a icmp_ne or icmp_eq and whether the
8178 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008179 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008180 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008181 Value *V = ICA;
8182 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008183 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008184 Instruction::Xor, V, ICA->getOperand(1)), SI);
8185 return ReplaceInstUsesWith(SI, V);
8186 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008187 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008188 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008189
8190 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008191 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8192 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008193 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008194 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8195 // This is not safe in general for floating point:
8196 // consider X== -0, Y== +0.
8197 // It becomes safe if either operand is a nonzero constant.
8198 ConstantFP *CFPt, *CFPf;
8199 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8200 !CFPt->getValueAPF().isZero()) ||
8201 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8202 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008203 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008204 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008205 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008206 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008207 return ReplaceInstUsesWith(SI, TrueVal);
8208 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8209
Reid Spencere4d87aa2006-12-23 06:05:41 +00008210 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008211 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008212 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8213 // This is not safe in general for floating point:
8214 // consider X== -0, Y== +0.
8215 // It becomes safe if either operand is a nonzero constant.
8216 ConstantFP *CFPt, *CFPf;
8217 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8218 !CFPt->getValueAPF().isZero()) ||
8219 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8220 !CFPf->getValueAPF().isZero()))
8221 return ReplaceInstUsesWith(SI, FalseVal);
8222 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008223 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008224 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8225 return ReplaceInstUsesWith(SI, TrueVal);
8226 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8227 }
8228 }
8229
8230 // See if we are selecting two values based on a comparison of the two values.
8231 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8232 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8233 // Transform (X == Y) ? X : Y -> Y
8234 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8235 return ReplaceInstUsesWith(SI, FalseVal);
8236 // Transform (X != Y) ? X : Y -> X
8237 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8238 return ReplaceInstUsesWith(SI, TrueVal);
8239 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8240
8241 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8242 // Transform (X == Y) ? Y : X -> X
8243 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8244 return ReplaceInstUsesWith(SI, FalseVal);
8245 // Transform (X != Y) ? Y : X -> Y
8246 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008247 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008248 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8249 }
8250 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008251
Chris Lattner87875da2005-01-13 22:52:24 +00008252 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8253 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8254 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008255 Instruction *AddOp = 0, *SubOp = 0;
8256
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008257 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8258 if (TI->getOpcode() == FI->getOpcode())
8259 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8260 return IV;
8261
8262 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8263 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008264 if (TI->getOpcode() == Instruction::Sub &&
8265 FI->getOpcode() == Instruction::Add) {
8266 AddOp = FI; SubOp = TI;
8267 } else if (FI->getOpcode() == Instruction::Sub &&
8268 TI->getOpcode() == Instruction::Add) {
8269 AddOp = TI; SubOp = FI;
8270 }
8271
8272 if (AddOp) {
8273 Value *OtherAddOp = 0;
8274 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8275 OtherAddOp = AddOp->getOperand(1);
8276 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8277 OtherAddOp = AddOp->getOperand(0);
8278 }
8279
8280 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008281 // So at this point we know we have (Y -> OtherAddOp):
8282 // select C, (add X, Y), (sub X, Z)
8283 Value *NegVal; // Compute -Z
8284 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8285 NegVal = ConstantExpr::getNeg(C);
8286 } else {
8287 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008288 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008289 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008290
8291 Value *NewTrueOp = OtherAddOp;
8292 Value *NewFalseOp = NegVal;
8293 if (AddOp != TI)
8294 std::swap(NewTrueOp, NewFalseOp);
8295 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008296 SelectInst::Create(CondVal, NewTrueOp,
8297 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008298
8299 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008300 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008301 }
8302 }
8303 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008304
Chris Lattnere576b912004-04-09 23:46:01 +00008305 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008306 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008307 // See the comment above GetSelectFoldableOperands for a description of the
8308 // transformation we are doing here.
8309 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8310 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8311 !isa<Constant>(FalseVal))
8312 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8313 unsigned OpToFold = 0;
8314 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8315 OpToFold = 1;
8316 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8317 OpToFold = 2;
8318 }
8319
8320 if (OpToFold) {
8321 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008322 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008323 SelectInst::Create(SI.getCondition(),
8324 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008325 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008326 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008328 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008329 else {
8330 assert(0 && "Unknown instruction!!");
8331 }
8332 }
8333 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008334
Chris Lattnere576b912004-04-09 23:46:01 +00008335 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8336 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8337 !isa<Constant>(TrueVal))
8338 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8339 unsigned OpToFold = 0;
8340 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8341 OpToFold = 1;
8342 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8343 OpToFold = 2;
8344 }
8345
8346 if (OpToFold) {
8347 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008348 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008349 SelectInst::Create(SI.getCondition(), C,
8350 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008351 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008352 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008353 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008354 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008355 else
Chris Lattnere576b912004-04-09 23:46:01 +00008356 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008357 }
8358 }
8359 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008360
8361 if (BinaryOperator::isNot(CondVal)) {
8362 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8363 SI.setOperand(1, FalseVal);
8364 SI.setOperand(2, TrueVal);
8365 return &SI;
8366 }
8367
Chris Lattner3d69f462004-03-12 05:52:32 +00008368 return 0;
8369}
8370
Dan Gohmaneee962e2008-04-10 18:43:06 +00008371/// EnforceKnownAlignment - If the specified pointer points to an object that
8372/// we control, modify the object's alignment to PrefAlign. This isn't
8373/// often possible though. If alignment is important, a more reliable approach
8374/// is to simply align all global variables and allocation instructions to
8375/// their preferred alignment from the beginning.
8376///
8377static unsigned EnforceKnownAlignment(Value *V,
8378 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008379
Dan Gohmaneee962e2008-04-10 18:43:06 +00008380 User *U = dyn_cast<User>(V);
8381 if (!U) return Align;
8382
8383 switch (getOpcode(U)) {
8384 default: break;
8385 case Instruction::BitCast:
8386 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8387 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008388 // If all indexes are zero, it is just the alignment of the base pointer.
8389 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008390 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008391 if (!isa<Constant>(*i) ||
8392 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008393 AllZeroOperands = false;
8394 break;
8395 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008396
8397 if (AllZeroOperands) {
8398 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008399 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008400 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008401 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008402 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008403 }
8404
8405 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8406 // If there is a large requested alignment and we can, bump up the alignment
8407 // of the global.
8408 if (!GV->isDeclaration()) {
8409 GV->setAlignment(PrefAlign);
8410 Align = PrefAlign;
8411 }
8412 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8413 // If there is a requested alignment and if this is an alloca, round up. We
8414 // don't do this for malloc, because some systems can't respect the request.
8415 if (isa<AllocaInst>(AI)) {
8416 AI->setAlignment(PrefAlign);
8417 Align = PrefAlign;
8418 }
8419 }
8420
8421 return Align;
8422}
8423
8424/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8425/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8426/// and it is more than the alignment of the ultimate object, see if we can
8427/// increase the alignment of the ultimate object, making this check succeed.
8428unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8429 unsigned PrefAlign) {
8430 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8431 sizeof(PrefAlign) * CHAR_BIT;
8432 APInt Mask = APInt::getAllOnesValue(BitWidth);
8433 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8434 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8435 unsigned TrailZ = KnownZero.countTrailingOnes();
8436 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8437
8438 if (PrefAlign > Align)
8439 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8440
8441 // We don't need to make any adjustment.
8442 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008443}
8444
Chris Lattnerf497b022008-01-13 23:50:23 +00008445Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008446 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8447 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008448 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8449 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8450
8451 if (CopyAlign < MinAlign) {
8452 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8453 return MI;
8454 }
8455
8456 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8457 // load/store.
8458 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8459 if (MemOpLength == 0) return 0;
8460
Chris Lattner37ac6082008-01-14 00:28:35 +00008461 // Source and destination pointer types are always "i8*" for intrinsic. See
8462 // if the size is something we can handle with a single primitive load/store.
8463 // A single load+store correctly handles overlapping memory in the memmove
8464 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008465 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008466 if (Size == 0) return MI; // Delete this mem transfer.
8467
8468 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008469 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008470
Chris Lattner37ac6082008-01-14 00:28:35 +00008471 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008472 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008473
8474 // Memcpy forces the use of i8* for the source and destination. That means
8475 // that if you're using memcpy to move one double around, you'll get a cast
8476 // from double* to i8*. We'd much rather use a double load+store rather than
8477 // an i64 load+store, here because this improves the odds that the source or
8478 // dest address will be promotable. See if we can find a better type than the
8479 // integer datatype.
8480 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8481 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8482 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8483 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8484 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008485 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008486 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8487 if (STy->getNumElements() == 1)
8488 SrcETy = STy->getElementType(0);
8489 else
8490 break;
8491 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8492 if (ATy->getNumElements() == 1)
8493 SrcETy = ATy->getElementType();
8494 else
8495 break;
8496 } else
8497 break;
8498 }
8499
Dan Gohman8f8e2692008-05-23 01:52:21 +00008500 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008501 NewPtrTy = PointerType::getUnqual(SrcETy);
8502 }
8503 }
8504
8505
Chris Lattnerf497b022008-01-13 23:50:23 +00008506 // If the memcpy/memmove provides better alignment info than we can
8507 // infer, use it.
8508 SrcAlign = std::max(SrcAlign, CopyAlign);
8509 DstAlign = std::max(DstAlign, CopyAlign);
8510
8511 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8512 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008513 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8514 InsertNewInstBefore(L, *MI);
8515 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8516
8517 // Set the size of the copy to 0, it will be deleted on the next iteration.
8518 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8519 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008520}
Chris Lattner3d69f462004-03-12 05:52:32 +00008521
Chris Lattner69ea9d22008-04-30 06:39:11 +00008522Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8523 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8524 if (MI->getAlignment()->getZExtValue() < Alignment) {
8525 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8526 return MI;
8527 }
8528
8529 // Extract the length and alignment and fill if they are constant.
8530 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8531 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8532 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8533 return 0;
8534 uint64_t Len = LenC->getZExtValue();
8535 Alignment = MI->getAlignment()->getZExtValue();
8536
8537 // If the length is zero, this is a no-op
8538 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8539
8540 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8541 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8542 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8543
8544 Value *Dest = MI->getDest();
8545 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8546
8547 // Alignment 0 is identity for alignment 1 for memset, but not store.
8548 if (Alignment == 0) Alignment = 1;
8549
8550 // Extract the fill value and store.
8551 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8552 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8553 Alignment), *MI);
8554
8555 // Set the size of the copy to 0, it will be deleted on the next iteration.
8556 MI->setLength(Constant::getNullValue(LenC->getType()));
8557 return MI;
8558 }
8559
8560 return 0;
8561}
8562
8563
Chris Lattner8b0ea312006-01-13 20:11:04 +00008564/// visitCallInst - CallInst simplification. This mostly only handles folding
8565/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8566/// the heavy lifting.
8567///
Chris Lattner9fe38862003-06-19 17:00:31 +00008568Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008569 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8570 if (!II) return visitCallSite(&CI);
8571
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008572 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8573 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008574 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008575 bool Changed = false;
8576
8577 // memmove/cpy/set of zero bytes is a noop.
8578 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8579 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8580
Chris Lattner35b9e482004-10-12 04:52:52 +00008581 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008582 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008583 // Replace the instruction with just byte operations. We would
8584 // transform other cases to loads/stores, but we don't know if
8585 // alignment is sufficient.
8586 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008587 }
8588
Chris Lattner35b9e482004-10-12 04:52:52 +00008589 // If we have a memmove and the source operation is a constant global,
8590 // then the source and dest pointers can't alias, so we can change this
8591 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008592 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008593 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8594 if (GVSrc->isConstant()) {
8595 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008596 Intrinsic::ID MemCpyID;
8597 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8598 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008599 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008600 MemCpyID = Intrinsic::memcpy_i64;
8601 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008602 Changed = true;
8603 }
Chris Lattnera935db82008-05-28 05:30:41 +00008604
8605 // memmove(x,x,size) -> noop.
8606 if (MMI->getSource() == MMI->getDest())
8607 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008608 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008609
Chris Lattner95a959d2006-03-06 20:18:44 +00008610 // If we can determine a pointer alignment that is bigger than currently
8611 // set, update the alignment.
8612 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008613 if (Instruction *I = SimplifyMemTransfer(MI))
8614 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008615 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8616 if (Instruction *I = SimplifyMemSet(MSI))
8617 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008618 }
8619
Chris Lattner8b0ea312006-01-13 20:11:04 +00008620 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00008621 }
8622
8623 switch (II->getIntrinsicID()) {
8624 default: break;
8625 case Intrinsic::bswap:
8626 // bswap(bswap(x)) -> x
8627 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8628 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8629 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8630 break;
8631 case Intrinsic::ppc_altivec_lvx:
8632 case Intrinsic::ppc_altivec_lvxl:
8633 case Intrinsic::x86_sse_loadu_ps:
8634 case Intrinsic::x86_sse2_loadu_pd:
8635 case Intrinsic::x86_sse2_loadu_dq:
8636 // Turn PPC lvx -> load if the pointer is known aligned.
8637 // Turn X86 loadups -> load if the pointer is known aligned.
8638 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8639 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8640 PointerType::getUnqual(II->getType()),
8641 CI);
8642 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00008643 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008644 break;
8645 case Intrinsic::ppc_altivec_stvx:
8646 case Intrinsic::ppc_altivec_stvxl:
8647 // Turn stvx -> store if the pointer is known aligned.
8648 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8649 const Type *OpPtrTy =
8650 PointerType::getUnqual(II->getOperand(1)->getType());
8651 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8652 return new StoreInst(II->getOperand(1), Ptr);
8653 }
8654 break;
8655 case Intrinsic::x86_sse_storeu_ps:
8656 case Intrinsic::x86_sse2_storeu_pd:
8657 case Intrinsic::x86_sse2_storeu_dq:
8658 case Intrinsic::x86_sse2_storel_dq:
8659 // Turn X86 storeu -> store if the pointer is known aligned.
8660 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8661 const Type *OpPtrTy =
8662 PointerType::getUnqual(II->getOperand(2)->getType());
8663 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8664 return new StoreInst(II->getOperand(2), Ptr);
8665 }
8666 break;
8667
8668 case Intrinsic::x86_sse_cvttss2si: {
8669 // These intrinsics only demands the 0th element of its input vector. If
8670 // we can simplify the input based on that, do so now.
8671 uint64_t UndefElts;
8672 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8673 UndefElts)) {
8674 II->setOperand(1, V);
8675 return II;
8676 }
8677 break;
8678 }
8679
8680 case Intrinsic::ppc_altivec_vperm:
8681 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8682 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8683 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00008684
Chris Lattner0521e3c2008-06-18 04:33:20 +00008685 // Check that all of the elements are integer constants or undefs.
8686 bool AllEltsOk = true;
8687 for (unsigned i = 0; i != 16; ++i) {
8688 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8689 !isa<UndefValue>(Mask->getOperand(i))) {
8690 AllEltsOk = false;
8691 break;
8692 }
8693 }
8694
8695 if (AllEltsOk) {
8696 // Cast the input vectors to byte vectors.
8697 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8698 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8699 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008700
Chris Lattner0521e3c2008-06-18 04:33:20 +00008701 // Only extract each element once.
8702 Value *ExtractedElts[32];
8703 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8704
Chris Lattnere2ed0572006-04-06 19:19:17 +00008705 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00008706 if (isa<UndefValue>(Mask->getOperand(i)))
8707 continue;
8708 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8709 Idx &= 31; // Match the hardware behavior.
8710
8711 if (ExtractedElts[Idx] == 0) {
8712 Instruction *Elt =
8713 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8714 InsertNewInstBefore(Elt, CI);
8715 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008716 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00008717
Chris Lattner0521e3c2008-06-18 04:33:20 +00008718 // Insert this value into the result vector.
8719 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8720 i, "tmp");
8721 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008722 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008723 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008724 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008725 }
8726 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008727
Chris Lattner0521e3c2008-06-18 04:33:20 +00008728 case Intrinsic::stackrestore: {
8729 // If the save is right next to the restore, remove the restore. This can
8730 // happen when variable allocas are DCE'd.
8731 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8732 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8733 BasicBlock::iterator BI = SS;
8734 if (&*++BI == II)
8735 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008736 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008737 }
8738
8739 // Scan down this block to see if there is another stack restore in the
8740 // same block without an intervening call/alloca.
8741 BasicBlock::iterator BI = II;
8742 TerminatorInst *TI = II->getParent()->getTerminator();
8743 bool CannotRemove = false;
8744 for (++BI; &*BI != TI; ++BI) {
8745 if (isa<AllocaInst>(BI)) {
8746 CannotRemove = true;
8747 break;
8748 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00008749 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8750 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8751 // If there is a stackrestore below this one, remove this one.
8752 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8753 return EraseInstFromFunction(CI);
8754 // Otherwise, ignore the intrinsic.
8755 } else {
8756 // If we found a non-intrinsic call, we can't remove the stack
8757 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008758 CannotRemove = true;
8759 break;
8760 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008761 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008762 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008763
8764 // If the stack restore is in a return/unwind block and if there are no
8765 // allocas or calls between the restore and the return, nuke the restore.
8766 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8767 return EraseInstFromFunction(CI);
8768 break;
8769 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008770 }
8771
Chris Lattner8b0ea312006-01-13 20:11:04 +00008772 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008773}
8774
8775// InvokeInst simplification
8776//
8777Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008778 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008779}
8780
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008781/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8782/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008783static bool isSafeToEliminateVarargsCast(const CallSite CS,
8784 const CastInst * const CI,
8785 const TargetData * const TD,
8786 const int ix) {
8787 if (!CI->isLosslessCast())
8788 return false;
8789
8790 // The size of ByVal arguments is derived from the type, so we
8791 // can't change to a type with a different size. If the size were
8792 // passed explicitly we could avoid this check.
8793 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8794 return true;
8795
8796 const Type* SrcTy =
8797 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8798 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8799 if (!SrcTy->isSized() || !DstTy->isSized())
8800 return false;
8801 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8802 return false;
8803 return true;
8804}
8805
Chris Lattnera44d8a22003-10-07 22:32:43 +00008806// visitCallSite - Improvements for call and invoke instructions.
8807//
8808Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008809 bool Changed = false;
8810
8811 // If the callee is a constexpr cast of a function, attempt to move the cast
8812 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008813 if (transformConstExprCastCall(CS)) return 0;
8814
Chris Lattner6c266db2003-10-07 22:54:13 +00008815 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008816
Chris Lattner08b22ec2005-05-13 07:09:09 +00008817 if (Function *CalleeF = dyn_cast<Function>(Callee))
8818 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8819 Instruction *OldCall = CS.getInstruction();
8820 // If the call and callee calling conventions don't match, this call must
8821 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008822 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008823 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8824 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008825 if (!OldCall->use_empty())
8826 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8827 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8828 return EraseInstFromFunction(*OldCall);
8829 return 0;
8830 }
8831
Chris Lattner17be6352004-10-18 02:59:09 +00008832 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8833 // This instruction is not reachable, just remove it. We insert a store to
8834 // undef so that we know that this code is not reachable, despite the fact
8835 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008836 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008837 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008838 CS.getInstruction());
8839
8840 if (!CS.getInstruction()->use_empty())
8841 CS.getInstruction()->
8842 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8843
8844 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8845 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008846 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8847 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008848 }
Chris Lattner17be6352004-10-18 02:59:09 +00008849 return EraseInstFromFunction(*CS.getInstruction());
8850 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008851
Duncan Sandscdb6d922007-09-17 10:26:40 +00008852 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8853 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8854 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8855 return transformCallThroughTrampoline(CS);
8856
Chris Lattner6c266db2003-10-07 22:54:13 +00008857 const PointerType *PTy = cast<PointerType>(Callee->getType());
8858 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8859 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008860 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008861 // See if we can optimize any arguments passed through the varargs area of
8862 // the call.
8863 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008864 E = CS.arg_end(); I != E; ++I, ++ix) {
8865 CastInst *CI = dyn_cast<CastInst>(*I);
8866 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8867 *I = CI->getOperand(0);
8868 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008869 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008870 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008871 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008872
Duncan Sandsf0c33542007-12-19 21:13:37 +00008873 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008874 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008875 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008876 Changed = true;
8877 }
8878
Chris Lattner6c266db2003-10-07 22:54:13 +00008879 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008880}
8881
Chris Lattner9fe38862003-06-19 17:00:31 +00008882// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8883// attempt to move the cast to the arguments of the call/invoke.
8884//
8885bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8886 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8887 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008888 if (CE->getOpcode() != Instruction::BitCast ||
8889 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008890 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008891 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008892 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008893 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008894
8895 // Okay, this is a cast from a function to a different type. Unless doing so
8896 // would cause a type conversion of one of our arguments, change this call to
8897 // be a direct call with arguments casted to the appropriate types.
8898 //
8899 const FunctionType *FT = Callee->getFunctionType();
8900 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008901 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008902
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008903 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008904 return false; // TODO: Handle multiple return values.
8905
Chris Lattnerf78616b2004-01-14 06:06:08 +00008906 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008907 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008908 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008909 // Conversion is ok if changing from one pointer type to another or from
8910 // a pointer to an integer of the same size.
8911 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00008912 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00008913 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008914
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008915 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008916 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008917 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008918 return false; // Cannot transform this return value.
8919
Chris Lattner58d74912008-03-12 17:45:29 +00008920 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8921 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008922 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008923 return false; // Attribute not compatible with transformed value.
8924 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008925
Chris Lattnerf78616b2004-01-14 06:06:08 +00008926 // If the callsite is an invoke instruction, and the return value is used by
8927 // a PHI node in a successor, we cannot change the return type of the call
8928 // because there is no place to put the cast instruction (without breaking
8929 // the critical edge). Bail out in this case.
8930 if (!Caller->use_empty())
8931 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8932 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8933 UI != E; ++UI)
8934 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8935 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008936 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008937 return false;
8938 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008939
8940 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8941 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008942
Chris Lattner9fe38862003-06-19 17:00:31 +00008943 CallSite::arg_iterator AI = CS.arg_begin();
8944 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8945 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008946 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008947
8948 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008949 return false; // Cannot transform this parameter value.
8950
Chris Lattner58d74912008-03-12 17:45:29 +00008951 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8952 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008953
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008954 // Converting from one pointer type to another or between a pointer and an
8955 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008956 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008957 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8958 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008959 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008960 }
8961
8962 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008963 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008964 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008965
Chris Lattner58d74912008-03-12 17:45:29 +00008966 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8967 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008968 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008969 // won't be dropping them. Check that these extra arguments have attributes
8970 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008971 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8972 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008973 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008974 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008975 if (PAttrs & ParamAttr::VarArgsIncompatible)
8976 return false;
8977 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008978
Chris Lattner9fe38862003-06-19 17:00:31 +00008979 // Okay, we decided that this is a safe thing to do: go ahead and start
8980 // inserting cast instructions as necessary...
8981 std::vector<Value*> Args;
8982 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008983 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008984 attrVec.reserve(NumCommonArgs);
8985
8986 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008987 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008988
8989 // If the return value is not being used, the type may not be compatible
8990 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008991 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008992
8993 // Add the new return attributes.
8994 if (RAttrs)
8995 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008996
8997 AI = CS.arg_begin();
8998 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8999 const Type *ParamTy = FT->getParamType(i);
9000 if ((*AI)->getType() == ParamTy) {
9001 Args.push_back(*AI);
9002 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009003 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009004 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009005 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009006 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009007 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009008
9009 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009010 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009011 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009012 }
9013
9014 // If the function takes more arguments than the call was taking, add them
9015 // now...
9016 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9017 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9018
9019 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009020 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009021 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009022 cerr << "WARNING: While resolving call to function '"
9023 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009024 } else {
9025 // Add all of the arguments in their promoted form to the arg list...
9026 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9027 const Type *PTy = getPromotedType((*AI)->getType());
9028 if (PTy != (*AI)->getType()) {
9029 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009030 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9031 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009032 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009033 InsertNewInstBefore(Cast, *Caller);
9034 Args.push_back(Cast);
9035 } else {
9036 Args.push_back(*AI);
9037 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009038
Duncan Sandse1e520f2008-01-13 08:02:44 +00009039 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009040 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009041 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9042 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009043 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009044 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009045
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009046 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009047 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009048
Chris Lattner58d74912008-03-12 17:45:29 +00009049 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009050
Chris Lattner9fe38862003-06-19 17:00:31 +00009051 Instruction *NC;
9052 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009053 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009054 Args.begin(), Args.end(),
9055 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009056 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009057 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009058 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009059 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9060 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009061 CallInst *CI = cast<CallInst>(Caller);
9062 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009063 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009064 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009065 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009066 }
9067
Chris Lattner6934a042007-02-11 01:23:03 +00009068 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009069 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009070 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009071 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009072 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009073 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009074 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009075
9076 // If this is an invoke instruction, we should insert it after the first
9077 // non-phi, instruction in the normal successor block.
9078 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009079 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009080 InsertNewInstBefore(NC, *I);
9081 } else {
9082 // Otherwise, it's a call, just insert cast right after the call instr
9083 InsertNewInstBefore(NC, *Caller);
9084 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009085 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009086 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009087 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009088 }
9089 }
9090
9091 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9092 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009093 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009094 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009095 return true;
9096}
9097
Duncan Sandscdb6d922007-09-17 10:26:40 +00009098// transformCallThroughTrampoline - Turn a call to a function created by the
9099// init_trampoline intrinsic into a direct call to the underlying function.
9100//
9101Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9102 Value *Callee = CS.getCalledValue();
9103 const PointerType *PTy = cast<PointerType>(Callee->getType());
9104 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009105 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009106
9107 // If the call already has the 'nest' attribute somewhere then give up -
9108 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009109 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009110 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009111
9112 IntrinsicInst *Tramp =
9113 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9114
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009115 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009116 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9117 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9118
Chris Lattner58d74912008-03-12 17:45:29 +00009119 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9120 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009121 unsigned NestIdx = 1;
9122 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009123 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009124
9125 // Look for a parameter marked with the 'nest' attribute.
9126 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9127 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009128 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009129 // Record the parameter type and any other attributes.
9130 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009131 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009132 break;
9133 }
9134
9135 if (NestTy) {
9136 Instruction *Caller = CS.getInstruction();
9137 std::vector<Value*> NewArgs;
9138 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9139
Chris Lattner58d74912008-03-12 17:45:29 +00009140 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9141 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009142
Duncan Sandscdb6d922007-09-17 10:26:40 +00009143 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009144 // mean appending it. Likewise for attributes.
9145
9146 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009147 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9148 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009149
Duncan Sandscdb6d922007-09-17 10:26:40 +00009150 {
9151 unsigned Idx = 1;
9152 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9153 do {
9154 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009155 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009156 Value *NestVal = Tramp->getOperand(3);
9157 if (NestVal->getType() != NestTy)
9158 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9159 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009160 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009161 }
9162
9163 if (I == E)
9164 break;
9165
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009166 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009167 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009168 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009169 NewAttrs.push_back
9170 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009171
9172 ++Idx, ++I;
9173 } while (1);
9174 }
9175
9176 // The trampoline may have been bitcast to a bogus type (FTy).
9177 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009178 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009179
Duncan Sandscdb6d922007-09-17 10:26:40 +00009180 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009181 NewTypes.reserve(FTy->getNumParams()+1);
9182
Duncan Sandscdb6d922007-09-17 10:26:40 +00009183 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009184 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009185 {
9186 unsigned Idx = 1;
9187 FunctionType::param_iterator I = FTy->param_begin(),
9188 E = FTy->param_end();
9189
9190 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009191 if (Idx == NestIdx)
9192 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009193 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009194
9195 if (I == E)
9196 break;
9197
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009198 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009199 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009200
9201 ++Idx, ++I;
9202 } while (1);
9203 }
9204
9205 // Replace the trampoline call with a direct call. Let the generic
9206 // code sort out any function type mismatches.
9207 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009208 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009209 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9210 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009211 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009212
9213 Instruction *NewCaller;
9214 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009215 NewCaller = InvokeInst::Create(NewCallee,
9216 II->getNormalDest(), II->getUnwindDest(),
9217 NewArgs.begin(), NewArgs.end(),
9218 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009219 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009220 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009221 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009222 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9223 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009224 if (cast<CallInst>(Caller)->isTailCall())
9225 cast<CallInst>(NewCaller)->setTailCall();
9226 cast<CallInst>(NewCaller)->
9227 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009228 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009229 }
9230 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9231 Caller->replaceAllUsesWith(NewCaller);
9232 Caller->eraseFromParent();
9233 RemoveFromWorkList(Caller);
9234 return 0;
9235 }
9236 }
9237
9238 // Replace the trampoline call with a direct call. Since there is no 'nest'
9239 // parameter, there is no need to adjust the argument list. Let the generic
9240 // code sort out any function type mismatches.
9241 Constant *NewCallee =
9242 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9243 CS.setCalledFunction(NewCallee);
9244 return CS.getInstruction();
9245}
9246
Chris Lattner7da52b22006-11-01 04:51:18 +00009247/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9248/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9249/// and a single binop.
9250Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9251 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009252 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9253 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009254 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009255 Value *LHSVal = FirstInst->getOperand(0);
9256 Value *RHSVal = FirstInst->getOperand(1);
9257
9258 const Type *LHSType = LHSVal->getType();
9259 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009260
9261 // Scan to see if all operands are the same opcode, all have one use, and all
9262 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009263 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009264 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009265 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009266 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009267 // types or GEP's with different index types.
9268 I->getOperand(0)->getType() != LHSType ||
9269 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009270 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009271
9272 // If they are CmpInst instructions, check their predicates
9273 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9274 if (cast<CmpInst>(I)->getPredicate() !=
9275 cast<CmpInst>(FirstInst)->getPredicate())
9276 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009277
9278 // Keep track of which operand needs a phi node.
9279 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9280 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009281 }
9282
Chris Lattner53738a42006-11-08 19:42:28 +00009283 // Otherwise, this is safe to transform, determine if it is profitable.
9284
9285 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9286 // Indexes are often folded into load/store instructions, so we don't want to
9287 // hide them behind a phi.
9288 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9289 return 0;
9290
Chris Lattner7da52b22006-11-01 04:51:18 +00009291 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009292 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009293 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009294 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009295 NewLHS = PHINode::Create(LHSType,
9296 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009297 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9298 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009299 InsertNewInstBefore(NewLHS, PN);
9300 LHSVal = NewLHS;
9301 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009302
9303 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009304 NewRHS = PHINode::Create(RHSType,
9305 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009306 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9307 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009308 InsertNewInstBefore(NewRHS, PN);
9309 RHSVal = NewRHS;
9310 }
9311
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009312 // Add all operands to the new PHIs.
9313 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9314 if (NewLHS) {
9315 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9316 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9317 }
9318 if (NewRHS) {
9319 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9320 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9321 }
9322 }
9323
Chris Lattner7da52b22006-11-01 04:51:18 +00009324 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009325 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009326 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009327 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009328 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009329 else {
9330 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009331 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009332 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009333}
9334
Chris Lattner76c73142006-11-01 07:13:54 +00009335/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9336/// of the block that defines it. This means that it must be obvious the value
9337/// of the load is not changed from the point of the load to the end of the
9338/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009339///
9340/// Finally, it is safe, but not profitable, to sink a load targetting a
9341/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9342/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009343static bool isSafeToSinkLoad(LoadInst *L) {
9344 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9345
9346 for (++BBI; BBI != E; ++BBI)
9347 if (BBI->mayWriteToMemory())
9348 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009349
9350 // Check for non-address taken alloca. If not address-taken already, it isn't
9351 // profitable to do this xform.
9352 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9353 bool isAddressTaken = false;
9354 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9355 UI != E; ++UI) {
9356 if (isa<LoadInst>(UI)) continue;
9357 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9358 // If storing TO the alloca, then the address isn't taken.
9359 if (SI->getOperand(1) == AI) continue;
9360 }
9361 isAddressTaken = true;
9362 break;
9363 }
9364
9365 if (!isAddressTaken)
9366 return false;
9367 }
9368
Chris Lattner76c73142006-11-01 07:13:54 +00009369 return true;
9370}
9371
Chris Lattner9fe38862003-06-19 17:00:31 +00009372
Chris Lattnerbac32862004-11-14 19:13:23 +00009373// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9374// operator and they all are only used by the PHI, PHI together their
9375// inputs, and do the operation once, to the result of the PHI.
9376Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9377 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9378
9379 // Scan the instruction, looking for input operations that can be folded away.
9380 // If all input operands to the phi are the same instruction (e.g. a cast from
9381 // the same type or "+42") we can pull the operation through the PHI, reducing
9382 // code size and simplifying code.
9383 Constant *ConstantOp = 0;
9384 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009385 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009386 if (isa<CastInst>(FirstInst)) {
9387 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009388 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009389 // Can fold binop, compare or shift here if the RHS is a constant,
9390 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009391 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009392 if (ConstantOp == 0)
9393 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009394 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9395 isVolatile = LI->isVolatile();
9396 // We can't sink the load if the loaded value could be modified between the
9397 // load and the PHI.
9398 if (LI->getParent() != PN.getIncomingBlock(0) ||
9399 !isSafeToSinkLoad(LI))
9400 return 0;
Chris Lattner71042962008-07-08 17:18:32 +00009401
9402 // If the PHI is of volatile loads and the load block has multiple
9403 // successors, sinking it would remove a load of the volatile value from
9404 // the path through the other successor.
9405 if (isVolatile &&
9406 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9407 return 0;
9408
Chris Lattner9c080502006-11-01 07:43:41 +00009409 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009410 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009411 return FoldPHIArgBinOpIntoPHI(PN);
9412 // Can't handle general GEPs yet.
9413 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009414 } else {
9415 return 0; // Cannot fold this operation.
9416 }
9417
9418 // Check to see if all arguments are the same operation.
9419 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9420 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9421 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009422 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009423 return 0;
9424 if (CastSrcTy) {
9425 if (I->getOperand(0)->getType() != CastSrcTy)
9426 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009427 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009428 // We can't sink the load if the loaded value could be modified between
9429 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009430 if (LI->isVolatile() != isVolatile ||
9431 LI->getParent() != PN.getIncomingBlock(i) ||
9432 !isSafeToSinkLoad(LI))
9433 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009434
Chris Lattner71042962008-07-08 17:18:32 +00009435 // If the PHI is of volatile loads and the load block has multiple
9436 // successors, sinking it would remove a load of the volatile value from
9437 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +00009438 if (isVolatile &&
9439 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9440 return 0;
9441
9442
Chris Lattnerbac32862004-11-14 19:13:23 +00009443 } else if (I->getOperand(1) != ConstantOp) {
9444 return 0;
9445 }
9446 }
9447
9448 // Okay, they are all the same operation. Create a new PHI node of the
9449 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009450 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9451 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009452 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009453
9454 Value *InVal = FirstInst->getOperand(0);
9455 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009456
9457 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009458 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9459 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9460 if (NewInVal != InVal)
9461 InVal = 0;
9462 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9463 }
9464
9465 Value *PhiVal;
9466 if (InVal) {
9467 // The new PHI unions all of the same values together. This is really
9468 // common, so we handle it intelligently here for compile-time speed.
9469 PhiVal = InVal;
9470 delete NewPN;
9471 } else {
9472 InsertNewInstBefore(NewPN, PN);
9473 PhiVal = NewPN;
9474 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009475
Chris Lattnerbac32862004-11-14 19:13:23 +00009476 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009477 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009478 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009479 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009480 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009481 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009482 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009483 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009484 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9485
9486 // If this was a volatile load that we are merging, make sure to loop through
9487 // and mark all the input loads as non-volatile. If we don't do this, we will
9488 // insert a new volatile load and the old ones will not be deletable.
9489 if (isVolatile)
9490 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9491 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9492
9493 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009494}
Chris Lattnera1be5662002-05-02 17:06:02 +00009495
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009496/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9497/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009498static bool DeadPHICycle(PHINode *PN,
9499 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009500 if (PN->use_empty()) return true;
9501 if (!PN->hasOneUse()) return false;
9502
9503 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009504 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009505 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009506
9507 // Don't scan crazily complex things.
9508 if (PotentiallyDeadPHIs.size() == 16)
9509 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009510
9511 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9512 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009513
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009514 return false;
9515}
9516
Chris Lattnercf5008a2007-11-06 21:52:06 +00009517/// PHIsEqualValue - Return true if this phi node is always equal to
9518/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9519/// z = some value; x = phi (y, z); y = phi (x, z)
9520static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9521 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9522 // See if we already saw this PHI node.
9523 if (!ValueEqualPHIs.insert(PN))
9524 return true;
9525
9526 // Don't scan crazily complex things.
9527 if (ValueEqualPHIs.size() == 16)
9528 return false;
9529
9530 // Scan the operands to see if they are either phi nodes or are equal to
9531 // the value.
9532 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9533 Value *Op = PN->getIncomingValue(i);
9534 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9535 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9536 return false;
9537 } else if (Op != NonPhiInVal)
9538 return false;
9539 }
9540
9541 return true;
9542}
9543
9544
Chris Lattner473945d2002-05-06 18:06:38 +00009545// PHINode simplification
9546//
Chris Lattner7e708292002-06-25 16:13:24 +00009547Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009548 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009549 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009550
Owen Anderson7e057142006-07-10 22:03:18 +00009551 if (Value *V = PN.hasConstantValue())
9552 return ReplaceInstUsesWith(PN, V);
9553
Owen Anderson7e057142006-07-10 22:03:18 +00009554 // If all PHI operands are the same operation, pull them through the PHI,
9555 // reducing code size.
9556 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9557 PN.getIncomingValue(0)->hasOneUse())
9558 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9559 return Result;
9560
9561 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9562 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9563 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009564 if (PN.hasOneUse()) {
9565 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9566 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009567 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009568 PotentiallyDeadPHIs.insert(&PN);
9569 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9570 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9571 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009572
9573 // If this phi has a single use, and if that use just computes a value for
9574 // the next iteration of a loop, delete the phi. This occurs with unused
9575 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9576 // common case here is good because the only other things that catch this
9577 // are induction variable analysis (sometimes) and ADCE, which is only run
9578 // late.
9579 if (PHIUser->hasOneUse() &&
9580 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9581 PHIUser->use_back() == &PN) {
9582 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9583 }
9584 }
Owen Anderson7e057142006-07-10 22:03:18 +00009585
Chris Lattnercf5008a2007-11-06 21:52:06 +00009586 // We sometimes end up with phi cycles that non-obviously end up being the
9587 // same value, for example:
9588 // z = some value; x = phi (y, z); y = phi (x, z)
9589 // where the phi nodes don't necessarily need to be in the same block. Do a
9590 // quick check to see if the PHI node only contains a single non-phi value, if
9591 // so, scan to see if the phi cycle is actually equal to that value.
9592 {
9593 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9594 // Scan for the first non-phi operand.
9595 while (InValNo != NumOperandVals &&
9596 isa<PHINode>(PN.getIncomingValue(InValNo)))
9597 ++InValNo;
9598
9599 if (InValNo != NumOperandVals) {
9600 Value *NonPhiInVal = PN.getOperand(InValNo);
9601
9602 // Scan the rest of the operands to see if there are any conflicts, if so
9603 // there is no need to recursively scan other phis.
9604 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9605 Value *OpVal = PN.getIncomingValue(InValNo);
9606 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9607 break;
9608 }
9609
9610 // If we scanned over all operands, then we have one unique value plus
9611 // phi values. Scan PHI nodes to see if they all merge in each other or
9612 // the value.
9613 if (InValNo == NumOperandVals) {
9614 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9615 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9616 return ReplaceInstUsesWith(PN, NonPhiInVal);
9617 }
9618 }
9619 }
Chris Lattner60921c92003-12-19 05:58:40 +00009620 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009621}
9622
Reid Spencer17212df2006-12-12 09:18:51 +00009623static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9624 Instruction *InsertPoint,
9625 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009626 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9627 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009628 // We must cast correctly to the pointer type. Ensure that we
9629 // sign extend the integer value if it is smaller as this is
9630 // used for address computation.
9631 Instruction::CastOps opcode =
9632 (VTySize < PtrSize ? Instruction::SExt :
9633 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9634 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009635}
9636
Chris Lattnera1be5662002-05-02 17:06:02 +00009637
Chris Lattner7e708292002-06-25 16:13:24 +00009638Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009639 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009640 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009641 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009642 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009643 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009644
Chris Lattnere87597f2004-10-16 18:11:37 +00009645 if (isa<UndefValue>(GEP.getOperand(0)))
9646 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9647
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009648 bool HasZeroPointerIndex = false;
9649 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9650 HasZeroPointerIndex = C->isNullValue();
9651
9652 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009653 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009654
Chris Lattner28977af2004-04-05 01:30:19 +00009655 // Eliminate unneeded casts for indices.
9656 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009657
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009658 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009659 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9660 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009661 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009662 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009663 if (CI->getOpcode() == Instruction::ZExt ||
9664 CI->getOpcode() == Instruction::SExt) {
9665 const Type *SrcTy = CI->getOperand(0)->getType();
9666 // We can eliminate a cast from i32 to i64 iff the target
9667 // is a 32-bit pointer target.
9668 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9669 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009670 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009671 }
9672 }
9673 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009674 // If we are using a wider index than needed for this platform, shrink it
9675 // to what we need. If the incoming value needs a cast instruction,
9676 // insert it. This explicit cast can make subsequent optimizations more
9677 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009678 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009679 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009680 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009681 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009682 MadeChange = true;
9683 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009684 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9685 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009686 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009687 MadeChange = true;
9688 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009689 }
Chris Lattner28977af2004-04-05 01:30:19 +00009690 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009691 }
Chris Lattner28977af2004-04-05 01:30:19 +00009692 if (MadeChange) return &GEP;
9693
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009694 // If this GEP instruction doesn't move the pointer, and if the input operand
9695 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9696 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009697 if (GEP.hasAllZeroIndices()) {
9698 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9699 // If the bitcast is of an allocation, and the allocation will be
9700 // converted to match the type of the cast, don't touch this.
9701 if (isa<AllocationInst>(BCI->getOperand(0))) {
9702 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009703 if (Instruction *I = visitBitCast(*BCI)) {
9704 if (I != BCI) {
9705 I->takeName(BCI);
9706 BCI->getParent()->getInstList().insert(BCI, I);
9707 ReplaceInstUsesWith(*BCI, I);
9708 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009709 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009710 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009711 }
9712 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9713 }
9714 }
9715
Chris Lattner90ac28c2002-08-02 19:29:35 +00009716 // Combine Indices - If the source pointer to this getelementptr instruction
9717 // is a getelementptr instruction, combine the indices of the two
9718 // getelementptr instructions into a single instruction.
9719 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009720 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009721 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009722 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009723
9724 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009725 // Note that if our source is a gep chain itself that we wait for that
9726 // chain to be resolved before we perform this transformation. This
9727 // avoids us creating a TON of code in some cases.
9728 //
9729 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9730 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9731 return 0; // Wait until our source is folded to completion.
9732
Chris Lattner72588fc2007-02-15 22:48:32 +00009733 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009734
9735 // Find out whether the last index in the source GEP is a sequential idx.
9736 bool EndsWithSequential = false;
9737 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9738 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009739 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009740
Chris Lattner90ac28c2002-08-02 19:29:35 +00009741 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009742 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009743 // Replace: gep (gep %P, long B), long A, ...
9744 // With: T = long A+B; gep %P, T, ...
9745 //
Chris Lattner620ce142004-05-07 22:09:22 +00009746 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009747 if (SO1 == Constant::getNullValue(SO1->getType())) {
9748 Sum = GO1;
9749 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9750 Sum = SO1;
9751 } else {
9752 // If they aren't the same type, convert both to an integer of the
9753 // target's pointer size.
9754 if (SO1->getType() != GO1->getType()) {
9755 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009756 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009757 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009758 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009759 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009760 unsigned PS = TD->getPointerSizeInBits();
9761 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009762 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009763 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009764
Duncan Sands514ab342007-11-01 20:53:16 +00009765 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009766 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009767 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009768 } else {
9769 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009770 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9771 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009772 }
9773 }
9774 }
Chris Lattner620ce142004-05-07 22:09:22 +00009775 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9776 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9777 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009778 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009779 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009780 }
Chris Lattner28977af2004-04-05 01:30:19 +00009781 }
Chris Lattner620ce142004-05-07 22:09:22 +00009782
9783 // Recycle the GEP we already have if possible.
9784 if (SrcGEPOperands.size() == 2) {
9785 GEP.setOperand(0, SrcGEPOperands[0]);
9786 GEP.setOperand(1, Sum);
9787 return &GEP;
9788 } else {
9789 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9790 SrcGEPOperands.end()-1);
9791 Indices.push_back(Sum);
9792 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9793 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009794 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009795 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009796 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009797 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009798 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9799 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009800 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9801 }
9802
9803 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009804 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9805 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009806
Chris Lattner620ce142004-05-07 22:09:22 +00009807 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009808 // GEP of global variable. If all of the indices for this GEP are
9809 // constants, we can promote this to a constexpr instead of an instruction.
9810
9811 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009812 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009813 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9814 for (; I != E && isa<Constant>(*I); ++I)
9815 Indices.push_back(cast<Constant>(*I));
9816
9817 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009818 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9819 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009820
9821 // Replace all uses of the GEP with the new constexpr...
9822 return ReplaceInstUsesWith(GEP, CE);
9823 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009824 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009825 if (!isa<PointerType>(X->getType())) {
9826 // Not interesting. Source pointer must be a cast from pointer.
9827 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009828 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9829 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009830 //
9831 // This occurs when the program declares an array extern like "int X[];"
9832 //
9833 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9834 const PointerType *XTy = cast<PointerType>(X->getType());
9835 if (const ArrayType *XATy =
9836 dyn_cast<ArrayType>(XTy->getElementType()))
9837 if (const ArrayType *CATy =
9838 dyn_cast<ArrayType>(CPTy->getElementType()))
9839 if (CATy->getElementType() == XATy->getElementType()) {
9840 // At this point, we know that the cast source type is a pointer
9841 // to an array of the same type as the destination pointer
9842 // array. Because the array type is never stepped over (there
9843 // is a leading zero) we can fold the cast into this GEP.
9844 GEP.setOperand(0, X);
9845 return &GEP;
9846 }
9847 } else if (GEP.getNumOperands() == 2) {
9848 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009849 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9850 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009851 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9852 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9853 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009854 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9855 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009856 Value *Idx[2];
9857 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9858 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009859 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009860 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009861 // V and GEP are both pointer types --> BitCast
9862 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009863 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009864
9865 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009866 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009867 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009868 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009869
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009870 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009871 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009872 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009873
9874 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9875 // allow either a mul, shift, or constant here.
9876 Value *NewIdx = 0;
9877 ConstantInt *Scale = 0;
9878 if (ArrayEltSize == 1) {
9879 NewIdx = GEP.getOperand(1);
9880 Scale = ConstantInt::get(NewIdx->getType(), 1);
9881 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009882 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009883 Scale = CI;
9884 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9885 if (Inst->getOpcode() == Instruction::Shl &&
9886 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009887 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9888 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9889 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009890 NewIdx = Inst->getOperand(0);
9891 } else if (Inst->getOpcode() == Instruction::Mul &&
9892 isa<ConstantInt>(Inst->getOperand(1))) {
9893 Scale = cast<ConstantInt>(Inst->getOperand(1));
9894 NewIdx = Inst->getOperand(0);
9895 }
9896 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009897
Chris Lattner7835cdd2005-09-13 18:36:04 +00009898 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009899 // out, perform the transformation. Note, we don't know whether Scale is
9900 // signed or not. We'll use unsigned version of division/modulo
9901 // operation after making sure Scale doesn't have the sign bit set.
9902 if (Scale && Scale->getSExtValue() >= 0LL &&
9903 Scale->getZExtValue() % ArrayEltSize == 0) {
9904 Scale = ConstantInt::get(Scale->getType(),
9905 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009906 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009907 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009908 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009909 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009910 NewIdx = InsertNewInstBefore(Sc, GEP);
9911 }
9912
9913 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009914 Value *Idx[2];
9915 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9916 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009917 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009918 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009919 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9920 // The NewGEP must be pointer typed, so must the old one -> BitCast
9921 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009922 }
9923 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009924 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009925 }
9926
Chris Lattner8a2a3112001-12-14 16:52:21 +00009927 return 0;
9928}
9929
Chris Lattner0864acf2002-11-04 16:18:53 +00009930Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9931 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009932 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009933 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9934 const Type *NewTy =
9935 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009936 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009937
9938 // Create and insert the replacement instruction...
9939 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009940 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009941 else {
9942 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009943 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009944 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009945
9946 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009947
Chris Lattner0864acf2002-11-04 16:18:53 +00009948 // Scan to the end of the allocation instructions, to skip over a block of
9949 // allocas if possible...
9950 //
9951 BasicBlock::iterator It = New;
9952 while (isa<AllocationInst>(*It)) ++It;
9953
9954 // Now that I is pointing to the first non-allocation-inst in the block,
9955 // insert our getelementptr instruction...
9956 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009957 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009958 Value *Idx[2];
9959 Idx[0] = NullIdx;
9960 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009961 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9962 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009963
9964 // Now make everything use the getelementptr instead of the original
9965 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009966 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009967 } else if (isa<UndefValue>(AI.getArraySize())) {
9968 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009969 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009970 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009971
9972 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9973 // Note that we only do this for alloca's, because malloc should allocate and
9974 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009975 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009976 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009977 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9978
Chris Lattner0864acf2002-11-04 16:18:53 +00009979 return 0;
9980}
9981
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009982Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9983 Value *Op = FI.getOperand(0);
9984
Chris Lattner17be6352004-10-18 02:59:09 +00009985 // free undef -> unreachable.
9986 if (isa<UndefValue>(Op)) {
9987 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009988 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009989 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009990 return EraseInstFromFunction(FI);
9991 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009992
Chris Lattner6160e852004-02-28 04:57:37 +00009993 // If we have 'free null' delete the instruction. This can happen in stl code
9994 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009995 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009996 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009997
9998 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9999 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10000 FI.setOperand(0, CI->getOperand(0));
10001 return &FI;
10002 }
10003
10004 // Change free (gep X, 0,0,0,0) into free(X)
10005 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10006 if (GEPI->hasAllZeroIndices()) {
10007 AddToWorkList(GEPI);
10008 FI.setOperand(0, GEPI->getOperand(0));
10009 return &FI;
10010 }
10011 }
10012
10013 // Change free(malloc) into nothing, if the malloc has a single use.
10014 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10015 if (MI->hasOneUse()) {
10016 EraseInstFromFunction(FI);
10017 return EraseInstFromFunction(*MI);
10018 }
Chris Lattner6160e852004-02-28 04:57:37 +000010019
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010020 return 0;
10021}
10022
10023
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010024/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010025static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010026 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010027 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010028 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010029
Devang Patel99db6ad2007-10-18 19:52:32 +000010030 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10031 // Instead of loading constant c string, use corresponding integer value
10032 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010033 std::string Str;
10034 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010035 unsigned len = Str.length();
10036 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10037 unsigned numBits = Ty->getPrimitiveSizeInBits();
10038 // Replace LI with immediate integer store.
10039 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010040 APInt StrVal(numBits, 0);
10041 APInt SingleChar(numBits, 0);
10042 if (TD->isLittleEndian()) {
10043 for (signed i = len-1; i >= 0; i--) {
10044 SingleChar = (uint64_t) Str[i];
10045 StrVal = (StrVal << 8) | SingleChar;
10046 }
10047 } else {
10048 for (unsigned i = 0; i < len; i++) {
10049 SingleChar = (uint64_t) Str[i];
10050 StrVal = (StrVal << 8) | SingleChar;
10051 }
10052 // Append NULL at the end.
10053 SingleChar = 0;
10054 StrVal = (StrVal << 8) | SingleChar;
10055 }
10056 Value *NL = ConstantInt::get(StrVal);
10057 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010058 }
10059 }
10060 }
10061
Chris Lattnerb89e0712004-07-13 01:49:43 +000010062 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010063 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010064 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010065
Reid Spencer42230162007-01-22 05:51:25 +000010066 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010067 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010068 // If the source is an array, the code below will not succeed. Check to
10069 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10070 // constants.
10071 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10072 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10073 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010074 Value *Idxs[2];
10075 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10076 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010077 SrcTy = cast<PointerType>(CastOp->getType());
10078 SrcPTy = SrcTy->getElementType();
10079 }
10080
Reid Spencer42230162007-01-22 05:51:25 +000010081 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010082 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010083 // Do not allow turning this into a load of an integer, which is then
10084 // casted to a pointer, this pessimizes pointer analysis a lot.
10085 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010086 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10087 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010088
Chris Lattnerf9527852005-01-31 04:50:46 +000010089 // Okay, we are casting from one integer or pointer type to another of
10090 // the same size. Instead of casting the pointer before the load, cast
10091 // the result of the loaded value.
10092 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10093 CI->getName(),
10094 LI.isVolatile()),LI);
10095 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010096 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010097 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010098 }
10099 }
10100 return 0;
10101}
10102
Chris Lattnerc10aced2004-09-19 18:43:46 +000010103/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010104/// from this value cannot trap. If it is not obviously safe to load from the
10105/// specified pointer, we do a quick local scan of the basic block containing
10106/// ScanFrom, to determine if the address is already accessed.
10107static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010108 // If it is an alloca it is always safe to load from.
10109 if (isa<AllocaInst>(V)) return true;
10110
Duncan Sands46318cd2007-09-19 10:25:38 +000010111 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010112 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010113 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010114 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010115
10116 // Otherwise, be a little bit agressive by scanning the local block where we
10117 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010118 // from/to. If so, the previous load or store would have already trapped,
10119 // so there is no harm doing an extra load (also, CSE will later eliminate
10120 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010121 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10122
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010123 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010124 --BBI;
10125
Chris Lattner2de3fec2008-06-20 05:12:56 +000010126 // If we see a free or a call (which might do a free) the pointer could be
10127 // marked invalid.
10128 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10129 return false;
10130
Chris Lattner8a375202004-09-19 19:18:10 +000010131 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10132 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010133 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000010134 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010135 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010136
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010137 }
Chris Lattner8a375202004-09-19 19:18:10 +000010138 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010139}
10140
Chris Lattner8d2e8882007-08-11 18:48:48 +000010141/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10142/// until we find the underlying object a pointer is referring to or something
10143/// we don't understand. Note that the returned pointer may be offset from the
10144/// input, because we ignore GEP indices.
10145static Value *GetUnderlyingObject(Value *Ptr) {
10146 while (1) {
10147 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10148 if (CE->getOpcode() == Instruction::BitCast ||
10149 CE->getOpcode() == Instruction::GetElementPtr)
10150 Ptr = CE->getOperand(0);
10151 else
10152 return Ptr;
10153 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10154 Ptr = BCI->getOperand(0);
10155 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10156 Ptr = GEP->getOperand(0);
10157 } else {
10158 return Ptr;
10159 }
10160 }
10161}
10162
Chris Lattner833b8a42003-06-26 05:06:25 +000010163Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10164 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010165
Dan Gohman9941f742007-07-20 16:34:21 +000010166 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010167 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10168 if (KnownAlign >
10169 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10170 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010171 LI.setAlignment(KnownAlign);
10172
Chris Lattner37366c12005-05-01 04:24:53 +000010173 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010174 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010175 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010176 return Res;
10177
10178 // None of the following transforms are legal for volatile loads.
10179 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010180
Chris Lattner62f254d2005-09-12 22:00:15 +000010181 if (&LI.getParent()->front() != &LI) {
10182 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010183 // If the instruction immediately before this is a store to the same
10184 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010185 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10186 if (SI->getOperand(1) == LI.getOperand(0))
10187 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010188 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10189 if (LIB->getOperand(0) == LI.getOperand(0))
10190 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010191 }
Chris Lattner37366c12005-05-01 04:24:53 +000010192
Christopher Lambb15147e2007-12-29 07:56:53 +000010193 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10194 const Value *GEPI0 = GEPI->getOperand(0);
10195 // TODO: Consider a target hook for valid address spaces for this xform.
10196 if (isa<ConstantPointerNull>(GEPI0) &&
10197 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010198 // Insert a new store to null instruction before the load to indicate
10199 // that this code is not reachable. We do this instead of inserting
10200 // an unreachable instruction directly because we cannot modify the
10201 // CFG.
10202 new StoreInst(UndefValue::get(LI.getType()),
10203 Constant::getNullValue(Op->getType()), &LI);
10204 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10205 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010206 }
Chris Lattner37366c12005-05-01 04:24:53 +000010207
Chris Lattnere87597f2004-10-16 18:11:37 +000010208 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010209 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010210 // TODO: Consider a target hook for valid address spaces for this xform.
10211 if (isa<UndefValue>(C) || (C->isNullValue() &&
10212 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010213 // Insert a new store to null instruction before the load to indicate that
10214 // this code is not reachable. We do this instead of inserting an
10215 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010216 new StoreInst(UndefValue::get(LI.getType()),
10217 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010218 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010219 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010220
Chris Lattnere87597f2004-10-16 18:11:37 +000010221 // Instcombine load (constant global) into the value loaded.
10222 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010223 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010224 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010225
Chris Lattnere87597f2004-10-16 18:11:37 +000010226 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010227 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010228 if (CE->getOpcode() == Instruction::GetElementPtr) {
10229 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010230 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010231 if (Constant *V =
10232 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010233 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010234 if (CE->getOperand(0)->isNullValue()) {
10235 // Insert a new store to null instruction before the load to indicate
10236 // that this code is not reachable. We do this instead of inserting
10237 // an unreachable instruction directly because we cannot modify the
10238 // CFG.
10239 new StoreInst(UndefValue::get(LI.getType()),
10240 Constant::getNullValue(Op->getType()), &LI);
10241 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10242 }
10243
Reid Spencer3da59db2006-11-27 01:05:10 +000010244 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010245 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010246 return Res;
10247 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010248 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010249 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010250
10251 // If this load comes from anywhere in a constant global, and if the global
10252 // is all undef or zero, we know what it loads.
10253 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10254 if (GV->isConstant() && GV->hasInitializer()) {
10255 if (GV->getInitializer()->isNullValue())
10256 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10257 else if (isa<UndefValue>(GV->getInitializer()))
10258 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10259 }
10260 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010261
Chris Lattner37366c12005-05-01 04:24:53 +000010262 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010263 // Change select and PHI nodes to select values instead of addresses: this
10264 // helps alias analysis out a lot, allows many others simplifications, and
10265 // exposes redundancy in the code.
10266 //
10267 // Note that we cannot do the transformation unless we know that the
10268 // introduced loads cannot trap! Something like this is valid as long as
10269 // the condition is always false: load (select bool %C, int* null, int* %G),
10270 // but it would not be valid if we transformed it to load from null
10271 // unconditionally.
10272 //
10273 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10274 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010275 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10276 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010277 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010278 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010279 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010280 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010281 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010282 }
10283
Chris Lattner684fe212004-09-23 15:46:00 +000010284 // load (select (cond, null, P)) -> load P
10285 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10286 if (C->isNullValue()) {
10287 LI.setOperand(0, SI->getOperand(2));
10288 return &LI;
10289 }
10290
10291 // load (select (cond, P, null)) -> load P
10292 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10293 if (C->isNullValue()) {
10294 LI.setOperand(0, SI->getOperand(1));
10295 return &LI;
10296 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010297 }
10298 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010299 return 0;
10300}
10301
Reid Spencer55af2b52007-01-19 21:20:31 +000010302/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010303/// when possible.
10304static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10305 User *CI = cast<User>(SI.getOperand(1));
10306 Value *CastOp = CI->getOperand(0);
10307
10308 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10309 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10310 const Type *SrcPTy = SrcTy->getElementType();
10311
Reid Spencer42230162007-01-22 05:51:25 +000010312 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010313 // If the source is an array, the code below will not succeed. Check to
10314 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10315 // constants.
10316 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10317 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10318 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010319 Value* Idxs[2];
10320 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10321 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010322 SrcTy = cast<PointerType>(CastOp->getType());
10323 SrcPTy = SrcTy->getElementType();
10324 }
10325
Reid Spencer67f827c2007-01-20 23:35:48 +000010326 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10327 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10328 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010329
10330 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010331 // the same size. Instead of casting the pointer before
10332 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010333 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010334 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010335 Instruction::CastOps opcode = Instruction::BitCast;
10336 const Type* CastSrcTy = SIOp0->getType();
10337 const Type* CastDstTy = SrcPTy;
10338 if (isa<PointerType>(CastDstTy)) {
10339 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010340 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010341 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010342 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010343 opcode = Instruction::PtrToInt;
10344 }
10345 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010346 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010347 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010348 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010349 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010350 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010351 return new StoreInst(NewCast, CastOp);
10352 }
10353 }
10354 }
10355 return 0;
10356}
10357
Chris Lattner2f503e62005-01-31 05:36:43 +000010358Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10359 Value *Val = SI.getOperand(0);
10360 Value *Ptr = SI.getOperand(1);
10361
10362 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010363 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010364 ++NumCombined;
10365 return 0;
10366 }
Chris Lattner836692d2007-01-15 06:51:56 +000010367
10368 // If the RHS is an alloca with a single use, zapify the store, making the
10369 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010370 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010371 if (isa<AllocaInst>(Ptr)) {
10372 EraseInstFromFunction(SI);
10373 ++NumCombined;
10374 return 0;
10375 }
10376
10377 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10378 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10379 GEP->getOperand(0)->hasOneUse()) {
10380 EraseInstFromFunction(SI);
10381 ++NumCombined;
10382 return 0;
10383 }
10384 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010385
Dan Gohman9941f742007-07-20 16:34:21 +000010386 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010387 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10388 if (KnownAlign >
10389 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10390 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010391 SI.setAlignment(KnownAlign);
10392
Chris Lattner9ca96412006-02-08 03:25:32 +000010393 // Do really simple DSE, to catch cases where there are several consequtive
10394 // stores to the same location, separated by a few arithmetic operations. This
10395 // situation often occurs with bitfield accesses.
10396 BasicBlock::iterator BBI = &SI;
10397 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10398 --ScanInsts) {
10399 --BBI;
10400
10401 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10402 // Prev store isn't volatile, and stores to the same location?
10403 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10404 ++NumDeadStore;
10405 ++BBI;
10406 EraseInstFromFunction(*PrevSI);
10407 continue;
10408 }
10409 break;
10410 }
10411
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010412 // If this is a load, we have to stop. However, if the loaded value is from
10413 // the pointer we're loading and is producing the pointer we're storing,
10414 // then *this* store is dead (X = load P; store X -> P).
10415 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010416 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010417 EraseInstFromFunction(SI);
10418 ++NumCombined;
10419 return 0;
10420 }
10421 // Otherwise, this is a load from some other location. Stores before it
10422 // may not be dead.
10423 break;
10424 }
10425
Chris Lattner9ca96412006-02-08 03:25:32 +000010426 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010427 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010428 break;
10429 }
10430
10431
10432 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010433
10434 // store X, null -> turns into 'unreachable' in SimplifyCFG
10435 if (isa<ConstantPointerNull>(Ptr)) {
10436 if (!isa<UndefValue>(Val)) {
10437 SI.setOperand(0, UndefValue::get(Val->getType()));
10438 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010439 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010440 ++NumCombined;
10441 }
10442 return 0; // Do not modify these!
10443 }
10444
10445 // store undef, Ptr -> noop
10446 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010447 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010448 ++NumCombined;
10449 return 0;
10450 }
10451
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010452 // If the pointer destination is a cast, see if we can fold the cast into the
10453 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010454 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010455 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10456 return Res;
10457 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010458 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010459 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10460 return Res;
10461
Chris Lattner408902b2005-09-12 23:23:25 +000010462
10463 // If this store is the last instruction in the basic block, and if the block
10464 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010465 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010466 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010467 if (BI->isUnconditional())
10468 if (SimplifyStoreAtEndOfBlock(SI))
10469 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010470
Chris Lattner2f503e62005-01-31 05:36:43 +000010471 return 0;
10472}
10473
Chris Lattner3284d1f2007-04-15 00:07:55 +000010474/// SimplifyStoreAtEndOfBlock - Turn things like:
10475/// if () { *P = v1; } else { *P = v2 }
10476/// into a phi node with a store in the successor.
10477///
Chris Lattner31755a02007-04-15 01:02:18 +000010478/// Simplify things like:
10479/// *P = v1; if () { *P = v2; }
10480/// into a phi node with a store in the successor.
10481///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010482bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10483 BasicBlock *StoreBB = SI.getParent();
10484
10485 // Check to see if the successor block has exactly two incoming edges. If
10486 // so, see if the other predecessor contains a store to the same location.
10487 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010488 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010489
10490 // Determine whether Dest has exactly two predecessors and, if so, compute
10491 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010492 pred_iterator PI = pred_begin(DestBB);
10493 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010494 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010495 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010496 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010497 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010498 return false;
10499
10500 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010501 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010502 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010503 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010504 }
Chris Lattner31755a02007-04-15 01:02:18 +000010505 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010506 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000010507
10508 // Bail out if all the relevant blocks aren't distinct (this can happen,
10509 // for example, if SI is in an infinite loop)
10510 if (StoreBB == DestBB || OtherBB == DestBB)
10511 return false;
10512
Chris Lattner31755a02007-04-15 01:02:18 +000010513 // Verify that the other block ends in a branch and is not otherwise empty.
10514 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010515 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010516 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010517 return false;
10518
Chris Lattner31755a02007-04-15 01:02:18 +000010519 // If the other block ends in an unconditional branch, check for the 'if then
10520 // else' case. there is an instruction before the branch.
10521 StoreInst *OtherStore = 0;
10522 if (OtherBr->isUnconditional()) {
10523 // If this isn't a store, or isn't a store to the same location, bail out.
10524 --BBI;
10525 OtherStore = dyn_cast<StoreInst>(BBI);
10526 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10527 return false;
10528 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010529 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010530 // destinations is StoreBB, then we have the if/then case.
10531 if (OtherBr->getSuccessor(0) != StoreBB &&
10532 OtherBr->getSuccessor(1) != StoreBB)
10533 return false;
10534
10535 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010536 // if/then triangle. See if there is a store to the same ptr as SI that
10537 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010538 for (;; --BBI) {
10539 // Check to see if we find the matching store.
10540 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10541 if (OtherStore->getOperand(1) != SI.getOperand(1))
10542 return false;
10543 break;
10544 }
Eli Friedman6903a242008-06-13 22:02:12 +000010545 // If we find something that may be using or overwriting the stored
10546 // value, or if we run out of instructions, we can't do the xform.
10547 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000010548 BBI == OtherBB->begin())
10549 return false;
10550 }
10551
10552 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000010553 // make sure nothing reads or overwrites the stored value in
10554 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010555 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10556 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000010557 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000010558 return false;
10559 }
10560 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010561
Chris Lattner31755a02007-04-15 01:02:18 +000010562 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010563 Value *MergedVal = OtherStore->getOperand(0);
10564 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010565 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010566 PN->reserveOperandSpace(2);
10567 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010568 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10569 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010570 }
10571
10572 // Advance to a place where it is safe to insert the new store and
10573 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010574 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010575 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10576 OtherStore->isVolatile()), *BBI);
10577
10578 // Nuke the old stores.
10579 EraseInstFromFunction(SI);
10580 EraseInstFromFunction(*OtherStore);
10581 ++NumCombined;
10582 return true;
10583}
10584
Chris Lattner2f503e62005-01-31 05:36:43 +000010585
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010586Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10587 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010588 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010589 BasicBlock *TrueDest;
10590 BasicBlock *FalseDest;
10591 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10592 !isa<Constant>(X)) {
10593 // Swap Destinations and condition...
10594 BI.setCondition(X);
10595 BI.setSuccessor(0, FalseDest);
10596 BI.setSuccessor(1, TrueDest);
10597 return &BI;
10598 }
10599
Reid Spencere4d87aa2006-12-23 06:05:41 +000010600 // Cannonicalize fcmp_one -> fcmp_oeq
10601 FCmpInst::Predicate FPred; Value *Y;
10602 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10603 TrueDest, FalseDest)))
10604 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10605 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10606 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010607 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010608 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10609 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010610 // Swap Destinations and condition...
10611 BI.setCondition(NewSCC);
10612 BI.setSuccessor(0, FalseDest);
10613 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010614 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010615 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010616 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010617 return &BI;
10618 }
10619
10620 // Cannonicalize icmp_ne -> icmp_eq
10621 ICmpInst::Predicate IPred;
10622 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10623 TrueDest, FalseDest)))
10624 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10625 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10626 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10627 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010628 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010629 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10630 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010631 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010632 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010633 BI.setSuccessor(0, FalseDest);
10634 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010635 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010636 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010637 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010638 return &BI;
10639 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010640
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010641 return 0;
10642}
Chris Lattner0864acf2002-11-04 16:18:53 +000010643
Chris Lattner46238a62004-07-03 00:26:11 +000010644Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10645 Value *Cond = SI.getCondition();
10646 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10647 if (I->getOpcode() == Instruction::Add)
10648 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10649 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10650 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010651 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010652 AddRHS));
10653 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010654 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010655 return &SI;
10656 }
10657 }
10658 return 0;
10659}
10660
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010661Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10662 // See if we are trying to extract a known value. If so, use that instead.
Matthijs Kooijman710eb232008-06-16 12:57:37 +000010663 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +000010664 EV.idx_end(), &EV))
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010665 return ReplaceInstUsesWith(EV, Elt);
10666
10667 // No changes
10668 return 0;
10669}
10670
Chris Lattner220b0cf2006-03-05 00:22:33 +000010671/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10672/// is to leave as a vector operation.
10673static bool CheapToScalarize(Value *V, bool isConstant) {
10674 if (isa<ConstantAggregateZero>(V))
10675 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010676 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010677 if (isConstant) return true;
10678 // If all elts are the same, we can extract.
10679 Constant *Op0 = C->getOperand(0);
10680 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10681 if (C->getOperand(i) != Op0)
10682 return false;
10683 return true;
10684 }
10685 Instruction *I = dyn_cast<Instruction>(V);
10686 if (!I) return false;
10687
10688 // Insert element gets simplified to the inserted element or is deleted if
10689 // this is constant idx extract element and its a constant idx insertelt.
10690 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10691 isa<ConstantInt>(I->getOperand(2)))
10692 return true;
10693 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10694 return true;
10695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10696 if (BO->hasOneUse() &&
10697 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10698 CheapToScalarize(BO->getOperand(1), isConstant)))
10699 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010700 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10701 if (CI->hasOneUse() &&
10702 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10703 CheapToScalarize(CI->getOperand(1), isConstant)))
10704 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010705
10706 return false;
10707}
10708
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010709/// Read and decode a shufflevector mask.
10710///
10711/// It turns undef elements into values that are larger than the number of
10712/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010713static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10714 unsigned NElts = SVI->getType()->getNumElements();
10715 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10716 return std::vector<unsigned>(NElts, 0);
10717 if (isa<UndefValue>(SVI->getOperand(2)))
10718 return std::vector<unsigned>(NElts, 2*NElts);
10719
10720 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010721 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000010722 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10723 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000010724 Result.push_back(NElts*2); // undef -> 8
10725 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000010726 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010727 return Result;
10728}
10729
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010730/// FindScalarElement - Given a vector and an element number, see if the scalar
10731/// value is already around as a register, for example if it were inserted then
10732/// extracted from the vector.
10733static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010734 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10735 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010736 unsigned Width = PTy->getNumElements();
10737 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010738 return UndefValue::get(PTy->getElementType());
10739
10740 if (isa<UndefValue>(V))
10741 return UndefValue::get(PTy->getElementType());
10742 else if (isa<ConstantAggregateZero>(V))
10743 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010744 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010745 return CP->getOperand(EltNo);
10746 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10747 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010748 if (!isa<ConstantInt>(III->getOperand(2)))
10749 return 0;
10750 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010751
10752 // If this is an insert to the element we are looking for, return the
10753 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010754 if (EltNo == IIElt)
10755 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010756
10757 // Otherwise, the insertelement doesn't modify the value, recurse on its
10758 // vector input.
10759 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010760 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010761 unsigned InEl = getShuffleMask(SVI)[EltNo];
10762 if (InEl < Width)
10763 return FindScalarElement(SVI->getOperand(0), InEl);
10764 else if (InEl < Width*2)
10765 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10766 else
10767 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010768 }
10769
10770 // Otherwise, we don't know.
10771 return 0;
10772}
10773
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010774Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010775 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010776 if (isa<UndefValue>(EI.getOperand(0)))
10777 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10778
Dan Gohman07a96762007-07-16 14:29:03 +000010779 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010780 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10781 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10782
Reid Spencer9d6565a2007-02-15 02:26:10 +000010783 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010784 // If vector val is constant with all elements the same, replace EI with
10785 // that element. When the elements are not identical, we cannot replace yet
10786 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010787 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010788 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010789 if (C->getOperand(i) != op0) {
10790 op0 = 0;
10791 break;
10792 }
10793 if (op0)
10794 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010795 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010796
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010797 // If extracting a specified index from the vector, see if we can recursively
10798 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010799 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010800 unsigned IndexVal = IdxC->getZExtValue();
10801 unsigned VectorWidth =
10802 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10803
10804 // If this is extracting an invalid index, turn this into undef, to avoid
10805 // crashing the code below.
10806 if (IndexVal >= VectorWidth)
10807 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10808
Chris Lattner867b99f2006-10-05 06:55:50 +000010809 // This instruction only demands the single element from the input vector.
10810 // If the input vector has a single use, simplify it based on this use
10811 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010812 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010813 uint64_t UndefElts;
10814 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010815 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010816 UndefElts)) {
10817 EI.setOperand(0, V);
10818 return &EI;
10819 }
10820 }
10821
Reid Spencerb83eb642006-10-20 07:07:24 +000010822 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010823 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010824
10825 // If the this extractelement is directly using a bitcast from a vector of
10826 // the same number of elements, see if we can find the source element from
10827 // it. In this case, we will end up needing to bitcast the scalars.
10828 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10829 if (const VectorType *VT =
10830 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10831 if (VT->getNumElements() == VectorWidth)
10832 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10833 return new BitCastInst(Elt, EI.getType());
10834 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010835 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010836
Chris Lattner73fa49d2006-05-25 22:53:38 +000010837 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010838 if (I->hasOneUse()) {
10839 // Push extractelement into predecessor operation if legal and
10840 // profitable to do so
10841 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010842 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10843 if (CheapToScalarize(BO, isConstantElt)) {
10844 ExtractElementInst *newEI0 =
10845 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10846 EI.getName()+".lhs");
10847 ExtractElementInst *newEI1 =
10848 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10849 EI.getName()+".rhs");
10850 InsertNewInstBefore(newEI0, EI);
10851 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010852 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010853 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010854 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010855 unsigned AS =
10856 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010857 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10858 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010859 GetElementPtrInst *GEP =
10860 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010861 InsertNewInstBefore(GEP, EI);
10862 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010863 }
10864 }
10865 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10866 // Extracting the inserted element?
10867 if (IE->getOperand(2) == EI.getOperand(1))
10868 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10869 // If the inserted and extracted elements are constants, they must not
10870 // be the same value, extract from the pre-inserted value instead.
10871 if (isa<Constant>(IE->getOperand(2)) &&
10872 isa<Constant>(EI.getOperand(1))) {
10873 AddUsesToWorkList(EI);
10874 EI.setOperand(0, IE->getOperand(0));
10875 return &EI;
10876 }
10877 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10878 // If this is extracting an element from a shufflevector, figure out where
10879 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010880 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10881 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010882 Value *Src;
10883 if (SrcIdx < SVI->getType()->getNumElements())
10884 Src = SVI->getOperand(0);
10885 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10886 SrcIdx -= SVI->getType()->getNumElements();
10887 Src = SVI->getOperand(1);
10888 } else {
10889 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010890 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010891 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010892 }
10893 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010894 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010895 return 0;
10896}
10897
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010898/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10899/// elements from either LHS or RHS, return the shuffle mask and true.
10900/// Otherwise, return false.
10901static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10902 std::vector<Constant*> &Mask) {
10903 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10904 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010905 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010906
10907 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010908 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010909 return true;
10910 } else if (V == LHS) {
10911 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010912 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010913 return true;
10914 } else if (V == RHS) {
10915 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010916 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010917 return true;
10918 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10919 // If this is an insert of an extract from some other vector, include it.
10920 Value *VecOp = IEI->getOperand(0);
10921 Value *ScalarOp = IEI->getOperand(1);
10922 Value *IdxOp = IEI->getOperand(2);
10923
Chris Lattnerd929f062006-04-27 21:14:21 +000010924 if (!isa<ConstantInt>(IdxOp))
10925 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010926 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010927
10928 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10929 // Okay, we can handle this if the vector we are insertinting into is
10930 // transitively ok.
10931 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10932 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010933 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010934 return true;
10935 }
10936 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10937 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010938 EI->getOperand(0)->getType() == V->getType()) {
10939 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010940 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010941
10942 // This must be extracting from either LHS or RHS.
10943 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10944 // Okay, we can handle this if the vector we are insertinting into is
10945 // transitively ok.
10946 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10947 // If so, update the mask to reflect the inserted value.
10948 if (EI->getOperand(0) == LHS) {
10949 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010950 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010951 } else {
10952 assert(EI->getOperand(0) == RHS);
10953 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010954 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010955
10956 }
10957 return true;
10958 }
10959 }
10960 }
10961 }
10962 }
10963 // TODO: Handle shufflevector here!
10964
10965 return false;
10966}
10967
10968/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10969/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10970/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010971static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010972 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010973 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010974 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010975 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010976 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010977
10978 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010979 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010980 return V;
10981 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010982 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010983 return V;
10984 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10985 // If this is an insert of an extract from some other vector, include it.
10986 Value *VecOp = IEI->getOperand(0);
10987 Value *ScalarOp = IEI->getOperand(1);
10988 Value *IdxOp = IEI->getOperand(2);
10989
10990 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10991 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10992 EI->getOperand(0)->getType() == V->getType()) {
10993 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010994 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10995 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010996
10997 // Either the extracted from or inserted into vector must be RHSVec,
10998 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010999 if (EI->getOperand(0) == RHS || RHS == 0) {
11000 RHS = EI->getOperand(0);
11001 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011002 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011003 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011004 return V;
11005 }
11006
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011007 if (VecOp == RHS) {
11008 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011009 // Everything but the extracted element is replaced with the RHS.
11010 for (unsigned i = 0; i != NumElts; ++i) {
11011 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011012 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011013 }
11014 return V;
11015 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011016
11017 // If this insertelement is a chain that comes from exactly these two
11018 // vectors, return the vector and the effective shuffle.
11019 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11020 return EI->getOperand(0);
11021
Chris Lattnerefb47352006-04-15 01:39:45 +000011022 }
11023 }
11024 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011025 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011026
11027 // Otherwise, can't do anything fancy. Return an identity vector.
11028 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011029 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011030 return V;
11031}
11032
11033Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11034 Value *VecOp = IE.getOperand(0);
11035 Value *ScalarOp = IE.getOperand(1);
11036 Value *IdxOp = IE.getOperand(2);
11037
Chris Lattner599ded12007-04-09 01:11:16 +000011038 // Inserting an undef or into an undefined place, remove this.
11039 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11040 ReplaceInstUsesWith(IE, VecOp);
11041
Chris Lattnerefb47352006-04-15 01:39:45 +000011042 // If the inserted element was extracted from some other vector, and if the
11043 // indexes are constant, try to turn this into a shufflevector operation.
11044 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11045 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11046 EI->getOperand(0)->getType() == IE.getType()) {
11047 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011048 unsigned ExtractedIdx =
11049 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011050 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011051
11052 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11053 return ReplaceInstUsesWith(IE, VecOp);
11054
11055 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11056 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11057
11058 // If we are extracting a value from a vector, then inserting it right
11059 // back into the same place, just use the input vector.
11060 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11061 return ReplaceInstUsesWith(IE, VecOp);
11062
11063 // We could theoretically do this for ANY input. However, doing so could
11064 // turn chains of insertelement instructions into a chain of shufflevector
11065 // instructions, and right now we do not merge shufflevectors. As such,
11066 // only do this in a situation where it is clear that there is benefit.
11067 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11068 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11069 // the values of VecOp, except then one read from EIOp0.
11070 // Build a new shuffle mask.
11071 std::vector<Constant*> Mask;
11072 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011073 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011074 else {
11075 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011076 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011077 NumVectorElts));
11078 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011079 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011080 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011081 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011082 }
11083
11084 // If this insertelement isn't used by some other insertelement, turn it
11085 // (and any insertelements it points to), into one big shuffle.
11086 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11087 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011088 Value *RHS = 0;
11089 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11090 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11091 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011092 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011093 }
11094 }
11095 }
11096
11097 return 0;
11098}
11099
11100
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011101Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11102 Value *LHS = SVI.getOperand(0);
11103 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011104 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011105
11106 bool MadeChange = false;
11107
Chris Lattner867b99f2006-10-05 06:55:50 +000011108 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011109 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011110 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11111
Chris Lattnere4929dd2007-01-05 07:36:08 +000011112 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011113 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011114 if (isa<UndefValue>(SVI.getOperand(1))) {
11115 // Scan to see if there are any references to the RHS. If so, replace them
11116 // with undef element refs and set MadeChange to true.
11117 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11118 if (Mask[i] >= e && Mask[i] != 2*e) {
11119 Mask[i] = 2*e;
11120 MadeChange = true;
11121 }
11122 }
11123
11124 if (MadeChange) {
11125 // Remap any references to RHS to use LHS.
11126 std::vector<Constant*> Elts;
11127 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11128 if (Mask[i] == 2*e)
11129 Elts.push_back(UndefValue::get(Type::Int32Ty));
11130 else
11131 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11132 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011133 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011134 }
11135 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011136
Chris Lattner863bcff2006-05-25 23:48:38 +000011137 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11138 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11139 if (LHS == RHS || isa<UndefValue>(LHS)) {
11140 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011141 // shuffle(undef,undef,mask) -> undef.
11142 return ReplaceInstUsesWith(SVI, LHS);
11143 }
11144
Chris Lattner863bcff2006-05-25 23:48:38 +000011145 // Remap any references to RHS to use LHS.
11146 std::vector<Constant*> Elts;
11147 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011148 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011149 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011150 else {
11151 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11152 (Mask[i] < e && isa<UndefValue>(LHS)))
11153 Mask[i] = 2*e; // Turn into undef.
11154 else
11155 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011156 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011157 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011158 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011159 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011160 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011161 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011162 LHS = SVI.getOperand(0);
11163 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011164 MadeChange = true;
11165 }
11166
Chris Lattner7b2e27922006-05-26 00:29:06 +000011167 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011168 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011169
Chris Lattner863bcff2006-05-25 23:48:38 +000011170 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11171 if (Mask[i] >= e*2) continue; // Ignore undef values.
11172 // Is this an identity shuffle of the LHS value?
11173 isLHSID &= (Mask[i] == i);
11174
11175 // Is this an identity shuffle of the RHS value?
11176 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011177 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011178
Chris Lattner863bcff2006-05-25 23:48:38 +000011179 // Eliminate identity shuffles.
11180 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11181 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011182
Chris Lattner7b2e27922006-05-26 00:29:06 +000011183 // If the LHS is a shufflevector itself, see if we can combine it with this
11184 // one without producing an unusual shuffle. Here we are really conservative:
11185 // we are absolutely afraid of producing a shuffle mask not in the input
11186 // program, because the code gen may not be smart enough to turn a merged
11187 // shuffle into two specific shuffles: it may produce worse code. As such,
11188 // we only merge two shuffles if the result is one of the two input shuffle
11189 // masks. In this case, merging the shuffles just removes one instruction,
11190 // which we know is safe. This is good for things like turning:
11191 // (splat(splat)) -> splat.
11192 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11193 if (isa<UndefValue>(RHS)) {
11194 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11195
11196 std::vector<unsigned> NewMask;
11197 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11198 if (Mask[i] >= 2*e)
11199 NewMask.push_back(2*e);
11200 else
11201 NewMask.push_back(LHSMask[Mask[i]]);
11202
11203 // If the result mask is equal to the src shuffle or this shuffle mask, do
11204 // the replacement.
11205 if (NewMask == LHSMask || NewMask == Mask) {
11206 std::vector<Constant*> Elts;
11207 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11208 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011209 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011210 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011211 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011212 }
11213 }
11214 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11215 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011216 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011217 }
11218 }
11219 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011220
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011221 return MadeChange ? &SVI : 0;
11222}
11223
11224
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011225
Chris Lattnerea1c4542004-12-08 23:43:58 +000011226
11227/// TryToSinkInstruction - Try to move the specified instruction from its
11228/// current block into the beginning of DestBlock, which can only happen if it's
11229/// safe to move the instruction past all of the instructions between it and the
11230/// end of its block.
11231static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11232 assert(I->hasOneUse() && "Invariants didn't hold!");
11233
Chris Lattner108e9022005-10-27 17:13:11 +000011234 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011235 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11236 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011237
Chris Lattnerea1c4542004-12-08 23:43:58 +000011238 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011239 if (isa<AllocaInst>(I) && I->getParent() ==
11240 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011241 return false;
11242
Chris Lattner96a52a62004-12-09 07:14:34 +000011243 // We can only sink load instructions if there is nothing between the load and
11244 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011245 if (I->mayReadFromMemory()) {
11246 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011247 Scan != E; ++Scan)
11248 if (Scan->mayWriteToMemory())
11249 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011250 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011251
Dan Gohman02dea8b2008-05-23 21:05:58 +000011252 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011253
Chris Lattner4bc5f802005-08-08 19:11:57 +000011254 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011255 ++NumSunkInst;
11256 return true;
11257}
11258
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011259
11260/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11261/// all reachable code to the worklist.
11262///
11263/// This has a couple of tricks to make the code faster and more powerful. In
11264/// particular, we constant fold and DCE instructions as we go, to avoid adding
11265/// them to the worklist (this significantly speeds up instcombine on code where
11266/// many instructions are dead or constant). Additionally, if we find a branch
11267/// whose condition is a known constant, we only visit the reachable successors.
11268///
11269static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011270 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011271 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011272 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011273 std::vector<BasicBlock*> Worklist;
11274 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011275
Chris Lattner2c7718a2007-03-23 19:17:18 +000011276 while (!Worklist.empty()) {
11277 BB = Worklist.back();
11278 Worklist.pop_back();
11279
11280 // We have now visited this block! If we've already been here, ignore it.
11281 if (!Visited.insert(BB)) continue;
11282
11283 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11284 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011285
Chris Lattner2c7718a2007-03-23 19:17:18 +000011286 // DCE instruction if trivially dead.
11287 if (isInstructionTriviallyDead(Inst)) {
11288 ++NumDeadInst;
11289 DOUT << "IC: DCE: " << *Inst;
11290 Inst->eraseFromParent();
11291 continue;
11292 }
11293
11294 // ConstantProp instruction if trivially constant.
11295 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11296 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11297 Inst->replaceAllUsesWith(C);
11298 ++NumConstProp;
11299 Inst->eraseFromParent();
11300 continue;
11301 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011302
Chris Lattner2c7718a2007-03-23 19:17:18 +000011303 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011304 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011305
11306 // Recursively visit successors. If this is a branch or switch on a
11307 // constant, only visit the reachable successor.
11308 TerminatorInst *TI = BB->getTerminator();
11309 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11310 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11311 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011312 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011313 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011314 continue;
11315 }
11316 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11317 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11318 // See if this is an explicit destination.
11319 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11320 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011321 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011322 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011323 continue;
11324 }
11325
11326 // Otherwise it is the default destination.
11327 Worklist.push_back(SI->getSuccessor(0));
11328 continue;
11329 }
11330 }
11331
11332 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11333 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011334 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011335}
11336
Chris Lattnerec9c3582007-03-03 02:04:50 +000011337bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011338 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011339 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011340
11341 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11342 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011343
Chris Lattnerb3d59702005-07-07 20:40:38 +000011344 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011345 // Do a depth-first traversal of the function, populate the worklist with
11346 // the reachable instructions. Ignore blocks that are not reachable. Keep
11347 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011348 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011349 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011350
Chris Lattnerb3d59702005-07-07 20:40:38 +000011351 // Do a quick scan over the function. If we find any blocks that are
11352 // unreachable, remove any instructions inside of them. This prevents
11353 // the instcombine code from having to deal with some bad special cases.
11354 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11355 if (!Visited.count(BB)) {
11356 Instruction *Term = BB->getTerminator();
11357 while (Term != BB->begin()) { // Remove instrs bottom-up
11358 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011359
Bill Wendlingb7427032006-11-26 09:46:52 +000011360 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011361 ++NumDeadInst;
11362
11363 if (!I->use_empty())
11364 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11365 I->eraseFromParent();
11366 }
11367 }
11368 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011369
Chris Lattnerdbab3862007-03-02 21:28:56 +000011370 while (!Worklist.empty()) {
11371 Instruction *I = RemoveOneFromWorkList();
11372 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011373
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011374 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011375 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011376 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011377 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011378 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011379 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011380
Bill Wendlingb7427032006-11-26 09:46:52 +000011381 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011382
11383 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011384 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011385 continue;
11386 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011387
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011388 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011389 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011390 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011391
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011392 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011393 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011394 ReplaceInstUsesWith(*I, C);
11395
Chris Lattner62b14df2002-09-02 04:59:56 +000011396 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011397 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011398 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011399 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011400 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011401
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011402 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11403 // See if we can constant fold its operands.
11404 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11405 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11406 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11407 i->set(NewC);
11408 }
11409 }
11410 }
11411
Chris Lattnerea1c4542004-12-08 23:43:58 +000011412 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011413 // FIXME: Remove GetResultInst test when first class support for aggregates
11414 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011415 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011416 BasicBlock *BB = I->getParent();
11417 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11418 if (UserParent != BB) {
11419 bool UserIsSuccessor = false;
11420 // See if the user is one of our successors.
11421 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11422 if (*SI == UserParent) {
11423 UserIsSuccessor = true;
11424 break;
11425 }
11426
11427 // If the user is one of our immediate successors, and if that successor
11428 // only has us as a predecessors (we'd have to split the critical edge
11429 // otherwise), we can keep going.
11430 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11431 next(pred_begin(UserParent)) == pred_end(UserParent))
11432 // Okay, the CFG is simple enough, try to sink this instruction.
11433 Changed |= TryToSinkInstruction(I, UserParent);
11434 }
11435 }
11436
Chris Lattner8a2a3112001-12-14 16:52:21 +000011437 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011438#ifndef NDEBUG
11439 std::string OrigI;
11440#endif
11441 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011442 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011443 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011444 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011445 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011446 DOUT << "IC: Old = " << *I
11447 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011448
Chris Lattnerf523d062004-06-09 05:08:07 +000011449 // Everything uses the new instruction now.
11450 I->replaceAllUsesWith(Result);
11451
11452 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011453 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011454 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011455
Chris Lattner6934a042007-02-11 01:23:03 +000011456 // Move the name to the new instruction first.
11457 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011458
11459 // Insert the new instruction into the basic block...
11460 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011461 BasicBlock::iterator InsertPos = I;
11462
11463 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11464 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11465 ++InsertPos;
11466
11467 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011468
Chris Lattner00d51312004-05-01 23:27:23 +000011469 // Make sure that we reprocess all operands now that we reduced their
11470 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011471 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011472
Chris Lattnerf523d062004-06-09 05:08:07 +000011473 // Instructions can end up on the worklist more than once. Make sure
11474 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011475 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011476
11477 // Erase the old instruction.
11478 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011479 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011480#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011481 DOUT << "IC: Mod = " << OrigI
11482 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011483#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011484
Chris Lattner90ac28c2002-08-02 19:29:35 +000011485 // If the instruction was modified, it's possible that it is now dead.
11486 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011487 if (isInstructionTriviallyDead(I)) {
11488 // Make sure we process all operands now that we are reducing their
11489 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011490 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011491
Chris Lattner00d51312004-05-01 23:27:23 +000011492 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011493 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011494 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011495 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011496 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011497 AddToWorkList(I);
11498 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011499 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011500 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011501 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011502 }
11503 }
11504
Chris Lattnerec9c3582007-03-03 02:04:50 +000011505 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011506
11507 // Do an explicit clear, this shrinks the map if needed.
11508 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011509 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011510}
11511
Chris Lattnerec9c3582007-03-03 02:04:50 +000011512
11513bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011514 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11515
Chris Lattnerec9c3582007-03-03 02:04:50 +000011516 bool EverMadeChange = false;
11517
11518 // Iterate while there is work to do.
11519 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011520 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011521 EverMadeChange = true;
11522 return EverMadeChange;
11523}
11524
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011525FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011526 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011527}
Brian Gaeked0fde302003-11-11 22:41:34 +000011528