blob: bc77ad5bf2b52257b33d5677a4452973d37e4171 [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 Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 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);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000183 Instruction *visitAnd(BinaryOperator &I);
184 Instruction *visitOr (BinaryOperator &I);
185 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000186 Instruction *visitShl(BinaryOperator &I);
187 Instruction *visitAShr(BinaryOperator &I);
188 Instruction *visitLShr(BinaryOperator &I);
189 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000190 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196 Instruction *LHS,
197 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000198 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000200
Reid Spencere4d87aa2006-12-23 06:05:41 +0000201 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000203 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000204 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000207 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000208 Instruction *visitTrunc(TruncInst &CI);
209 Instruction *visitZExt(ZExtInst &CI);
210 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000211 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000212 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000213 Instruction *visitFPToUI(FPToUIInst &FI);
214 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000215 Instruction *visitUIToFP(CastInst &CI);
216 Instruction *visitSIToFP(CastInst &CI);
217 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000218 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000219 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000222 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000223 Instruction *visitCallInst(CallInst &CI);
224 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000225 Instruction *visitPHINode(PHINode &PN);
226 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000227 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000228 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000229 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000230 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000231 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000232 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000233 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000234 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000235 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000236 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000237
238 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000240
Chris Lattner9fe38862003-06-19 17:00:31 +0000241 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000242 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000243 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000244 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000245 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
246 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000247 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000248
Chris Lattner28977af2004-04-05 01:30:19 +0000249 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000250 // InsertNewInstBefore - insert an instruction New before instruction Old
251 // in the program. Add the new instruction to the worklist.
252 //
Chris Lattner955f3312004-09-28 21:48:02 +0000253 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000254 assert(New && New->getParent() == 0 &&
255 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000256 BasicBlock *BB = Old.getParent();
257 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000258 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000259 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000260 }
261
Chris Lattner0c967662004-09-24 15:21:34 +0000262 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
263 /// This also adds the cast to the worklist. Finally, this returns the
264 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000265 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
266 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000267 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000268
Chris Lattnere2ed0572006-04-06 19:19:17 +0000269 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000270 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000271
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000272 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000273 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000274 return C;
275 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000276
277 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
278 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
279 }
280
Chris Lattner0c967662004-09-24 15:21:34 +0000281
Chris Lattner8b170942002-08-09 23:47:40 +0000282 // ReplaceInstUsesWith - This method is to be used when an instruction is
283 // found to be dead, replacable with another preexisting expression. Here
284 // we add all uses of I to the worklist, replace all uses of I with the new
285 // value, then return I, so that the inst combiner will know that I was
286 // modified.
287 //
288 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000289 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000290 if (&I != V) {
291 I.replaceAllUsesWith(V);
292 return &I;
293 } else {
294 // If we are replacing the instruction with itself, this must be in a
295 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000296 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000297 return &I;
298 }
Chris Lattner8b170942002-08-09 23:47:40 +0000299 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000300
Chris Lattner6dce1a72006-02-07 06:56:34 +0000301 // UpdateValueUsesWith - This method is to be used when an value is
302 // found to be replacable with another preexisting expression or was
303 // updated. Here we add all uses of I to the worklist, replace all uses of
304 // I with the new value (unless the instruction was just updated), then
305 // return true, so that the inst combiner will know that I was modified.
306 //
307 bool UpdateValueUsesWith(Value *Old, Value *New) {
308 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
309 if (Old != New)
310 Old->replaceAllUsesWith(New);
311 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000312 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000313 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000314 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000315 return true;
316 }
317
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
321 // this function.
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000325 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000326 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000327 return 0; // Don't do anything with FI
328 }
Chris Lattner173234a2008-06-02 01:18:21 +0000329
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333 }
334
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 }
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
341 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000342
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000343 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000344 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
345 /// InsertBefore instruction. This is specialized a bit to avoid inserting
346 /// casts that are known to not do anything...
347 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000348 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
349 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000350 Instruction *InsertBefore);
351
Reid Spencere4d87aa2006-12-23 06:05:41 +0000352 /// SimplifyCommutative - This performs a few simplifications for
353 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000354 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000355
Reid Spencere4d87aa2006-12-23 06:05:41 +0000356 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
357 /// most-complex to least-complex order.
358 bool SimplifyCompare(CmpInst &I);
359
Reid Spencer2ec619a2007-03-23 21:24:59 +0000360 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
361 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000362 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
363 APInt& KnownZero, APInt& KnownOne,
364 unsigned Depth = 0);
365
Chris Lattner867b99f2006-10-05 06:55:50 +0000366 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
367 uint64_t &UndefElts, unsigned Depth = 0);
368
Chris Lattner4e998b22004-09-29 05:07:12 +0000369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
373
Chris Lattnerbac32862004-11-14 19:13:23 +0000374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379
380
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000385 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000387 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000389 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000393
Chris Lattnerafe91a52006-06-15 19:07:26 +0000394
Reid Spencerc55b2432006-12-13 18:21:21 +0000395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396
Dan Gohmaneee962e2008-04-10 18:43:06 +0000397 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
398 unsigned CastOpc,
399 int &NumCastsRemoved);
400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000402
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000403 };
404}
405
Dan Gohman844731a2008-05-13 00:00:25 +0000406char InstCombiner::ID = 0;
407static RegisterPass<InstCombiner>
408X("instcombine", "Combine redundant instructions");
409
Chris Lattner4f98c562003-03-10 21:43:22 +0000410// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000411// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000412static unsigned getComplexity(Value *V) {
413 if (isa<Instruction>(V)) {
414 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000415 return 3;
416 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000417 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000418 if (isa<Argument>(V)) return 3;
419 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000420}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000421
Chris Lattnerc8802d22003-03-11 00:12:48 +0000422// isOnlyUse - Return true if this instruction will be deleted if we stop using
423// it.
424static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000425 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000426}
427
Chris Lattner4cb170c2004-02-23 06:38:22 +0000428// getPromotedType - Return the specified type promoted as it would be to pass
429// though a va_arg area...
430static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000431 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432 if (ITy->getBitWidth() < 32)
433 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000434 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000435 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000436}
437
Reid Spencer3da59db2006-11-27 01:05:10 +0000438/// getBitCastOperand - If the specified operand is a CastInst or a constant
439/// expression bitcast, return the operand value, otherwise return null.
440static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000442 return I->getOperand(0);
443 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000444 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000445 return CE->getOperand(0);
446 return 0;
447}
448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449/// This function is a wrapper around CastInst::isEliminableCastPair. It
450/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000451static Instruction::CastOps
452isEliminableCastPair(
453 const CastInst *CI, ///< The first cast instruction
454 unsigned opcode, ///< The opcode of the second cast instruction
455 const Type *DstTy, ///< The target type for the second cast instruction
456 TargetData *TD ///< The target data for pointer size
457) {
458
459 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
460 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000461
Reid Spencer3da59db2006-11-27 01:05:10 +0000462 // Get the opcodes of the two Cast instructions
463 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
464 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000465
Reid Spencer3da59db2006-11-27 01:05:10 +0000466 return Instruction::CastOps(
467 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
468 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000469}
470
471/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
472/// in any code being generated. It does not require codegen if V is simple
473/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000474static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
475 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000476 if (V->getType() == Ty || isa<Constant>(V)) return false;
477
Chris Lattner01575b72006-05-25 23:24:33 +0000478 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000479 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000480 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000481 return false;
482 return true;
483}
484
485/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
486/// InsertBefore instruction. This is specialized a bit to avoid inserting
487/// casts that are known to not do anything...
488///
Reid Spencer17212df2006-12-12 09:18:51 +0000489Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
490 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000491 Instruction *InsertBefore) {
492 if (V->getType() == DestTy) return V;
493 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000494 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000495
Reid Spencer17212df2006-12-12 09:18:51 +0000496 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000497}
498
Chris Lattner4f98c562003-03-10 21:43:22 +0000499// SimplifyCommutative - This performs a few simplifications for commutative
500// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000501//
Chris Lattner4f98c562003-03-10 21:43:22 +0000502// 1. Order operands such that they are listed from right (least complex) to
503// left (most complex). This puts constants before unary operators before
504// binary operators.
505//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000508//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000509bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 bool Changed = false;
511 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
512 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000513
Chris Lattner4f98c562003-03-10 21:43:22 +0000514 if (!I.isAssociative()) return Changed;
515 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 Constant *Folded = ConstantExpr::get(I.getOpcode(),
520 cast<Constant>(I.getOperand(1)),
521 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000522 I.setOperand(0, Op->getOperand(0));
523 I.setOperand(1, Folded);
524 return true;
525 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527 isOnlyUse(Op) && isOnlyUse(Op1)) {
528 Constant *C1 = cast<Constant>(Op->getOperand(1));
529 Constant *C2 = cast<Constant>(Op1->getOperand(1));
530
531 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000532 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000533 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534 Op1->getOperand(0),
535 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000536 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 I.setOperand(0, New);
538 I.setOperand(1, Folded);
539 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000540 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000541 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000542 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000543}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000544
Reid Spencere4d87aa2006-12-23 06:05:41 +0000545/// SimplifyCompare - For a CmpInst this function just orders the operands
546/// so that theyare listed from right (least complex) to left (most complex).
547/// This puts constants before unary operators before binary operators.
548bool InstCombiner::SimplifyCompare(CmpInst &I) {
549 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
550 return false;
551 I.swapOperands();
552 // Compare instructions are not associative so there's nothing else we can do.
553 return true;
554}
555
Chris Lattner8d969642003-03-10 23:06:50 +0000556// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000558//
Chris Lattner8d969642003-03-10 23:06:50 +0000559static inline Value *dyn_castNegVal(Value *V) {
560 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000561 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000562
Chris Lattner0ce85802004-12-14 20:08:06 +0000563 // Constants can be considered to be negated values if they can be folded.
564 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000566
567 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568 if (C->getType()->getElementType()->isInteger())
569 return ConstantExpr::getNeg(C);
570
Chris Lattner8d969642003-03-10 23:06:50 +0000571 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000572}
573
Chris Lattner8d969642003-03-10 23:06:50 +0000574static inline Value *dyn_castNotVal(Value *V) {
575 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000576 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000577
578 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000580 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000581 return 0;
582}
583
Chris Lattnerc8802d22003-03-11 00:12:48 +0000584// dyn_castFoldableMul - If this value is a multiply that can be folded into
585// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000586// non-constant operand of the multiply, and set CST to point to the multiplier.
587// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000588//
Chris Lattner50af16a2004-11-13 19:50:12 +0000589static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000590 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000591 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000592 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000594 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000595 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000596 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000597 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000598 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000599 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000600 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000601 return I->getOperand(0);
602 }
603 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000604 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000605}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000606
Chris Lattner574da9b2005-01-13 20:14:25 +0000607/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
608/// expression, return it.
609static User *dyn_castGetElementPtr(Value *V) {
610 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
611 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
612 if (CE->getOpcode() == Instruction::GetElementPtr)
613 return cast<User>(V);
614 return false;
615}
616
Dan Gohmaneee962e2008-04-10 18:43:06 +0000617/// getOpcode - If this is an Instruction or a ConstantExpr, return the
618/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000619static unsigned getOpcode(const Value *V) {
620 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000621 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000622 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000623 return CE->getOpcode();
624 // Use UserOp1 to mean there's no opcode.
625 return Instruction::UserOp1;
626}
627
Reid Spencer7177c3a2007-03-25 05:33:51 +0000628/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000629static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000630 APInt Val(C->getValue());
631 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000632}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000633/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000634static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000635 APInt Val(C->getValue());
636 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000637}
638/// Add - Add two ConstantInts together
639static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
640 return ConstantInt::get(C1->getValue() + C2->getValue());
641}
642/// And - Bitwise AND two ConstantInts together
643static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() & C2->getValue());
645}
646/// Subtract - Subtract one ConstantInt from another
647static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() - C2->getValue());
649}
650/// Multiply - Multiply two ConstantInts together
651static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000653}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000654/// MultiplyOverflows - True if the multiply can not be expressed in an int
655/// this size.
656static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
657 uint32_t W = C1->getBitWidth();
658 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
659 if (sign) {
660 LHSExt.sext(W * 2);
661 RHSExt.sext(W * 2);
662 } else {
663 LHSExt.zext(W * 2);
664 RHSExt.zext(W * 2);
665 }
666
667 APInt MulExt = LHSExt * RHSExt;
668
669 if (sign) {
670 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672 return MulExt.slt(Min) || MulExt.sgt(Max);
673 } else
674 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
675}
Chris Lattner955f3312004-09-28 21:48:02 +0000676
Reid Spencere7816b52007-03-08 01:52:58 +0000677
Chris Lattner255d8912006-02-11 09:31:47 +0000678/// ShrinkDemandedConstant - Check to see if the specified operand of the
679/// specified instruction is a constant integer. If so, check to see if there
680/// are any bits set in the constant that are not demanded. If so, shrink the
681/// constant and return true.
682static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000683 APInt Demanded) {
684 assert(I && "No instruction?");
685 assert(OpNo < I->getNumOperands() && "Operand index too large");
686
687 // If the operand is not a constant integer, nothing to do.
688 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689 if (!OpC) return false;
690
691 // If there are no bits set that aren't demanded, nothing to do.
692 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693 if ((~Demanded & OpC->getValue()) == 0)
694 return false;
695
696 // This instruction is producing bits that are not demanded. Shrink the RHS.
697 Demanded &= OpC->getValue();
698 I->setOperand(OpNo, ConstantInt::get(Demanded));
699 return true;
700}
701
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000702// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
703// set of known zero and one bits, compute the maximum and minimum values that
704// could have the specified known zero and known one bits, returning them in
705// min/max.
706static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000707 const APInt& KnownZero,
708 const APInt& KnownOne,
709 APInt& Min, APInt& Max) {
710 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
711 assert(KnownZero.getBitWidth() == BitWidth &&
712 KnownOne.getBitWidth() == BitWidth &&
713 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
714 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000715 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000716
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718 // bit if it is unknown.
719 Min = KnownOne;
720 Max = KnownOne|UnknownBits;
721
Zhou Sheng4acf1552007-03-28 05:15:57 +0000722 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000723 Min.set(BitWidth-1);
724 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726}
727
728// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729// a set of known zero and one bits, compute the maximum and minimum values that
730// could have the specified known zero and known one bits, returning them in
731// min/max.
732static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000733 const APInt &KnownZero,
734 const APInt &KnownOne,
735 APInt &Min, APInt &Max) {
736 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000737 assert(KnownZero.getBitWidth() == BitWidth &&
738 KnownOne.getBitWidth() == BitWidth &&
739 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
740 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000741 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000742
743 // The minimum value is when the unknown bits are all zeros.
744 Min = KnownOne;
745 // The maximum value is when the unknown bits are all ones.
746 Max = KnownOne|UnknownBits;
747}
Chris Lattner255d8912006-02-11 09:31:47 +0000748
Reid Spencer8cb68342007-03-12 17:25:59 +0000749/// SimplifyDemandedBits - This function attempts to replace V with a simpler
750/// value based on the demanded bits. When this function is called, it is known
751/// that only the bits set in DemandedMask of the result of V are ever used
752/// downstream. Consequently, depending on the mask and V, it may be possible
753/// to replace V with a constant or one of its operands. In such cases, this
754/// function does the replacement and returns true. In all other cases, it
755/// returns false after analyzing the expression and setting KnownOne and known
756/// to be one in the expression. KnownZero contains all the bits that are known
757/// to be zero in the expression. These are provided to potentially allow the
758/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
759/// the expression. KnownOne and KnownZero always follow the invariant that
760/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
761/// the bits in KnownOne and KnownZero may only be accurate for those bits set
762/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
763/// and KnownOne must all be the same.
764bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
765 APInt& KnownZero, APInt& KnownOne,
766 unsigned Depth) {
767 assert(V != 0 && "Null pointer of Value???");
768 assert(Depth <= 6 && "Limit Search Depth");
769 uint32_t BitWidth = DemandedMask.getBitWidth();
770 const IntegerType *VTy = cast<IntegerType>(V->getType());
771 assert(VTy->getBitWidth() == BitWidth &&
772 KnownZero.getBitWidth() == BitWidth &&
773 KnownOne.getBitWidth() == BitWidth &&
774 "Value *V, DemandedMask, KnownZero and KnownOne \
775 must have same BitWidth");
776 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
777 // We know all of the bits for a constant!
778 KnownOne = CI->getValue() & DemandedMask;
779 KnownZero = ~KnownOne & DemandedMask;
780 return false;
781 }
782
Zhou Sheng96704452007-03-14 03:21:24 +0000783 KnownZero.clear();
784 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000785 if (!V->hasOneUse()) { // Other users may use these bits.
786 if (Depth != 0) { // Not at the root.
787 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
788 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
789 return false;
790 }
791 // If this is the root being simplified, allow it to have multiple uses,
792 // just set the DemandedMask to all bits.
793 DemandedMask = APInt::getAllOnesValue(BitWidth);
794 } else if (DemandedMask == 0) { // Not demanding any bits from V.
795 if (V != UndefValue::get(VTy))
796 return UpdateValueUsesWith(V, UndefValue::get(VTy));
797 return false;
798 } else if (Depth == 6) { // Limit search depth.
799 return false;
800 }
801
802 Instruction *I = dyn_cast<Instruction>(V);
803 if (!I) return false; // Only analyze instructions.
804
Reid Spencer8cb68342007-03-12 17:25:59 +0000805 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
806 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
807 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000808 default:
809 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
810 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000811 case Instruction::And:
812 // If either the LHS or the RHS are Zero, the result is zero.
813 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
814 RHSKnownZero, RHSKnownOne, Depth+1))
815 return true;
816 assert((RHSKnownZero & RHSKnownOne) == 0 &&
817 "Bits known to be one AND zero?");
818
819 // If something is known zero on the RHS, the bits aren't demanded on the
820 // LHS.
821 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
822 LHSKnownZero, LHSKnownOne, Depth+1))
823 return true;
824 assert((LHSKnownZero & LHSKnownOne) == 0 &&
825 "Bits known to be one AND zero?");
826
827 // If all of the demanded bits are known 1 on one side, return the other.
828 // These bits cannot contribute to the result of the 'and'.
829 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
830 (DemandedMask & ~LHSKnownZero))
831 return UpdateValueUsesWith(I, I->getOperand(0));
832 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
833 (DemandedMask & ~RHSKnownZero))
834 return UpdateValueUsesWith(I, I->getOperand(1));
835
836 // If all of the demanded bits in the inputs are known zeros, return zero.
837 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
838 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
839
840 // If the RHS is a constant, see if we can simplify it.
841 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
842 return UpdateValueUsesWith(I, I);
843
844 // Output known-1 bits are only known if set in both the LHS & RHS.
845 RHSKnownOne &= LHSKnownOne;
846 // Output known-0 are known to be clear if zero in either the LHS | RHS.
847 RHSKnownZero |= LHSKnownZero;
848 break;
849 case Instruction::Or:
850 // If either the LHS or the RHS are One, the result is One.
851 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1))
853 return true;
854 assert((RHSKnownZero & RHSKnownOne) == 0 &&
855 "Bits known to be one AND zero?");
856 // If something is known one on the RHS, the bits aren't demanded on the
857 // LHS.
858 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
859 LHSKnownZero, LHSKnownOne, Depth+1))
860 return true;
861 assert((LHSKnownZero & LHSKnownOne) == 0 &&
862 "Bits known to be one AND zero?");
863
864 // If all of the demanded bits are known zero on one side, return the other.
865 // These bits cannot contribute to the result of the 'or'.
866 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
867 (DemandedMask & ~LHSKnownOne))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
870 (DemandedMask & ~RHSKnownOne))
871 return UpdateValueUsesWith(I, I->getOperand(1));
872
873 // If all of the potentially set bits on one side are known to be set on
874 // the other side, just use the 'other' side.
875 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
876 (DemandedMask & (~RHSKnownZero)))
877 return UpdateValueUsesWith(I, I->getOperand(0));
878 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
879 (DemandedMask & (~LHSKnownZero)))
880 return UpdateValueUsesWith(I, I->getOperand(1));
881
882 // If the RHS is a constant, see if we can simplify it.
883 if (ShrinkDemandedConstant(I, 1, DemandedMask))
884 return UpdateValueUsesWith(I, I);
885
886 // Output known-0 bits are only known if clear in both the LHS & RHS.
887 RHSKnownZero &= LHSKnownZero;
888 // Output known-1 are known to be set if set in either the LHS | RHS.
889 RHSKnownOne |= LHSKnownOne;
890 break;
891 case Instruction::Xor: {
892 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893 RHSKnownZero, RHSKnownOne, Depth+1))
894 return true;
895 assert((RHSKnownZero & RHSKnownOne) == 0 &&
896 "Bits known to be one AND zero?");
897 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
898 LHSKnownZero, LHSKnownOne, Depth+1))
899 return true;
900 assert((LHSKnownZero & LHSKnownOne) == 0 &&
901 "Bits known to be one AND zero?");
902
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'xor'.
905 if ((DemandedMask & RHSKnownZero) == DemandedMask)
906 return UpdateValueUsesWith(I, I->getOperand(0));
907 if ((DemandedMask & LHSKnownZero) == DemandedMask)
908 return UpdateValueUsesWith(I, I->getOperand(1));
909
910 // Output known-0 bits are known if clear or set in both the LHS & RHS.
911 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
912 (RHSKnownOne & LHSKnownOne);
913 // Output known-1 are known to be set if set in only one of the LHS, RHS.
914 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
915 (RHSKnownOne & LHSKnownZero);
916
917 // If all of the demanded bits are known to be zero on one side or the
918 // other, turn this into an *inclusive* or.
919 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
920 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
921 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000922 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 I->getName());
924 InsertNewInstBefore(Or, *I);
925 return UpdateValueUsesWith(I, Or);
926 }
927
928 // If all of the demanded bits on one side are known, and all of the set
929 // bits on that side are also known to be set on the other side, turn this
930 // into an AND, as we know the bits will be cleared.
931 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
932 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
933 // all known
934 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
935 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
936 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000937 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 InsertNewInstBefore(And, *I);
939 return UpdateValueUsesWith(I, And);
940 }
941 }
942
943 // If the RHS is a constant, see if we can simplify it.
944 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
945 if (ShrinkDemandedConstant(I, 1, DemandedMask))
946 return UpdateValueUsesWith(I, I);
947
948 RHSKnownZero = KnownZeroOut;
949 RHSKnownOne = KnownOneOut;
950 break;
951 }
952 case Instruction::Select:
953 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
954 RHSKnownZero, RHSKnownOne, Depth+1))
955 return true;
956 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
957 LHSKnownZero, LHSKnownOne, Depth+1))
958 return true;
959 assert((RHSKnownZero & RHSKnownOne) == 0 &&
960 "Bits known to be one AND zero?");
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963
964 // If the operands are constants, see if we can simplify them.
965 if (ShrinkDemandedConstant(I, 1, DemandedMask))
966 return UpdateValueUsesWith(I, I);
967 if (ShrinkDemandedConstant(I, 2, DemandedMask))
968 return UpdateValueUsesWith(I, I);
969
970 // Only known if known in both the LHS and RHS.
971 RHSKnownOne &= LHSKnownOne;
972 RHSKnownZero &= LHSKnownZero;
973 break;
974 case Instruction::Trunc: {
975 uint32_t truncBf =
976 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000977 DemandedMask.zext(truncBf);
978 RHSKnownZero.zext(truncBf);
979 RHSKnownOne.zext(truncBf);
980 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
981 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000982 return true;
983 DemandedMask.trunc(BitWidth);
984 RHSKnownZero.trunc(BitWidth);
985 RHSKnownOne.trunc(BitWidth);
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
988 break;
989 }
990 case Instruction::BitCast:
991 if (!I->getOperand(0)->getType()->isInteger())
992 return false;
993
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995 RHSKnownZero, RHSKnownOne, Depth+1))
996 return true;
997 assert((RHSKnownZero & RHSKnownOne) == 0 &&
998 "Bits known to be one AND zero?");
999 break;
1000 case Instruction::ZExt: {
1001 // Compute the bits in the result that are not present in the input.
1002 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001003 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001004
Zhou Shengd48653a2007-03-29 04:45:55 +00001005 DemandedMask.trunc(SrcBitWidth);
1006 RHSKnownZero.trunc(SrcBitWidth);
1007 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001010 return true;
1011 DemandedMask.zext(BitWidth);
1012 RHSKnownZero.zext(BitWidth);
1013 RHSKnownOne.zext(BitWidth);
1014 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1015 "Bits known to be one AND zero?");
1016 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001017 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001018 break;
1019 }
1020 case Instruction::SExt: {
1021 // Compute the bits in the result that are not present in the input.
1022 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001023 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001024
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001026 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001027
Zhou Sheng01542f32007-03-29 02:26:30 +00001028 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 // If any of the sign extended bits are demanded, we know that the sign
1030 // bit is demanded.
1031 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001032 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001033
Zhou Shengd48653a2007-03-29 04:45:55 +00001034 InputDemandedBits.trunc(SrcBitWidth);
1035 RHSKnownZero.trunc(SrcBitWidth);
1036 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001037 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1038 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001039 return true;
1040 InputDemandedBits.zext(BitWidth);
1041 RHSKnownZero.zext(BitWidth);
1042 RHSKnownOne.zext(BitWidth);
1043 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1044 "Bits known to be one AND zero?");
1045
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
1048
1049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001051 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001052 {
1053 // Convert to ZExt cast
1054 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1055 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001056 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001058 }
1059 break;
1060 }
1061 case Instruction::Add: {
1062 // Figure out what the input bits are. If the top bits of the and result
1063 // are not demanded, then the add doesn't demand them from its input
1064 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001065 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001066
1067 // If there is a constant on the RHS, there are a variety of xformations
1068 // we can do.
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1072 if (RHS->isZero())
1073 break;
1074
1075 // If the top bit of the output is demanded, demand everything from the
1076 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001077 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001078
1079 // Find information about known zero/one bits in the input.
1080 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1082 return true;
1083
1084 // If the RHS of the add has bits set that can't affect the input, reduce
1085 // the constant.
1086 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1087 return UpdateValueUsesWith(I, I);
1088
1089 // Avoid excess work.
1090 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1091 break;
1092
1093 // Turn it into OR if input bits are zero.
1094 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1095 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001096 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 I->getName());
1098 InsertNewInstBefore(Or, *I);
1099 return UpdateValueUsesWith(I, Or);
1100 }
1101
1102 // We can say something about the output known-zero and known-one bits,
1103 // depending on potential carries from the input constant and the
1104 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1105 // bits set and the RHS constant is 0x01001, then we know we have a known
1106 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1107
1108 // To compute this, we first compute the potential carry bits. These are
1109 // the bits which may be modified. I'm not aware of a better way to do
1110 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001111 const APInt& RHSVal = RHS->getValue();
1112 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001113
1114 // Now that we know which bits have carries, compute the known-1/0 sets.
1115
1116 // Bits are known one if they are known zero in one operand and one in the
1117 // other, and there is no input carry.
1118 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1119 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1120
1121 // Bits are known zero if they are known zero in both operands and there
1122 // is no input carry.
1123 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1124 } else {
1125 // If the high-bits of this ADD are not demanded, then it does not demand
1126 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001127 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001128 // Right fill the mask of bits for this ADD to demand the most
1129 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001130 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1132 LHSKnownZero, LHSKnownOne, Depth+1))
1133 return true;
1134 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1135 LHSKnownZero, LHSKnownOne, Depth+1))
1136 return true;
1137 }
1138 }
1139 break;
1140 }
1141 case Instruction::Sub:
1142 // If the high-bits of this SUB are not demanded, then it does not demand
1143 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 // Right fill the mask of bits for this SUB to demand the most
1146 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001147 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001148 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1))
1151 return true;
1152 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1153 LHSKnownZero, LHSKnownOne, Depth+1))
1154 return true;
1155 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001156 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1157 // the known zeros and ones.
1158 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001159 break;
1160 case Instruction::Shl:
1161 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001162 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001163 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 RHSKnownZero, RHSKnownOne, Depth+1))
1166 return true;
1167 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1168 "Bits known to be one AND zero?");
1169 RHSKnownZero <<= ShiftAmt;
1170 RHSKnownOne <<= ShiftAmt;
1171 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001172 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001173 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001174 }
1175 break;
1176 case Instruction::LShr:
1177 // For a logical shift right
1178 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001179 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001182 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1183 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001184 RHSKnownZero, RHSKnownOne, Depth+1))
1185 return true;
1186 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1187 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1189 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001190 if (ShiftAmt) {
1191 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001193 RHSKnownZero |= HighBits; // high bits known zero.
1194 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 }
1196 break;
1197 case Instruction::AShr:
1198 // If this is an arithmetic shift right and only the low-bit is set, we can
1199 // always convert this into a logical shr, even if the shift amount is
1200 // variable. The low bit of the shift cannot be an input sign bit unless
1201 // the shift amount is >= the size of the datatype, which is undefined.
1202 if (DemandedMask == 1) {
1203 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001204 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 I->getOperand(0), I->getOperand(1), I->getName());
1206 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207 return UpdateValueUsesWith(I, NewVal);
1208 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001209
1210 // If the sign bit is the only bit demanded by this ashr, then there is no
1211 // need to do it, the shift doesn't change the high bit.
1212 if (DemandedMask.isSignBit())
1213 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001216 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001219 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001220 // If any of the "high bits" are demanded, we should set the sign bit as
1221 // demanded.
1222 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1223 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001225 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 RHSKnownZero, RHSKnownOne, Depth+1))
1227 return true;
1228 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1229 "Bits known to be one AND zero?");
1230 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1233 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1234
1235 // Handle the sign bits.
1236 APInt SignBit(APInt::getSignBit(BitWidth));
1237 // Adjust to where it is now in the mask.
1238 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1239
1240 // If the input sign bit is known to be zero, or if none of the top bits
1241 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001242 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 (HighBits & ~DemandedMask) == HighBits) {
1244 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001245 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 I->getOperand(0), SA, I->getName());
1247 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1248 return UpdateValueUsesWith(I, NewVal);
1249 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1250 RHSKnownOne |= HighBits;
1251 }
1252 }
1253 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001254 case Instruction::SRem:
1255 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256 APInt RA = Rem->getValue();
1257 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001258 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1259 return UpdateValueUsesWith(I, I->getOperand(0));
1260
Dan Gohman23e1df82008-05-06 00:51:48 +00001261 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001262 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1263 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1264 LHSKnownZero, LHSKnownOne, Depth+1))
1265 return true;
1266
1267 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1268 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001269
1270 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001271
1272 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1273 }
1274 }
1275 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001276 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001277 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1278 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001279 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1280 KnownZero2, KnownOne2, Depth+1))
1281 return true;
1282
Dan Gohman23e8b712008-04-28 17:02:21 +00001283 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001284 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001285 KnownZero2, KnownOne2, Depth+1))
1286 return true;
1287
1288 Leaders = std::max(Leaders,
1289 KnownZero2.countLeadingOnes());
1290 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001291 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001293 case Instruction::Call:
1294 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1295 switch (II->getIntrinsicID()) {
1296 default: break;
1297 case Intrinsic::bswap: {
1298 // If the only bits demanded come from one byte of the bswap result,
1299 // just shift the input byte into position to eliminate the bswap.
1300 unsigned NLZ = DemandedMask.countLeadingZeros();
1301 unsigned NTZ = DemandedMask.countTrailingZeros();
1302
1303 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1304 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1305 // have 14 leading zeros, round to 8.
1306 NLZ &= ~7;
1307 NTZ &= ~7;
1308 // If we need exactly one byte, we can do this transformation.
1309 if (BitWidth-NLZ-NTZ == 8) {
1310 unsigned ResultBit = NTZ;
1311 unsigned InputBit = BitWidth-NTZ-8;
1312
1313 // Replace this with either a left or right shift to get the byte into
1314 // the right place.
1315 Instruction *NewVal;
1316 if (InputBit > ResultBit)
1317 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1318 ConstantInt::get(I->getType(), InputBit-ResultBit));
1319 else
1320 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1321 ConstantInt::get(I->getType(), ResultBit-InputBit));
1322 NewVal->takeName(I);
1323 InsertNewInstBefore(NewVal, *I);
1324 return UpdateValueUsesWith(I, NewVal);
1325 }
1326
1327 // TODO: Could compute known zero/one bits based on the input.
1328 break;
1329 }
1330 }
1331 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001332 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001333 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001334 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001335
1336 // If the client is only demanding bits that we know, return the known
1337 // constant.
1338 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1339 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1340 return false;
1341}
1342
Chris Lattner867b99f2006-10-05 06:55:50 +00001343
1344/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1345/// 64 or fewer elements. DemandedElts contains the set of elements that are
1346/// actually used by the caller. This method analyzes which elements of the
1347/// operand are undef and returns that information in UndefElts.
1348///
1349/// If the information about demanded elements can be used to simplify the
1350/// operation, the operation is simplified, then the resultant value is
1351/// returned. This returns null if no change was made.
1352Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1353 uint64_t &UndefElts,
1354 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001355 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001356 assert(VWidth <= 64 && "Vector too wide to analyze!");
1357 uint64_t EltMask = ~0ULL >> (64-VWidth);
1358 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1359 "Invalid DemandedElts!");
1360
1361 if (isa<UndefValue>(V)) {
1362 // If the entire vector is undefined, just return this info.
1363 UndefElts = EltMask;
1364 return 0;
1365 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1366 UndefElts = EltMask;
1367 return UndefValue::get(V->getType());
1368 }
1369
1370 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001371 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1372 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001373 Constant *Undef = UndefValue::get(EltTy);
1374
1375 std::vector<Constant*> Elts;
1376 for (unsigned i = 0; i != VWidth; ++i)
1377 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1378 Elts.push_back(Undef);
1379 UndefElts |= (1ULL << i);
1380 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else { // Otherwise, defined.
1384 Elts.push_back(CP->getOperand(i));
1385 }
1386
1387 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001388 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001389 return NewCP != CP ? NewCP : 0;
1390 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001391 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001392 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001393 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001394 Constant *Zero = Constant::getNullValue(EltTy);
1395 Constant *Undef = UndefValue::get(EltTy);
1396 std::vector<Constant*> Elts;
1397 for (unsigned i = 0; i != VWidth; ++i)
1398 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1399 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001400 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001401 }
1402
1403 if (!V->hasOneUse()) { // Other users may use these bits.
1404 if (Depth != 0) { // Not at the root.
1405 // TODO: Just compute the UndefElts information recursively.
1406 return false;
1407 }
1408 return false;
1409 } else if (Depth == 10) { // Limit search depth.
1410 return false;
1411 }
1412
1413 Instruction *I = dyn_cast<Instruction>(V);
1414 if (!I) return false; // Only analyze instructions.
1415
1416 bool MadeChange = false;
1417 uint64_t UndefElts2;
1418 Value *TmpV;
1419 switch (I->getOpcode()) {
1420 default: break;
1421
1422 case Instruction::InsertElement: {
1423 // If this is a variable index, we don't know which element it overwrites.
1424 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001425 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001426 if (Idx == 0) {
1427 // Note that we can't propagate undef elt info, because we don't know
1428 // which elt is getting updated.
1429 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1430 UndefElts2, Depth+1);
1431 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1432 break;
1433 }
1434
1435 // If this is inserting an element that isn't demanded, remove this
1436 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001437 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1439 return AddSoonDeadInstToWorklist(*I, 0);
1440
1441 // Otherwise, the element inserted overwrites whatever was there, so the
1442 // input demanded set is simpler than the output set.
1443 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1444 DemandedElts & ~(1ULL << IdxNo),
1445 UndefElts, Depth+1);
1446 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1447
1448 // The inserted element is defined.
1449 UndefElts |= 1ULL << IdxNo;
1450 break;
1451 }
Chris Lattner69878332007-04-14 22:29:23 +00001452 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001453 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001454 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1455 if (!VTy) break;
1456 unsigned InVWidth = VTy->getNumElements();
1457 uint64_t InputDemandedElts = 0;
1458 unsigned Ratio;
1459
1460 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001461 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001462 // elements as are demanded of us.
1463 Ratio = 1;
1464 InputDemandedElts = DemandedElts;
1465 } else if (VWidth > InVWidth) {
1466 // Untested so far.
1467 break;
1468
1469 // If there are more elements in the result than there are in the source,
1470 // then an input element is live if any of the corresponding output
1471 // elements are live.
1472 Ratio = VWidth/InVWidth;
1473 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1474 if (DemandedElts & (1ULL << OutIdx))
1475 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1476 }
1477 } else {
1478 // Untested so far.
1479 break;
1480
1481 // If there are more elements in the source than there are in the result,
1482 // then an input element is live if the corresponding output element is
1483 // live.
1484 Ratio = InVWidth/VWidth;
1485 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1486 if (DemandedElts & (1ULL << InIdx/Ratio))
1487 InputDemandedElts |= 1ULL << InIdx;
1488 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001489
Chris Lattner69878332007-04-14 22:29:23 +00001490 // div/rem demand all inputs, because they don't want divide by zero.
1491 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1492 UndefElts2, Depth+1);
1493 if (TmpV) {
1494 I->setOperand(0, TmpV);
1495 MadeChange = true;
1496 }
1497
1498 UndefElts = UndefElts2;
1499 if (VWidth > InVWidth) {
1500 assert(0 && "Unimp");
1501 // If there are more elements in the result than there are in the source,
1502 // then an output element is undef if the corresponding input element is
1503 // undef.
1504 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1505 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1506 UndefElts |= 1ULL << OutIdx;
1507 } else if (VWidth < InVWidth) {
1508 assert(0 && "Unimp");
1509 // If there are more elements in the source than there are in the result,
1510 // then a result element is undef if all of the corresponding input
1511 // elements are undef.
1512 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1513 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1514 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1515 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1516 }
1517 break;
1518 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001519 case Instruction::And:
1520 case Instruction::Or:
1521 case Instruction::Xor:
1522 case Instruction::Add:
1523 case Instruction::Sub:
1524 case Instruction::Mul:
1525 // div/rem demand all inputs, because they don't want divide by zero.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1530 UndefElts2, Depth+1);
1531 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1532
1533 // Output elements are undefined if both are undefined. Consider things
1534 // like undef&0. The result is known zero, not undef.
1535 UndefElts &= UndefElts2;
1536 break;
1537
1538 case Instruction::Call: {
1539 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1540 if (!II) break;
1541 switch (II->getIntrinsicID()) {
1542 default: break;
1543
1544 // Binary vector operations that work column-wise. A dest element is a
1545 // function of the corresponding input elements from the two inputs.
1546 case Intrinsic::x86_sse_sub_ss:
1547 case Intrinsic::x86_sse_mul_ss:
1548 case Intrinsic::x86_sse_min_ss:
1549 case Intrinsic::x86_sse_max_ss:
1550 case Intrinsic::x86_sse2_sub_sd:
1551 case Intrinsic::x86_sse2_mul_sd:
1552 case Intrinsic::x86_sse2_min_sd:
1553 case Intrinsic::x86_sse2_max_sd:
1554 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1555 UndefElts, Depth+1);
1556 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1557 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1558 UndefElts2, Depth+1);
1559 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1560
1561 // If only the low elt is demanded and this is a scalarizable intrinsic,
1562 // scalarize it now.
1563 if (DemandedElts == 1) {
1564 switch (II->getIntrinsicID()) {
1565 default: break;
1566 case Intrinsic::x86_sse_sub_ss:
1567 case Intrinsic::x86_sse_mul_ss:
1568 case Intrinsic::x86_sse2_sub_sd:
1569 case Intrinsic::x86_sse2_mul_sd:
1570 // TODO: Lower MIN/MAX/ABS/etc
1571 Value *LHS = II->getOperand(1);
1572 Value *RHS = II->getOperand(2);
1573 // Extract the element as scalars.
1574 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1575 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1576
1577 switch (II->getIntrinsicID()) {
1578 default: assert(0 && "Case stmts out of sync!");
1579 case Intrinsic::x86_sse_sub_ss:
1580 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001581 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001582 II->getName()), *II);
1583 break;
1584 case Intrinsic::x86_sse_mul_ss:
1585 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001586 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001587 II->getName()), *II);
1588 break;
1589 }
1590
1591 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001592 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1593 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001594 InsertNewInstBefore(New, *II);
1595 AddSoonDeadInstToWorklist(*II, 0);
1596 return New;
1597 }
1598 }
1599
1600 // Output elements are undefined if both are undefined. Consider things
1601 // like undef&0. The result is known zero, not undef.
1602 UndefElts &= UndefElts2;
1603 break;
1604 }
1605 break;
1606 }
1607 }
1608 return MadeChange ? I : 0;
1609}
1610
Dan Gohman45b4e482008-05-19 22:14:15 +00001611
Chris Lattner564a7272003-08-13 19:01:45 +00001612/// AssociativeOpt - Perform an optimization on an associative operator. This
1613/// function is designed to check a chain of associative operators for a
1614/// potential to apply a certain optimization. Since the optimization may be
1615/// applicable if the expression was reassociated, this checks the chain, then
1616/// reassociates the expression as necessary to expose the optimization
1617/// opportunity. This makes use of a special Functor, which must define
1618/// 'shouldApply' and 'apply' methods.
1619///
1620template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001621static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001622 unsigned Opcode = Root.getOpcode();
1623 Value *LHS = Root.getOperand(0);
1624
1625 // Quick check, see if the immediate LHS matches...
1626 if (F.shouldApply(LHS))
1627 return F.apply(Root);
1628
1629 // Otherwise, if the LHS is not of the same opcode as the root, return.
1630 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001631 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001632 // Should we apply this transform to the RHS?
1633 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1634
1635 // If not to the RHS, check to see if we should apply to the LHS...
1636 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1637 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1638 ShouldApply = true;
1639 }
1640
1641 // If the functor wants to apply the optimization to the RHS of LHSI,
1642 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1643 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001644 // Now all of the instructions are in the current basic block, go ahead
1645 // and perform the reassociation.
1646 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1647
1648 // First move the selected RHS to the LHS of the root...
1649 Root.setOperand(0, LHSI->getOperand(1));
1650
1651 // Make what used to be the LHS of the root be the user of the root...
1652 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001653 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001654 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1655 return 0;
1656 }
Chris Lattner65725312004-04-16 18:08:07 +00001657 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001658 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001659 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001660 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001661 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001662
1663 // Now propagate the ExtraOperand down the chain of instructions until we
1664 // get to LHSI.
1665 while (TmpLHSI != LHSI) {
1666 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001667 // Move the instruction to immediately before the chain we are
1668 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001669 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001670 ARI = NextLHSI;
1671
Chris Lattner564a7272003-08-13 19:01:45 +00001672 Value *NextOp = NextLHSI->getOperand(1);
1673 NextLHSI->setOperand(1, ExtraOperand);
1674 TmpLHSI = NextLHSI;
1675 ExtraOperand = NextOp;
1676 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001677
Chris Lattner564a7272003-08-13 19:01:45 +00001678 // Now that the instructions are reassociated, have the functor perform
1679 // the transformation...
1680 return F.apply(Root);
1681 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001682
Chris Lattner564a7272003-08-13 19:01:45 +00001683 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1684 }
1685 return 0;
1686}
1687
Dan Gohman844731a2008-05-13 00:00:25 +00001688namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001689
Nick Lewycky02d639f2008-05-23 04:34:58 +00001690// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001691struct AddRHS {
1692 Value *RHS;
1693 AddRHS(Value *rhs) : RHS(rhs) {}
1694 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1695 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001696 return BinaryOperator::CreateShl(Add.getOperand(0),
1697 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001698 }
1699};
1700
1701// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1702// iff C1&C2 == 0
1703struct AddMaskingAnd {
1704 Constant *C2;
1705 AddMaskingAnd(Constant *c) : C2(c) {}
1706 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001707 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001708 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001709 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001710 }
1711 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001712 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001713 }
1714};
1715
Dan Gohman844731a2008-05-13 00:00:25 +00001716}
1717
Chris Lattner6e7ba452005-01-01 16:22:27 +00001718static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001719 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001720 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001721 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001722 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001723
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001724 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001725 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001726 }
1727
Chris Lattner2eefe512004-04-09 19:05:30 +00001728 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001729 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1730 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001731
Chris Lattner2eefe512004-04-09 19:05:30 +00001732 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1733 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001734 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1735 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001736 }
1737
1738 Value *Op0 = SO, *Op1 = ConstOperand;
1739 if (!ConstIsRHS)
1740 std::swap(Op0, Op1);
1741 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001742 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001743 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001744 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001745 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001746 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001747 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001748 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001749 abort();
1750 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001751 return IC->InsertNewInstBefore(New, I);
1752}
1753
1754// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1755// constant as the other operand, try to fold the binary operator into the
1756// select arguments. This also works for Cast instructions, which obviously do
1757// not have a second operand.
1758static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1759 InstCombiner *IC) {
1760 // Don't modify shared select instructions
1761 if (!SI->hasOneUse()) return 0;
1762 Value *TV = SI->getOperand(1);
1763 Value *FV = SI->getOperand(2);
1764
1765 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001766 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001767 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001768
Chris Lattner6e7ba452005-01-01 16:22:27 +00001769 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1770 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1771
Gabor Greif051a9502008-04-06 20:25:17 +00001772 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1773 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001774 }
1775 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001776}
1777
Chris Lattner4e998b22004-09-29 05:07:12 +00001778
1779/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1780/// node as operand #0, see if we can fold the instruction into the PHI (which
1781/// is only possible if all operands to the PHI are constants).
1782Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1783 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001784 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001785 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001786
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001787 // Check to see if all of the operands of the PHI are constants. If there is
1788 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001789 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001790 BasicBlock *NonConstBB = 0;
1791 for (unsigned i = 0; i != NumPHIValues; ++i)
1792 if (!isa<Constant>(PN->getIncomingValue(i))) {
1793 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001794 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001795 NonConstBB = PN->getIncomingBlock(i);
1796
1797 // If the incoming non-constant value is in I's block, we have an infinite
1798 // loop.
1799 if (NonConstBB == I.getParent())
1800 return 0;
1801 }
1802
1803 // If there is exactly one non-constant value, we can insert a copy of the
1804 // operation in that block. However, if this is a critical edge, we would be
1805 // inserting the computation one some other paths (e.g. inside a loop). Only
1806 // do this if the pred block is unconditionally branching into the phi block.
1807 if (NonConstBB) {
1808 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1809 if (!BI || !BI->isUnconditional()) return 0;
1810 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001811
1812 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001813 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001814 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001815 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001816 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001817
1818 // Next, add all of the operands to the PHI.
1819 if (I.getNumOperands() == 2) {
1820 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001821 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001822 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001823 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001824 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1826 else
1827 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001828 } else {
1829 assert(PN->getIncomingBlock(i) == NonConstBB);
1830 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001831 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001832 PN->getIncomingValue(i), C, "phitmp",
1833 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001834 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001835 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001836 CI->getPredicate(),
1837 PN->getIncomingValue(i), C, "phitmp",
1838 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001839 else
1840 assert(0 && "Unknown binop!");
1841
Chris Lattnerdbab3862007-03-02 21:28:56 +00001842 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001843 }
1844 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001845 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001846 } else {
1847 CastInst *CI = cast<CastInst>(&I);
1848 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001849 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001850 Value *InV;
1851 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001852 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001853 } else {
1854 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001855 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001856 I.getType(), "phitmp",
1857 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001858 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001859 }
1860 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001861 }
1862 }
1863 return ReplaceInstUsesWith(I, NewPN);
1864}
1865
Chris Lattner2454a2e2008-01-29 06:52:45 +00001866
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001867/// WillNotOverflowSignedAdd - Return true if we can prove that:
1868/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1869/// This basically requires proving that the add in the original type would not
1870/// overflow to change the sign bit or have a carry out.
1871bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1872 // There are different heuristics we can use for this. Here are some simple
1873 // ones.
1874
1875 // Add has the property that adding any two 2's complement numbers can only
1876 // have one carry bit which can change a sign. As such, if LHS and RHS each
1877 // have at least two sign bits, we know that the addition of the two values will
1878 // sign extend fine.
1879 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1880 return true;
1881
1882
1883 // If one of the operands only has one non-zero bit, and if the other operand
1884 // has a known-zero bit in a more significant place than it (not including the
1885 // sign bit) the ripple may go up to and fill the zero, but won't change the
1886 // sign. For example, (X & ~4) + 1.
1887
1888 // TODO: Implement.
1889
1890 return false;
1891}
1892
Chris Lattner2454a2e2008-01-29 06:52:45 +00001893
Chris Lattner7e708292002-06-25 16:13:24 +00001894Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001895 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001896 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001897
Chris Lattner66331a42004-04-10 22:01:55 +00001898 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001899 // X + undef -> undef
1900 if (isa<UndefValue>(RHS))
1901 return ReplaceInstUsesWith(I, RHS);
1902
Chris Lattner66331a42004-04-10 22:01:55 +00001903 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001904 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001905 if (RHSC->isNullValue())
1906 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001907 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001908 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1909 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001910 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001911 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001912
Chris Lattner66331a42004-04-10 22:01:55 +00001913 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001914 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001915 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001916 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001917 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001918 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001919
1920 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1921 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001922 if (!isa<VectorType>(I.getType())) {
1923 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1924 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1925 KnownZero, KnownOne))
1926 return &I;
1927 }
Chris Lattner66331a42004-04-10 22:01:55 +00001928 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001929
1930 if (isa<PHINode>(LHS))
1931 if (Instruction *NV = FoldOpIntoPhi(I))
1932 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001933
Chris Lattner4f637d42006-01-06 17:59:59 +00001934 ConstantInt *XorRHS = 0;
1935 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001936 if (isa<ConstantInt>(RHSC) &&
1937 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001938 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001939 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001940
Zhou Sheng4351c642007-04-02 08:20:41 +00001941 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001942 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1943 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001944 do {
1945 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001946 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1947 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001948 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1949 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001950 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001951 if (!MaskedValueIsZero(XorLHS,
1952 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001953 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001954 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001955 }
1956 }
1957 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001958 C0080Val = APIntOps::lshr(C0080Val, Size);
1959 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1960 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001961
Reid Spencer35c38852007-03-28 01:36:16 +00001962 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001963 // with funny bit widths then this switch statement should be removed. It
1964 // is just here to get the size of the "middle" type back up to something
1965 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001966 const Type *MiddleType = 0;
1967 switch (Size) {
1968 default: break;
1969 case 32: MiddleType = Type::Int32Ty; break;
1970 case 16: MiddleType = Type::Int16Ty; break;
1971 case 8: MiddleType = Type::Int8Ty; break;
1972 }
1973 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001974 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001975 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001976 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001977 }
1978 }
Chris Lattner66331a42004-04-10 22:01:55 +00001979 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001980
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001981 if (I.getType() == Type::Int1Ty)
1982 return BinaryOperator::CreateXor(LHS, RHS);
1983
Nick Lewycky7d26bd82008-05-23 04:39:38 +00001984 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001985 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001986 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001987
1988 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1989 if (RHSI->getOpcode() == Instruction::Sub)
1990 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1991 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1992 }
1993 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1994 if (LHSI->getOpcode() == Instruction::Sub)
1995 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1996 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1997 }
Robert Bocchino71698282004-07-27 21:02:21 +00001998 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001999
Chris Lattner5c4afb92002-05-08 22:46:53 +00002000 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002001 // -A + -B --> -(A + B)
2002 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002003 if (LHS->getType()->isIntOrIntVector()) {
2004 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002005 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002006 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002007 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002008 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002009 }
2010
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002011 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002012 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002013
2014 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002015 if (!isa<Constant>(RHS))
2016 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002017 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002018
Misha Brukmanfd939082005-04-21 23:48:37 +00002019
Chris Lattner50af16a2004-11-13 19:50:12 +00002020 ConstantInt *C2;
2021 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2022 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002023 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002024
2025 // X*C1 + X*C2 --> X * (C1+C2)
2026 ConstantInt *C1;
2027 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002028 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002029 }
2030
2031 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002032 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002033 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002034
Chris Lattnere617c9e2007-01-05 02:17:46 +00002035 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002036 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2037 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002038
Chris Lattnerad3448c2003-02-18 19:57:07 +00002039
Chris Lattner564a7272003-08-13 19:01:45 +00002040 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002041 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002042 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2043 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002044
2045 // A+B --> A|B iff A and B have no bits set in common.
2046 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2047 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2048 APInt LHSKnownOne(IT->getBitWidth(), 0);
2049 APInt LHSKnownZero(IT->getBitWidth(), 0);
2050 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2051 if (LHSKnownZero != 0) {
2052 APInt RHSKnownOne(IT->getBitWidth(), 0);
2053 APInt RHSKnownZero(IT->getBitWidth(), 0);
2054 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2055
2056 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002057 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002058 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002059 }
2060 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002061
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002062 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002063 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002064 Value *W, *X, *Y, *Z;
2065 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2066 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2067 if (W != Y) {
2068 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002069 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002070 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002071 std::swap(W, X);
2072 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002073 std::swap(Y, Z);
2074 std::swap(W, X);
2075 }
2076 }
2077
2078 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002079 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002080 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002081 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002082 }
2083 }
2084 }
2085
Chris Lattner6b032052003-10-02 15:11:26 +00002086 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002087 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002088 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002089 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002090
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002091 // (X & FF00) + xx00 -> (X+xx00) & FF00
2092 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002093 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002094 if (Anded == CRHS) {
2095 // See if all bits from the first bit set in the Add RHS up are included
2096 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002097 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002098
2099 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002100 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002101
2102 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002103 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002104
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002105 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2106 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002107 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002108 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002109 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002110 }
2111 }
2112 }
2113
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002114 // Try to fold constant add into select arguments.
2115 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002116 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002117 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002118 }
2119
Reid Spencer1628cec2006-10-26 06:15:43 +00002120 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002121 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002122 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002123 CastInst *CI = dyn_cast<CastInst>(LHS);
2124 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002125 if (!CI) {
2126 CI = dyn_cast<CastInst>(RHS);
2127 Other = LHS;
2128 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002129 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002130 (CI->getType()->getPrimitiveSizeInBits() ==
2131 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002132 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002133 unsigned AS =
2134 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002135 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2136 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002137 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002138 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002139 }
2140 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002141
Chris Lattner42790482007-12-20 01:56:58 +00002142 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002143 {
2144 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2145 Value *Other = RHS;
2146 if (!SI) {
2147 SI = dyn_cast<SelectInst>(RHS);
2148 Other = LHS;
2149 }
Chris Lattner42790482007-12-20 01:56:58 +00002150 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002151 Value *TV = SI->getTrueValue();
2152 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002153 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002154
2155 // Can we fold the add into the argument of the select?
2156 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002157 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2158 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002159 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002160 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2161 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002162 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002163 }
2164 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002165
2166 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2167 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2168 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2169 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002170
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002171 // Check for (add (sext x), y), see if we can merge this into an
2172 // integer add followed by a sext.
2173 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2174 // (add (sext x), cst) --> (sext (add x, cst'))
2175 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2176 Constant *CI =
2177 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2178 if (LHSConv->hasOneUse() &&
2179 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2180 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2181 // Insert the new, smaller add.
2182 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2183 CI, "addconv");
2184 InsertNewInstBefore(NewAdd, I);
2185 return new SExtInst(NewAdd, I.getType());
2186 }
2187 }
2188
2189 // (add (sext x), (sext y)) --> (sext (add int x, y))
2190 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2191 // Only do this if x/y have the same type, if at last one of them has a
2192 // single use (so we don't increase the number of sexts), and if the
2193 // integer add will not overflow.
2194 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2195 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2196 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2197 RHSConv->getOperand(0))) {
2198 // Insert the new integer add.
2199 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2200 RHSConv->getOperand(0),
2201 "addconv");
2202 InsertNewInstBefore(NewAdd, I);
2203 return new SExtInst(NewAdd, I.getType());
2204 }
2205 }
2206 }
2207
2208 // Check for (add double (sitofp x), y), see if we can merge this into an
2209 // integer add followed by a promotion.
2210 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2211 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2212 // ... if the constant fits in the integer value. This is useful for things
2213 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2214 // requires a constant pool load, and generally allows the add to be better
2215 // instcombined.
2216 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2217 Constant *CI =
2218 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2219 if (LHSConv->hasOneUse() &&
2220 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2221 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2222 // Insert the new integer add.
2223 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2224 CI, "addconv");
2225 InsertNewInstBefore(NewAdd, I);
2226 return new SIToFPInst(NewAdd, I.getType());
2227 }
2228 }
2229
2230 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2231 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2232 // Only do this if x/y have the same type, if at last one of them has a
2233 // single use (so we don't increase the number of int->fp conversions),
2234 // and if the integer add will not overflow.
2235 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2236 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2237 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2238 RHSConv->getOperand(0))) {
2239 // Insert the new integer add.
2240 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2241 RHSConv->getOperand(0),
2242 "addconv");
2243 InsertNewInstBefore(NewAdd, I);
2244 return new SIToFPInst(NewAdd, I.getType());
2245 }
2246 }
2247 }
2248
Chris Lattner7e708292002-06-25 16:13:24 +00002249 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002250}
2251
Chris Lattner7e708292002-06-25 16:13:24 +00002252Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002254
Chris Lattnerd137ab42008-07-17 06:07:20 +00002255 if (Op0 == Op1 && // sub X, X -> 0
2256 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002257 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002258
Chris Lattner233f7dc2002-08-12 21:17:25 +00002259 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002260 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002261 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002262
Chris Lattnere87597f2004-10-16 18:11:37 +00002263 if (isa<UndefValue>(Op0))
2264 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2265 if (isa<UndefValue>(Op1))
2266 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2267
Chris Lattnerd65460f2003-11-05 01:06:05 +00002268 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2269 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002270 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002271 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002272
Chris Lattnerd65460f2003-11-05 01:06:05 +00002273 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002274 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002275 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002276 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002277
Chris Lattner76b7a062007-01-15 07:02:54 +00002278 // -(X >>u 31) -> (X >>s 31)
2279 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002280 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002281 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002282 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002283 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002284 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002285 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002286 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002287 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002288 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002289 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002290 }
2291 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002292 }
2293 else if (SI->getOpcode() == Instruction::AShr) {
2294 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2295 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002296 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002297 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002298 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002299 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002300 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002301 }
2302 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002303 }
2304 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002305 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002306
2307 // Try to fold constant sub into select arguments.
2308 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002309 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002310 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002311
2312 if (isa<PHINode>(Op0))
2313 if (Instruction *NV = FoldOpIntoPhi(I))
2314 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002315 }
2316
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002317 if (I.getType() == Type::Int1Ty)
2318 return BinaryOperator::CreateXor(Op0, Op1);
2319
Chris Lattner43d84d62005-04-07 16:15:25 +00002320 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2321 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002322 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002323 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002324 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002325 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002326 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002327 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2328 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2329 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002330 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002331 Op1I->getOperand(0));
2332 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002333 }
2334
Chris Lattnerfd059242003-10-15 16:48:29 +00002335 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002336 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2337 // is not used by anyone else...
2338 //
Chris Lattner0517e722004-02-02 20:09:56 +00002339 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002340 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002341 // Swap the two operands of the subexpr...
2342 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2343 Op1I->setOperand(0, IIOp1);
2344 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002345
Chris Lattnera2881962003-02-18 19:28:33 +00002346 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002347 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002348 }
2349
2350 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2351 //
2352 if (Op1I->getOpcode() == Instruction::And &&
2353 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2354 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2355
Chris Lattnerf523d062004-06-09 05:08:07 +00002356 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002357 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2358 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002359 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002360
Reid Spencerac5209e2006-10-16 23:08:08 +00002361 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002362 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002363 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002364 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002365 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002366 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002367 ConstantExpr::getNeg(DivRHS));
2368
Chris Lattnerad3448c2003-02-18 19:57:07 +00002369 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002370 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002371 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002372 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002373 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002374 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002375
2376 // X - ((X / Y) * Y) --> X % Y
2377 if (Op1I->getOpcode() == Instruction::Mul)
2378 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2379 if (Op0 == I->getOperand(0) &&
2380 Op1I->getOperand(1) == I->getOperand(1)) {
2381 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002382 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002383 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002384 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002385 }
Chris Lattner40371712002-05-09 01:29:19 +00002386 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002387 }
Chris Lattnera2881962003-02-18 19:28:33 +00002388
Chris Lattner9919e3d2006-12-02 00:13:08 +00002389 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002390 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002391 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002392 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2393 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2394 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2395 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002396 } else if (Op0I->getOpcode() == Instruction::Sub) {
2397 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002398 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002399 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002400 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002401
Chris Lattner50af16a2004-11-13 19:50:12 +00002402 ConstantInt *C1;
2403 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002404 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002405 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002406
Chris Lattner50af16a2004-11-13 19:50:12 +00002407 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2408 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002409 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002410 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002411 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002412}
2413
Chris Lattnera0141b92007-07-15 20:42:37 +00002414/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2415/// comparison only checks the sign bit. If it only checks the sign bit, set
2416/// TrueIfSigned if the result of the comparison is true when the input value is
2417/// signed.
2418static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2419 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002420 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002421 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2422 TrueIfSigned = true;
2423 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002424 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2425 TrueIfSigned = true;
2426 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002427 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2428 TrueIfSigned = false;
2429 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002430 case ICmpInst::ICMP_UGT:
2431 // True if LHS u> RHS and RHS == high-bit-mask - 1
2432 TrueIfSigned = true;
2433 return RHS->getValue() ==
2434 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2435 case ICmpInst::ICMP_UGE:
2436 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2437 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002438 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002439 default:
2440 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002441 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002442}
2443
Chris Lattner7e708292002-06-25 16:13:24 +00002444Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002445 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002446 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002447
Chris Lattnere87597f2004-10-16 18:11:37 +00002448 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2449 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2450
Chris Lattner233f7dc2002-08-12 21:17:25 +00002451 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002452 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2453 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002454
2455 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002456 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002457 if (SI->getOpcode() == Instruction::Shl)
2458 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002459 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002460 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002461
Zhou Sheng843f07672007-04-19 05:39:12 +00002462 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002463 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2464 if (CI->equalsInt(1)) // X * 1 == X
2465 return ReplaceInstUsesWith(I, Op0);
2466 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002468
Zhou Sheng97b52c22007-03-29 01:57:21 +00002469 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002470 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002472 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002473 }
Robert Bocchino71698282004-07-27 21:02:21 +00002474 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002475 if (Op1F->isNullValue())
2476 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002477
Chris Lattnera2881962003-02-18 19:28:33 +00002478 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2479 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002480 if (Op1F->isExactlyValue(1.0))
2481 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2482 } else if (isa<VectorType>(Op1->getType())) {
2483 if (isa<ConstantAggregateZero>(Op1))
2484 return ReplaceInstUsesWith(I, Op1);
2485
2486 // As above, vector X*splat(1.0) -> X in all defined cases.
2487 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2488 if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2489 if (F->isExactlyValue(1.0))
2490 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00002491 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002492
2493 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2494 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002495 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002496 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002497 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002498 Op1, "tmp");
2499 InsertNewInstBefore(Add, I);
2500 Value *C1C2 = ConstantExpr::getMul(Op1,
2501 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002502 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002503
2504 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002505
2506 // Try to fold constant mul into select arguments.
2507 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002508 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002509 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002510
2511 if (isa<PHINode>(Op0))
2512 if (Instruction *NV = FoldOpIntoPhi(I))
2513 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002514 }
2515
Chris Lattnera4f445b2003-03-10 23:23:04 +00002516 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2517 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002518 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002519
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002520 if (I.getType() == Type::Int1Ty)
2521 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2522
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002523 // If one of the operands of the multiply is a cast from a boolean value, then
2524 // we know the bool is either zero or one, so this is a 'masking' multiply.
2525 // See if we can simplify things based on how the boolean was originally
2526 // formed.
2527 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002528 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002529 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002530 BoolCast = CI;
2531 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002532 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002533 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002534 BoolCast = CI;
2535 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002536 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002537 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2538 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002539 bool TIS = false;
2540
Reid Spencere4d87aa2006-12-23 06:05:41 +00002541 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002542 // multiply into a shift/and combination.
2543 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002544 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2545 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002546 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002547 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002548 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002549 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002550 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002551 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002552 BoolCast->getOperand(0)->getName()+
2553 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002554
2555 // If the multiply type is not the same as the source type, sign extend
2556 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002557 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002558 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2559 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002560 Instruction::CastOps opcode =
2561 (SrcBits == DstBits ? Instruction::BitCast :
2562 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2563 V = InsertCastBefore(opcode, V, I.getType(), I);
2564 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002565
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002566 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002567 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002568 }
2569 }
2570 }
2571
Chris Lattner7e708292002-06-25 16:13:24 +00002572 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002573}
2574
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002575/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2576/// instruction.
2577bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2578 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2579
2580 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2581 int NonNullOperand = -1;
2582 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2583 if (ST->isNullValue())
2584 NonNullOperand = 2;
2585 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2586 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2587 if (ST->isNullValue())
2588 NonNullOperand = 1;
2589
2590 if (NonNullOperand == -1)
2591 return false;
2592
2593 Value *SelectCond = SI->getOperand(0);
2594
2595 // Change the div/rem to use 'Y' instead of the select.
2596 I.setOperand(1, SI->getOperand(NonNullOperand));
2597
2598 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2599 // problem. However, the select, or the condition of the select may have
2600 // multiple uses. Based on our knowledge that the operand must be non-zero,
2601 // propagate the known value for the select into other uses of it, and
2602 // propagate a known value of the condition into its other users.
2603
2604 // If the select and condition only have a single use, don't bother with this,
2605 // early exit.
2606 if (SI->use_empty() && SelectCond->hasOneUse())
2607 return true;
2608
2609 // Scan the current block backward, looking for other uses of SI.
2610 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2611
2612 while (BBI != BBFront) {
2613 --BBI;
2614 // If we found a call to a function, we can't assume it will return, so
2615 // information from below it cannot be propagated above it.
2616 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2617 break;
2618
2619 // Replace uses of the select or its condition with the known values.
2620 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2621 I != E; ++I) {
2622 if (*I == SI) {
2623 *I = SI->getOperand(NonNullOperand);
2624 AddToWorkList(BBI);
2625 } else if (*I == SelectCond) {
2626 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2627 ConstantInt::getFalse();
2628 AddToWorkList(BBI);
2629 }
2630 }
2631
2632 // If we past the instruction, quit looking for it.
2633 if (&*BBI == SI)
2634 SI = 0;
2635 if (&*BBI == SelectCond)
2636 SelectCond = 0;
2637
2638 // If we ran out of things to eliminate, break out of the loop.
2639 if (SelectCond == 0 && SI == 0)
2640 break;
2641
2642 }
2643 return true;
2644}
2645
2646
Reid Spencer1628cec2006-10-26 06:15:43 +00002647/// This function implements the transforms on div instructions that work
2648/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2649/// used by the visitors to those instructions.
2650/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002651Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002653
Chris Lattner50b2ca42008-02-19 06:12:18 +00002654 // undef / X -> 0 for integer.
2655 // undef / X -> undef for FP (the undef could be a snan).
2656 if (isa<UndefValue>(Op0)) {
2657 if (Op0->getType()->isFPOrFPVector())
2658 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002659 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002660 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002661
2662 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002663 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002664 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002665
Reid Spencer1628cec2006-10-26 06:15:43 +00002666 return 0;
2667}
Misha Brukmanfd939082005-04-21 23:48:37 +00002668
Reid Spencer1628cec2006-10-26 06:15:43 +00002669/// This function implements the transforms common to both integer division
2670/// instructions (udiv and sdiv). It is called by the visitors to those integer
2671/// division instructions.
2672/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002673Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002674 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2675
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002676 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002677 if (Op0 == Op1) {
2678 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2679 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2680 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2681 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2682 }
2683
2684 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2685 return ReplaceInstUsesWith(I, CI);
2686 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002687
Reid Spencer1628cec2006-10-26 06:15:43 +00002688 if (Instruction *Common = commonDivTransforms(I))
2689 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002690
2691 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2692 // This does not apply for fdiv.
2693 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2694 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002695
2696 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2697 // div X, 1 == X
2698 if (RHS->equalsInt(1))
2699 return ReplaceInstUsesWith(I, Op0);
2700
2701 // (X / C1) / C2 -> X / (C1*C2)
2702 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2703 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2704 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002705 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2707 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002708 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002709 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002710 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002711
Reid Spencerbca0e382007-03-23 20:05:17 +00002712 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002713 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2714 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2715 return R;
2716 if (isa<PHINode>(Op0))
2717 if (Instruction *NV = FoldOpIntoPhi(I))
2718 return NV;
2719 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002720 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002721
Chris Lattnera2881962003-02-18 19:28:33 +00002722 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002723 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002724 if (LHS->equalsInt(0))
2725 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2726
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002727 // It can't be division by zero, hence it must be division by one.
2728 if (I.getType() == Type::Int1Ty)
2729 return ReplaceInstUsesWith(I, Op0);
2730
Reid Spencer1628cec2006-10-26 06:15:43 +00002731 return 0;
2732}
2733
2734Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2736
2737 // Handle the integer div common cases
2738 if (Instruction *Common = commonIDivTransforms(I))
2739 return Common;
2740
2741 // X udiv C^2 -> X >> C
2742 // Check to see if this is an unsigned division with an exact power of 2,
2743 // if so, convert to a right shift.
2744 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002745 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002746 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002747 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002748 }
2749
2750 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002751 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002752 if (RHSI->getOpcode() == Instruction::Shl &&
2753 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002754 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002755 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002756 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002757 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002758 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002759 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002761 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002762 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002763 }
2764 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002765 }
2766
Reid Spencer1628cec2006-10-26 06:15:43 +00002767 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2768 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002769 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002770 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002771 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002772 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002773 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002774 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002775 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002776 // Construct the "on true" case of the select
2777 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002778 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002779 Op0, TC, SI->getName()+".t");
2780 TSI = InsertNewInstBefore(TSI, I);
2781
2782 // Construct the "on false" case of the select
2783 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002784 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002785 Op0, FC, SI->getName()+".f");
2786 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002787
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002788 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002789 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002790 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002791 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002792 return 0;
2793}
2794
Reid Spencer1628cec2006-10-26 06:15:43 +00002795Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2796 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2797
2798 // Handle the integer div common cases
2799 if (Instruction *Common = commonIDivTransforms(I))
2800 return Common;
2801
2802 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2803 // sdiv X, -1 == -X
2804 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002805 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002806
2807 // -X/C -> X/-C
2808 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002809 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002810 }
2811
2812 // If the sign bits of both operands are zero (i.e. we can prove they are
2813 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002814 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002815 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002816 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002817 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002818 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002819 }
2820 }
2821
2822 return 0;
2823}
2824
2825Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2826 return commonDivTransforms(I);
2827}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002828
Reid Spencer0a783f72006-11-02 01:53:59 +00002829/// This function implements the transforms on rem instructions that work
2830/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2831/// is used by the visitors to those instructions.
2832/// @brief Transforms common to all three rem instructions
2833Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002834 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002835
Chris Lattner50b2ca42008-02-19 06:12:18 +00002836 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002837 if (Constant *LHS = dyn_cast<Constant>(Op0))
2838 if (LHS->isNullValue())
2839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2840
Chris Lattner50b2ca42008-02-19 06:12:18 +00002841 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2842 if (I.getType()->isFPOrFPVector())
2843 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002844 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002845 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002846 if (isa<UndefValue>(Op1))
2847 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002848
2849 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002850 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2851 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00002852
Reid Spencer0a783f72006-11-02 01:53:59 +00002853 return 0;
2854}
2855
2856/// This function implements the transforms common to both integer remainder
2857/// instructions (urem and srem). It is called by the visitors to those integer
2858/// remainder instructions.
2859/// @brief Common integer remainder transforms
2860Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2861 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2862
2863 if (Instruction *common = commonRemTransforms(I))
2864 return common;
2865
Chris Lattner857e8cd2004-12-12 21:48:58 +00002866 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002867 // X % 0 == undef, we don't need to preserve faults!
2868 if (RHS->equalsInt(0))
2869 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2870
Chris Lattnera2881962003-02-18 19:28:33 +00002871 if (RHS->equalsInt(1)) // X % 1 == 0
2872 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2873
Chris Lattner97943922006-02-28 05:49:21 +00002874 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2875 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2876 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2877 return R;
2878 } else if (isa<PHINode>(Op0I)) {
2879 if (Instruction *NV = FoldOpIntoPhi(I))
2880 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002881 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002882
2883 // See if we can fold away this rem instruction.
2884 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2885 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2886 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2887 KnownZero, KnownOne))
2888 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002889 }
Chris Lattnera2881962003-02-18 19:28:33 +00002890 }
2891
Reid Spencer0a783f72006-11-02 01:53:59 +00002892 return 0;
2893}
2894
2895Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
2898 if (Instruction *common = commonIRemTransforms(I))
2899 return common;
2900
2901 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2902 // X urem C^2 -> X and C
2903 // Check to see if this is an unsigned remainder with an exact power of 2,
2904 // if so, convert to a bitwise and.
2905 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002906 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002907 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002908 }
2909
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002910 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002911 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2912 if (RHSI->getOpcode() == Instruction::Shl &&
2913 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002914 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002915 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002916 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002917 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002918 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002919 }
2920 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002921 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002922
Reid Spencer0a783f72006-11-02 01:53:59 +00002923 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2924 // where C1&C2 are powers of two.
2925 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2926 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2927 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2928 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002929 if ((STO->getValue().isPowerOf2()) &&
2930 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002931 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002932 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002933 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002934 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002935 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002936 }
2937 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002938 }
2939
Chris Lattner3f5b8772002-05-06 16:14:14 +00002940 return 0;
2941}
2942
Reid Spencer0a783f72006-11-02 01:53:59 +00002943Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2944 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2945
Dan Gohmancff55092007-11-05 23:16:33 +00002946 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002947 if (Instruction *common = commonIRemTransforms(I))
2948 return common;
2949
2950 if (Value *RHSNeg = dyn_castNegVal(Op1))
2951 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002952 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002953 // X % -Y -> X % Y
2954 AddUsesToWorkList(I);
2955 I.setOperand(1, RHSNeg);
2956 return &I;
2957 }
2958
Dan Gohmancff55092007-11-05 23:16:33 +00002959 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002960 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002961 if (I.getType()->isInteger()) {
2962 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2963 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2964 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002965 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002966 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002967 }
2968
2969 return 0;
2970}
2971
2972Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002973 return commonRemTransforms(I);
2974}
2975
Chris Lattner457dd822004-06-09 07:59:58 +00002976// isOneBitSet - Return true if there is exactly one bit set in the specified
2977// constant.
2978static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002979 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002980}
2981
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002982// isHighOnes - Return true if the constant is of the form 1+0+.
2983// This is the same as lowones(~X).
2984static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002985 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002986}
2987
Reid Spencere4d87aa2006-12-23 06:05:41 +00002988/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002989/// are carefully arranged to allow folding of expressions such as:
2990///
2991/// (A < B) | (A > B) --> (A != B)
2992///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002993/// Note that this is only valid if the first and second predicates have the
2994/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002995///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002996/// Three bits are used to represent the condition, as follows:
2997/// 0 A > B
2998/// 1 A == B
2999/// 2 A < B
3000///
3001/// <=> Value Definition
3002/// 000 0 Always false
3003/// 001 1 A > B
3004/// 010 2 A == B
3005/// 011 3 A >= B
3006/// 100 4 A < B
3007/// 101 5 A != B
3008/// 110 6 A <= B
3009/// 111 7 Always true
3010///
3011static unsigned getICmpCode(const ICmpInst *ICI) {
3012 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003013 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003014 case ICmpInst::ICMP_UGT: return 1; // 001
3015 case ICmpInst::ICMP_SGT: return 1; // 001
3016 case ICmpInst::ICMP_EQ: return 2; // 010
3017 case ICmpInst::ICMP_UGE: return 3; // 011
3018 case ICmpInst::ICMP_SGE: return 3; // 011
3019 case ICmpInst::ICMP_ULT: return 4; // 100
3020 case ICmpInst::ICMP_SLT: return 4; // 100
3021 case ICmpInst::ICMP_NE: return 5; // 101
3022 case ICmpInst::ICMP_ULE: return 6; // 110
3023 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003024 // True -> 7
3025 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003026 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003027 return 0;
3028 }
3029}
3030
Reid Spencere4d87aa2006-12-23 06:05:41 +00003031/// getICmpValue - This is the complement of getICmpCode, which turns an
3032/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003033/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003034/// of predicate to use in new icmp instructions.
3035static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3036 switch (code) {
3037 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003038 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003039 case 1:
3040 if (sign)
3041 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3042 else
3043 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3044 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3045 case 3:
3046 if (sign)
3047 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3048 else
3049 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3050 case 4:
3051 if (sign)
3052 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3053 else
3054 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3055 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3056 case 6:
3057 if (sign)
3058 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3059 else
3060 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003061 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003062 }
3063}
3064
Reid Spencere4d87aa2006-12-23 06:05:41 +00003065static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3066 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3067 (ICmpInst::isSignedPredicate(p1) &&
3068 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3069 (ICmpInst::isSignedPredicate(p2) &&
3070 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3071}
3072
3073namespace {
3074// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3075struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003076 InstCombiner &IC;
3077 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003078 ICmpInst::Predicate pred;
3079 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3080 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3081 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003082 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003083 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3084 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003085 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3086 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003087 return false;
3088 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003089 Instruction *apply(Instruction &Log) const {
3090 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3091 if (ICI->getOperand(0) != LHS) {
3092 assert(ICI->getOperand(1) == LHS);
3093 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003094 }
3095
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003096 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003097 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003098 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003099 unsigned Code;
3100 switch (Log.getOpcode()) {
3101 case Instruction::And: Code = LHSCode & RHSCode; break;
3102 case Instruction::Or: Code = LHSCode | RHSCode; break;
3103 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003104 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003105 }
3106
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003107 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3108 ICmpInst::isSignedPredicate(ICI->getPredicate());
3109
3110 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003111 if (Instruction *I = dyn_cast<Instruction>(RV))
3112 return I;
3113 // Otherwise, it's a constant boolean value...
3114 return IC.ReplaceInstUsesWith(Log, RV);
3115 }
3116};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003117} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003118
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003119// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3120// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003121// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003122Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003123 ConstantInt *OpRHS,
3124 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003125 BinaryOperator &TheAnd) {
3126 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003127 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003128 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003129 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003130
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003131 switch (Op->getOpcode()) {
3132 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003133 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003134 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003135 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003136 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003137 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003138 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003139 }
3140 break;
3141 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003142 if (Together == AndRHS) // (X | C) & C --> C
3143 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003144
Chris Lattner6e7ba452005-01-01 16:22:27 +00003145 if (Op->hasOneUse() && Together != OpRHS) {
3146 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003147 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003148 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003149 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003150 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003151 }
3152 break;
3153 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003154 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003155 // Adding a one to a single bit bit-field should be turned into an XOR
3156 // of the bit. First thing to check is to see if this AND is with a
3157 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003158 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003159
3160 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003161 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003162 // Ok, at this point, we know that we are masking the result of the
3163 // ADD down to exactly one bit. If the constant we are adding has
3164 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003165 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003166
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003167 // Check to see if any bits below the one bit set in AndRHSV are set.
3168 if ((AddRHS & (AndRHSV-1)) == 0) {
3169 // If not, the only thing that can effect the output of the AND is
3170 // the bit specified by AndRHSV. If that bit is set, the effect of
3171 // the XOR is to toggle the bit. If it is clear, then the ADD has
3172 // no effect.
3173 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3174 TheAnd.setOperand(0, X);
3175 return &TheAnd;
3176 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003177 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003178 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003179 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003180 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003181 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003182 }
3183 }
3184 }
3185 }
3186 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003187
3188 case Instruction::Shl: {
3189 // We know that the AND will not produce any of the bits shifted in, so if
3190 // the anded constant includes them, clear them now!
3191 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003192 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003193 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003194 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3195 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003196
Zhou Sheng290bec52007-03-29 08:15:12 +00003197 if (CI->getValue() == ShlMask) {
3198 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003199 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3200 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003201 TheAnd.setOperand(1, CI);
3202 return &TheAnd;
3203 }
3204 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003205 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003206 case Instruction::LShr:
3207 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003208 // We know that the AND will not produce any of the bits shifted in, so if
3209 // the anded constant includes them, clear them now! This only applies to
3210 // unsigned shifts, because a signed shr may bring in set bits!
3211 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003212 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003213 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003214 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3215 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003216
Zhou Sheng290bec52007-03-29 08:15:12 +00003217 if (CI->getValue() == ShrMask) {
3218 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003219 return ReplaceInstUsesWith(TheAnd, Op);
3220 } else if (CI != AndRHS) {
3221 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3222 return &TheAnd;
3223 }
3224 break;
3225 }
3226 case Instruction::AShr:
3227 // Signed shr.
3228 // See if this is shifting in some sign extension, then masking it out
3229 // with an and.
3230 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003231 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003232 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003233 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3234 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003235 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003236 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003237 // Make the argument unsigned.
3238 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003239 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003240 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003241 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003242 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003243 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003244 }
3245 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003246 }
3247 return 0;
3248}
3249
Chris Lattner8b170942002-08-09 23:47:40 +00003250
Chris Lattnera96879a2004-09-29 17:40:11 +00003251/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3252/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003253/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3254/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003255/// insert new instructions.
3256Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003257 bool isSigned, bool Inside,
3258 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003259 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003260 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003261 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003262
Chris Lattnera96879a2004-09-29 17:40:11 +00003263 if (Inside) {
3264 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003265 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003266
Reid Spencere4d87aa2006-12-23 06:05:41 +00003267 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003268 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003269 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003270 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3271 return new ICmpInst(pred, V, Hi);
3272 }
3273
3274 // Emit V-Lo <u Hi-Lo
3275 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003276 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003277 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003278 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3279 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003280 }
3281
3282 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003283 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003284
Reid Spencere4e40032007-03-21 23:19:50 +00003285 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003286 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003287 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003288 ICmpInst::Predicate pred = (isSigned ?
3289 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3290 return new ICmpInst(pred, V, Hi);
3291 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003292
Reid Spencere4e40032007-03-21 23:19:50 +00003293 // Emit V-Lo >u Hi-1-Lo
3294 // Note that Hi has already had one subtracted from it, above.
3295 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003296 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003297 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003298 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3299 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003300}
3301
Chris Lattner7203e152005-09-18 07:22:02 +00003302// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3303// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3304// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3305// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003306static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003307 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003308 uint32_t BitWidth = Val->getType()->getBitWidth();
3309 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003310
3311 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003312 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003313 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003314 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003315 return true;
3316}
3317
Chris Lattner7203e152005-09-18 07:22:02 +00003318/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3319/// where isSub determines whether the operator is a sub. If we can fold one of
3320/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003321///
3322/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3323/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3324/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3325///
3326/// return (A +/- B).
3327///
3328Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003329 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003330 Instruction &I) {
3331 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3332 if (!LHSI || LHSI->getNumOperands() != 2 ||
3333 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3334
3335 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3336
3337 switch (LHSI->getOpcode()) {
3338 default: return 0;
3339 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003340 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003341 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003342 if ((Mask->getValue().countLeadingZeros() +
3343 Mask->getValue().countPopulation()) ==
3344 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003345 break;
3346
3347 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3348 // part, we don't need any explicit masks to take them out of A. If that
3349 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003350 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003351 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003352 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003353 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003354 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003355 break;
3356 }
3357 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003358 return 0;
3359 case Instruction::Or:
3360 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003361 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003362 if ((Mask->getValue().countLeadingZeros() +
3363 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003364 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003365 break;
3366 return 0;
3367 }
3368
3369 Instruction *New;
3370 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003371 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003372 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003373 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003374 return InsertNewInstBefore(New, I);
3375}
3376
Chris Lattner7e708292002-06-25 16:13:24 +00003377Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003378 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003380
Chris Lattnere87597f2004-10-16 18:11:37 +00003381 if (isa<UndefValue>(Op1)) // X & undef -> 0
3382 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3383
Chris Lattner6e7ba452005-01-01 16:22:27 +00003384 // and X, X = X
3385 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003386 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003387
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003388 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003389 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003390 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003391 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3392 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3393 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003394 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003395 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003396 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003397 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003398 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003399 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003400 } else if (isa<ConstantAggregateZero>(Op1)) {
3401 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003402 }
3403 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003404
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003405 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003406 const APInt& AndRHSMask = AndRHS->getValue();
3407 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003408
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003409 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003410 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003411 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003412 Value *Op0LHS = Op0I->getOperand(0);
3413 Value *Op0RHS = Op0I->getOperand(1);
3414 switch (Op0I->getOpcode()) {
3415 case Instruction::Xor:
3416 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003417 // If the mask is only needed on one incoming arm, push it up.
3418 if (Op0I->hasOneUse()) {
3419 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3420 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003421 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003422 Op0RHS->getName()+".masked");
3423 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003424 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003425 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003426 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003427 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003428 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3429 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003430 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003431 Op0LHS->getName()+".masked");
3432 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003433 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003434 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3435 }
3436 }
3437
Chris Lattner6e7ba452005-01-01 16:22:27 +00003438 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003439 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003440 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3441 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3442 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3443 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003444 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003445 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003446 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003447 break;
3448
3449 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003450 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3451 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3452 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3453 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003454 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003455
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003456 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3457 // has 1's for all bits that the subtraction with A might affect.
3458 if (Op0I->hasOneUse()) {
3459 uint32_t BitWidth = AndRHSMask.getBitWidth();
3460 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3461 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3462
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003463 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003464 if (!(A && A->isZero()) && // avoid infinite recursion.
3465 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003466 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3467 InsertNewInstBefore(NewNeg, I);
3468 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3469 }
3470 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003471 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003472
3473 case Instruction::Shl:
3474 case Instruction::LShr:
3475 // (1 << x) & 1 --> zext(x == 0)
3476 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003477 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003478 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3479 Constant::getNullValue(I.getType()));
3480 InsertNewInstBefore(NewICmp, I);
3481 return new ZExtInst(NewICmp, I.getType());
3482 }
3483 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003484 }
3485
Chris Lattner58403262003-07-23 19:25:52 +00003486 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003487 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003488 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003489 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003490 // If this is an integer truncation or change from signed-to-unsigned, and
3491 // if the source is an and/or with immediate, transform it. This
3492 // frequently occurs for bitfield accesses.
3493 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003494 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003495 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003496 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003497 if (CastOp->getOpcode() == Instruction::And) {
3498 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003499 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3500 // This will fold the two constants together, which may allow
3501 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003502 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003503 CastOp->getOperand(0), I.getType(),
3504 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003505 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003506 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003507 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003508 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003509 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003510 } else if (CastOp->getOpcode() == Instruction::Or) {
3511 // Change: and (cast (or X, C1) to T), C2
3512 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003513 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003514 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3515 return ReplaceInstUsesWith(I, AndRHS);
3516 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003517 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003518 }
Chris Lattner06782f82003-07-23 19:36:21 +00003519 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003520
3521 // Try to fold constant and into select arguments.
3522 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003524 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003525 if (isa<PHINode>(Op0))
3526 if (Instruction *NV = FoldOpIntoPhi(I))
3527 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003528 }
3529
Chris Lattner8d969642003-03-10 23:06:50 +00003530 Value *Op0NotVal = dyn_castNotVal(Op0);
3531 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003532
Chris Lattner5b62aa72004-06-18 06:07:51 +00003533 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3534 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3535
Misha Brukmancb6267b2004-07-30 12:50:08 +00003536 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003537 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003538 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003539 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003540 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003541 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003542 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003543
3544 {
Chris Lattner003b6202007-06-15 05:58:24 +00003545 Value *A = 0, *B = 0, *C = 0, *D = 0;
3546 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003547 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3548 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003549
3550 // (A|B) & ~(A&B) -> A^B
3551 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3552 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003553 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003554 }
3555 }
3556
3557 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003558 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3559 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003560
3561 // ~(A&B) & (A|B) -> A^B
3562 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3563 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003564 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003565 }
3566 }
Chris Lattner64daab52006-04-01 08:03:55 +00003567
3568 if (Op0->hasOneUse() &&
3569 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3570 if (A == Op1) { // (A^B)&A -> A&(A^B)
3571 I.swapOperands(); // Simplify below
3572 std::swap(Op0, Op1);
3573 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3574 cast<BinaryOperator>(Op0)->swapOperands();
3575 I.swapOperands(); // Simplify below
3576 std::swap(Op0, Op1);
3577 }
3578 }
3579 if (Op1->hasOneUse() &&
3580 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3581 if (B == Op0) { // B&(A^B) -> B&(B^A)
3582 cast<BinaryOperator>(Op1)->swapOperands();
3583 std::swap(A, B);
3584 }
3585 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003586 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003587 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003588 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003589 }
3590 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003591 }
3592
Nick Lewyckyb30591e2008-08-06 04:54:03 +00003593 { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3594 // where C is a power of 2
3595 Value *A, *B;
3596 ConstantInt *C1, *C2;
Evan Chengab5d5e32008-08-20 23:36:48 +00003597 ICmpInst::Predicate LHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3598 ICmpInst::Predicate RHSCC = ICmpInst::BAD_ICMP_PREDICATE;
Nick Lewyckyb30591e2008-08-06 04:54:03 +00003599 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3600 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3601 if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3602 C1->getValue().isPowerOf2()) {
3603 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3604 InsertNewInstBefore(NewOr, I);
3605 return new ICmpInst(LHSCC, NewOr, C1);
3606 }
3607 }
3608
Reid Spencere4d87aa2006-12-23 06:05:41 +00003609 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3610 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3611 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003612 return R;
3613
Chris Lattner955f3312004-09-28 21:48:02 +00003614 Value *LHSVal, *RHSVal;
3615 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003616 ICmpInst::Predicate LHSCC, RHSCC;
3617 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3618 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3619 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3620 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3621 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3622 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3623 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003624 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3625
3626 // Don't try to fold ICMP_SLT + ICMP_ULT.
3627 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3628 ICmpInst::isSignedPredicate(LHSCC) ==
3629 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003630 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003631 ICmpInst::Predicate GT;
3632 if (ICmpInst::isSignedPredicate(LHSCC) ||
3633 (ICmpInst::isEquality(LHSCC) &&
3634 ICmpInst::isSignedPredicate(RHSCC)))
3635 GT = ICmpInst::ICMP_SGT;
3636 else
3637 GT = ICmpInst::ICMP_UGT;
3638
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3640 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003641 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003642 std::swap(LHS, RHS);
3643 std::swap(LHSCst, RHSCst);
3644 std::swap(LHSCC, RHSCC);
3645 }
3646
Reid Spencere4d87aa2006-12-23 06:05:41 +00003647 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003648 // comparing a value against two constants and and'ing the result
3649 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3651 // (from the FoldICmpLogical check above), that the two constants
3652 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003653 assert(LHSCst != RHSCst && "Compares not folded above?");
3654
3655 switch (LHSCC) {
3656 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003658 switch (RHSCC) {
3659 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3661 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3662 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003663 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3665 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3666 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003667 return ReplaceInstUsesWith(I, LHS);
3668 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003670 switch (RHSCC) {
3671 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 case ICmpInst::ICMP_ULT:
3673 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3674 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3675 break; // (X != 13 & X u< 15) -> no change
3676 case ICmpInst::ICMP_SLT:
3677 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3678 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3679 break; // (X != 13 & X s< 15) -> no change
3680 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3681 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3682 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003683 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 case ICmpInst::ICMP_NE:
3685 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003686 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003687 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003688 LHSVal->getName()+".off");
3689 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003690 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3691 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003692 }
3693 break; // (X != 13 & X != 15) -> no change
3694 }
3695 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003696 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003697 switch (RHSCC) {
3698 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003699 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3700 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3703 break;
3704 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3705 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003706 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3708 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003709 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003710 break;
3711 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003712 switch (RHSCC) {
3713 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003714 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3715 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003716 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3718 break;
3719 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3720 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003721 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003722 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3723 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003724 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725 break;
3726 case ICmpInst::ICMP_UGT:
3727 switch (RHSCC) {
3728 default: assert(0 && "Unknown integer condition code!");
Eli Friedman5c1f1722008-06-21 23:36:13 +00003729 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3731 return ReplaceInstUsesWith(I, RHS);
3732 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3733 break;
3734 case ICmpInst::ICMP_NE:
3735 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3736 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3737 break; // (X u> 13 & X != 15) -> no change
3738 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3739 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3740 true, I);
3741 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3742 break;
3743 }
3744 break;
3745 case ICmpInst::ICMP_SGT:
3746 switch (RHSCC) {
3747 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003748 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003749 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3750 return ReplaceInstUsesWith(I, RHS);
3751 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3752 break;
3753 case ICmpInst::ICMP_NE:
3754 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3755 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3756 break; // (X s> 13 & X != 15) -> no change
3757 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3758 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3759 true, I);
3760 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3761 break;
3762 }
3763 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003764 }
3765 }
3766 }
3767
Chris Lattner6fc205f2006-05-05 06:39:07 +00003768 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003769 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3770 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3771 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3772 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003773 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003774 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003775 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3776 I.getType(), TD) &&
3777 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3778 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003779 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003780 Op1C->getOperand(0),
3781 I.getName());
3782 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003783 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003784 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003785 }
Chris Lattnere511b742006-11-14 07:46:50 +00003786
3787 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003788 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3789 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3790 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003791 SI0->getOperand(1) == SI1->getOperand(1) &&
3792 (SI0->hasOneUse() || SI1->hasOneUse())) {
3793 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003794 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003795 SI1->getOperand(0),
3796 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003797 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003798 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003799 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003800 }
3801
Chris Lattner99c65742007-10-24 05:38:08 +00003802 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3803 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3804 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3805 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3806 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3807 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3808 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3809 // If either of the constants are nans, then the whole thing returns
3810 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003811 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003812 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3813 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3814 RHS->getOperand(0));
3815 }
3816 }
3817 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003818
Chris Lattner7e708292002-06-25 16:13:24 +00003819 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003820}
3821
Chris Lattnerafe91a52006-06-15 19:07:26 +00003822/// CollectBSwapParts - Look to see if the specified value defines a single byte
3823/// in the result. If it does, and if the specified byte hasn't been filled in
3824/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003825static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003826 Instruction *I = dyn_cast<Instruction>(V);
3827 if (I == 0) return true;
3828
3829 // If this is an or instruction, it is an inner node of the bswap.
3830 if (I->getOpcode() == Instruction::Or)
3831 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3832 CollectBSwapParts(I->getOperand(1), ByteValues);
3833
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003834 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003835 // If this is a shift by a constant int, and it is "24", then its operand
3836 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003837 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003838 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003839 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003840 8*(ByteValues.size()-1))
3841 return true;
3842
3843 unsigned DestNo;
3844 if (I->getOpcode() == Instruction::Shl) {
3845 // X << 24 defines the top byte with the lowest of the input bytes.
3846 DestNo = ByteValues.size()-1;
3847 } else {
3848 // X >>u 24 defines the low byte with the highest of the input bytes.
3849 DestNo = 0;
3850 }
3851
3852 // If the destination byte value is already defined, the values are or'd
3853 // together, which isn't a bswap (unless it's an or of the same bits).
3854 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3855 return true;
3856 ByteValues[DestNo] = I->getOperand(0);
3857 return false;
3858 }
3859
3860 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3861 // don't have this.
3862 Value *Shift = 0, *ShiftLHS = 0;
3863 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3864 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3865 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3866 return true;
3867 Instruction *SI = cast<Instruction>(Shift);
3868
3869 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003870 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3871 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003872 return true;
3873
3874 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3875 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003876 if (AndAmt->getValue().getActiveBits() > 64)
3877 return true;
3878 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003879 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003880 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003881 break;
3882 // Unknown mask for bswap.
3883 if (DestByte == ByteValues.size()) return true;
3884
Reid Spencerb83eb642006-10-20 07:07:24 +00003885 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003886 unsigned SrcByte;
3887 if (SI->getOpcode() == Instruction::Shl)
3888 SrcByte = DestByte - ShiftBytes;
3889 else
3890 SrcByte = DestByte + ShiftBytes;
3891
3892 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3893 if (SrcByte != ByteValues.size()-DestByte-1)
3894 return true;
3895
3896 // If the destination byte value is already defined, the values are or'd
3897 // together, which isn't a bswap (unless it's an or of the same bits).
3898 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3899 return true;
3900 ByteValues[DestByte] = SI->getOperand(0);
3901 return false;
3902}
3903
3904/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3905/// If so, insert the new bswap intrinsic and return it.
3906Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003907 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3908 if (!ITy || ITy->getBitWidth() % 16)
3909 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003910
3911 /// ByteValues - For each byte of the result, we keep track of which value
3912 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003913 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003914 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003915
3916 // Try to find all the pieces corresponding to the bswap.
3917 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3918 CollectBSwapParts(I.getOperand(1), ByteValues))
3919 return 0;
3920
3921 // Check to see if all of the bytes come from the same value.
3922 Value *V = ByteValues[0];
3923 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3924
3925 // Check to make sure that all of the bytes come from the same value.
3926 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3927 if (ByteValues[i] != V)
3928 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003929 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003930 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003931 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003932 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003933}
3934
3935
Chris Lattner7e708292002-06-25 16:13:24 +00003936Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003937 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003939
Chris Lattner42593e62007-03-24 23:56:43 +00003940 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003941 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003942
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003943 // or X, X = X
3944 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003945 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003946
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003947 // See if we can simplify any instructions used by the instruction whose sole
3948 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003949 if (!isa<VectorType>(I.getType())) {
3950 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3951 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3952 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3953 KnownZero, KnownOne))
3954 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003955 } else if (isa<ConstantAggregateZero>(Op1)) {
3956 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3957 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3958 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3959 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003960 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003961
3962
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003963
Chris Lattner3f5b8772002-05-06 16:14:14 +00003964 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003965 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003966 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003967 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3968 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003969 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003970 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003971 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003972 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003973 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003974 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003975
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003976 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3977 if (match(Op0, m_Xor(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::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003982 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003983 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003984
3985 // Try to fold constant and into select arguments.
3986 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003987 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003988 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003989 if (isa<PHINode>(Op0))
3990 if (Instruction *NV = FoldOpIntoPhi(I))
3991 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003992 }
3993
Chris Lattner4f637d42006-01-06 17:59:59 +00003994 Value *A = 0, *B = 0;
3995 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003996
3997 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3998 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3999 return ReplaceInstUsesWith(I, Op1);
4000 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4001 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4002 return ReplaceInstUsesWith(I, Op0);
4003
Chris Lattner6423d4c2006-07-10 20:25:24 +00004004 // (A | B) | C and A | (B | C) -> bswap if possible.
4005 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004006 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004007 match(Op1, m_Or(m_Value(), m_Value())) ||
4008 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4009 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004010 if (Instruction *BSwap = MatchBSwap(I))
4011 return BSwap;
4012 }
4013
Chris Lattner6e4c6492005-05-09 04:58:36 +00004014 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4015 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004016 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004018 InsertNewInstBefore(NOr, I);
4019 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004020 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004021 }
4022
4023 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4024 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004025 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004026 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
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
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004032 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004033 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004034 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4035 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004036 Value *V1 = 0, *V2 = 0, *V3 = 0;
4037 C1 = dyn_cast<ConstantInt>(C);
4038 C2 = dyn_cast<ConstantInt>(D);
4039 if (C1 && C2) { // (A & C1)|(B & C2)
4040 // If we have: ((V + N) & C1) | (V & C2)
4041 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4042 // replace with V+N.
4043 if (C1->getValue() == ~C2->getValue()) {
4044 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4045 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4046 // Add commutes, try both ways.
4047 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4048 return ReplaceInstUsesWith(I, A);
4049 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4050 return ReplaceInstUsesWith(I, A);
4051 }
4052 // Or commutes, try both ways.
4053 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4054 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4055 // Add commutes, try both ways.
4056 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4057 return ReplaceInstUsesWith(I, B);
4058 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4059 return ReplaceInstUsesWith(I, B);
4060 }
4061 }
Chris Lattner044e5332007-04-08 08:01:49 +00004062 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004063 }
4064
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004065 // Check to see if we have any common things being and'ed. If so, find the
4066 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004067 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4068 if (A == B) // (A & C)|(A & D) == A & (C|D)
4069 V1 = A, V2 = C, V3 = D;
4070 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4071 V1 = A, V2 = B, V3 = C;
4072 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4073 V1 = C, V2 = A, V3 = D;
4074 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4075 V1 = C, V2 = A, V3 = B;
4076
4077 if (V1) {
4078 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4080 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004081 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004082 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004083 }
Chris Lattnere511b742006-11-14 07:46:50 +00004084
4085 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004086 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4087 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4088 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004089 SI0->getOperand(1) == SI1->getOperand(1) &&
4090 (SI0->hasOneUse() || SI1->hasOneUse())) {
4091 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004092 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004093 SI1->getOperand(0),
4094 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004095 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004096 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004097 }
4098 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004099
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004100 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4101 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004102 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004103 } else {
4104 A = 0;
4105 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004106 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004107 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4108 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004109 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004110
Misha Brukmancb6267b2004-07-30 12:50:08 +00004111 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004112 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004113 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004114 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004115 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004116 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004117 }
Chris Lattnera2881962003-02-18 19:28:33 +00004118
Reid Spencere4d87aa2006-12-23 06:05:41 +00004119 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4120 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4121 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004122 return R;
4123
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004124 Value *LHSVal, *RHSVal;
4125 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004126 ICmpInst::Predicate LHSCC, RHSCC;
4127 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4128 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4129 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4130 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4131 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4132 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4133 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004134 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4135 // We can't fold (ugt x, C) | (sgt x, C2).
4136 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004137 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004138 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004139 bool NeedsSwap;
4140 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004141 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004142 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004143 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004144
4145 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004146 std::swap(LHS, RHS);
4147 std::swap(LHSCst, RHSCst);
4148 std::swap(LHSCC, RHSCC);
4149 }
4150
Reid Spencere4d87aa2006-12-23 06:05:41 +00004151 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004152 // comparing a value against two constants and or'ing the result
4153 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4155 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004156 // equal.
4157 assert(LHSCst != RHSCst && "Compares not folded above?");
4158
4159 switch (LHSCC) {
4160 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004161 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004162 switch (RHSCC) {
4163 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004165 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4166 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004167 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004168 LHSVal->getName()+".off");
4169 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004170 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004171 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004172 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004173 break; // (X == 13 | X == 15) -> no change
4174 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4175 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004176 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004177 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4178 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4179 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004180 return ReplaceInstUsesWith(I, RHS);
4181 }
4182 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004183 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004184 switch (RHSCC) {
4185 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004186 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4187 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4188 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004189 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004190 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4191 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4192 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004193 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004194 }
4195 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004196 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004197 switch (RHSCC) {
4198 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004199 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004200 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004201 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004202 // If RHSCst is [us]MAXINT, it is always false. Not handling
4203 // this can cause overflow.
4204 if (RHSCst->isMaxValue(false))
4205 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004206 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4207 false, I);
4208 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4209 break;
4210 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4211 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004212 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004213 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4214 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004215 }
4216 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004217 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004218 switch (RHSCC) {
4219 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004220 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4221 break;
4222 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004223 // If RHSCst is [us]MAXINT, it is always false. Not handling
4224 // this can cause overflow.
4225 if (RHSCst->isMaxValue(true))
4226 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004227 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4228 false, I);
4229 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4230 break;
4231 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4232 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4233 return ReplaceInstUsesWith(I, RHS);
4234 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4235 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004236 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004237 break;
4238 case ICmpInst::ICMP_UGT:
4239 switch (RHSCC) {
4240 default: assert(0 && "Unknown integer condition code!");
4241 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4242 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4243 return ReplaceInstUsesWith(I, LHS);
4244 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4245 break;
4246 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4247 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004248 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004249 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4250 break;
4251 }
4252 break;
4253 case ICmpInst::ICMP_SGT:
4254 switch (RHSCC) {
4255 default: assert(0 && "Unknown integer condition code!");
4256 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4257 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4258 return ReplaceInstUsesWith(I, LHS);
4259 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4260 break;
4261 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4262 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004263 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004264 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4265 break;
4266 }
4267 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004268 }
4269 }
4270 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004271
4272 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004273 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004274 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004275 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004276 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4277 !isa<ICmpInst>(Op1C->getOperand(0))) {
4278 const Type *SrcTy = Op0C->getOperand(0)->getType();
4279 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4280 // Only do this if the casts both really cause code to be
4281 // generated.
4282 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4283 I.getType(), TD) &&
4284 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4285 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004286 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004287 Op1C->getOperand(0),
4288 I.getName());
4289 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004290 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004291 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004292 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004293 }
Chris Lattner99c65742007-10-24 05:38:08 +00004294 }
4295
4296
4297 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4298 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4299 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4300 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004301 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4302 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004303 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4304 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4305 // If either of the constants are nans, then the whole thing returns
4306 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004307 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004308 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4309
4310 // Otherwise, no need to compare the two constants, compare the
4311 // rest.
4312 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4313 RHS->getOperand(0));
4314 }
4315 }
4316 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004317
Chris Lattner7e708292002-06-25 16:13:24 +00004318 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004319}
4320
Dan Gohman844731a2008-05-13 00:00:25 +00004321namespace {
4322
Chris Lattnerc317d392004-02-16 01:20:27 +00004323// XorSelf - Implements: X ^ X --> 0
4324struct XorSelf {
4325 Value *RHS;
4326 XorSelf(Value *rhs) : RHS(rhs) {}
4327 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4328 Instruction *apply(BinaryOperator &Xor) const {
4329 return &Xor;
4330 }
4331};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004332
Dan Gohman844731a2008-05-13 00:00:25 +00004333}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004334
Chris Lattner7e708292002-06-25 16:13:24 +00004335Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004336 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004338
Evan Chengd34af782008-03-25 20:07:13 +00004339 if (isa<UndefValue>(Op1)) {
4340 if (isa<UndefValue>(Op0))
4341 // Handle undef ^ undef -> 0 special case. This is a common
4342 // idiom (misuse).
4343 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004344 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004345 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004346
Chris Lattnerc317d392004-02-16 01:20:27 +00004347 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4348 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004349 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004350 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004351 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004352
4353 // See if we can simplify any instructions used by the instruction whose sole
4354 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004355 if (!isa<VectorType>(I.getType())) {
4356 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4357 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4358 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4359 KnownZero, KnownOne))
4360 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004361 } else if (isa<ConstantAggregateZero>(Op1)) {
4362 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004363 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004364
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004365 // Is this a ~ operation?
4366 if (Value *NotOp = dyn_castNotVal(&I)) {
4367 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4368 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4369 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4370 if (Op0I->getOpcode() == Instruction::And ||
4371 Op0I->getOpcode() == Instruction::Or) {
4372 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4373 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4374 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004375 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004376 Op0I->getOperand(1)->getName()+".not");
4377 InsertNewInstBefore(NotY, I);
4378 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004379 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004380 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004381 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004382 }
4383 }
4384 }
4385 }
4386
4387
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004388 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004389 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4390 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4391 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004392 return new ICmpInst(ICI->getInversePredicate(),
4393 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004394
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004395 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4396 return new FCmpInst(FCI->getInversePredicate(),
4397 FCI->getOperand(0), FCI->getOperand(1));
4398 }
4399
Nick Lewycky517e1f52008-05-31 19:01:33 +00004400 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4401 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4402 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4403 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4404 Instruction::CastOps Opcode = Op0C->getOpcode();
4405 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4406 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4407 Op0C->getDestTy())) {
4408 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4409 CI->getOpcode(), CI->getInversePredicate(),
4410 CI->getOperand(0), CI->getOperand(1)), I);
4411 NewCI->takeName(CI);
4412 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4413 }
4414 }
4415 }
4416 }
4417 }
4418
Reid Spencere4d87aa2006-12-23 06:05:41 +00004419 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004420 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004421 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4422 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004423 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4424 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004425 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004426 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004427 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004428
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004429 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004430 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004431 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004432 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004433 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004434 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004435 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004436 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004437 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004438 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004439 // (X + C) ^ signbit -> (X + C + signbit)
4440 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004441 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004442
Chris Lattner7c4049c2004-01-12 19:35:11 +00004443 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004444 } else if (Op0I->getOpcode() == Instruction::Or) {
4445 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004446 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004447 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4448 // Anything in both C1 and C2 is known to be zero, remove it from
4449 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004450 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004451 NewRHS = ConstantExpr::getAnd(NewRHS,
4452 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004453 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004454 I.setOperand(0, Op0I->getOperand(0));
4455 I.setOperand(1, NewRHS);
4456 return &I;
4457 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004458 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004459 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004460 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004461
4462 // Try to fold constant and into select arguments.
4463 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004465 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004466 if (isa<PHINode>(Op0))
4467 if (Instruction *NV = FoldOpIntoPhi(I))
4468 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004469 }
4470
Chris Lattner8d969642003-03-10 23:06:50 +00004471 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004472 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004473 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004474
Chris Lattner8d969642003-03-10 23:06:50 +00004475 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004476 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004477 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004478
Chris Lattner318bf792007-03-18 22:51:34 +00004479
4480 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4481 if (Op1I) {
4482 Value *A, *B;
4483 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4484 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004485 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004486 I.swapOperands();
4487 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004488 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004489 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004490 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004491 }
Chris Lattner318bf792007-03-18 22:51:34 +00004492 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4493 if (Op0 == A) // A^(A^B) == B
4494 return ReplaceInstUsesWith(I, B);
4495 else if (Op0 == B) // A^(B^A) == B
4496 return ReplaceInstUsesWith(I, A);
4497 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004498 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004499 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004500 std::swap(A, B);
4501 }
Chris Lattner318bf792007-03-18 22:51:34 +00004502 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004503 I.swapOperands(); // Simplified below.
4504 std::swap(Op0, Op1);
4505 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004506 }
Chris Lattner318bf792007-03-18 22:51:34 +00004507 }
4508
4509 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4510 if (Op0I) {
4511 Value *A, *B;
4512 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4513 if (A == Op1) // (B|A)^B == (A|B)^B
4514 std::swap(A, B);
4515 if (B == Op1) { // (A|B)^B == A & ~B
4516 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004517 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4518 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004519 }
Chris Lattner318bf792007-03-18 22:51:34 +00004520 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4521 if (Op1 == A) // (A^B)^A == B
4522 return ReplaceInstUsesWith(I, B);
4523 else if (Op1 == B) // (B^A)^A == B
4524 return ReplaceInstUsesWith(I, A);
4525 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4526 if (A == Op1) // (A&B)^A -> (B&A)^A
4527 std::swap(A, B);
4528 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004529 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004530 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004531 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4532 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004533 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004534 }
Chris Lattner318bf792007-03-18 22:51:34 +00004535 }
4536
4537 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4538 if (Op0I && Op1I && Op0I->isShift() &&
4539 Op0I->getOpcode() == Op1I->getOpcode() &&
4540 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4541 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4542 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004543 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004544 Op1I->getOperand(0),
4545 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004546 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004547 Op1I->getOperand(1));
4548 }
4549
4550 if (Op0I && Op1I) {
4551 Value *A, *B, *C, *D;
4552 // (A & B)^(A | B) -> A ^ B
4553 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4554 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4555 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004556 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004557 }
4558 // (A | B)^(A & B) -> A ^ B
4559 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4560 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4561 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004562 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004563 }
4564
4565 // (A & B)^(C & D)
4566 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4567 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4568 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4569 // (X & Y)^(X & Y) -> (Y^Z) & X
4570 Value *X = 0, *Y = 0, *Z = 0;
4571 if (A == C)
4572 X = A, Y = B, Z = D;
4573 else if (A == D)
4574 X = A, Y = B, Z = C;
4575 else if (B == C)
4576 X = B, Y = A, Z = D;
4577 else if (B == D)
4578 X = B, Y = A, Z = C;
4579
4580 if (X) {
4581 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004582 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4583 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004584 }
4585 }
4586 }
4587
Reid Spencere4d87aa2006-12-23 06:05:41 +00004588 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4589 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4590 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004591 return R;
4592
Chris Lattner6fc205f2006-05-05 06:39:07 +00004593 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004594 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004595 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004596 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4597 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004598 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004599 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004600 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4601 I.getType(), TD) &&
4602 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4603 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004604 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004605 Op1C->getOperand(0),
4606 I.getName());
4607 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004608 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004609 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004610 }
Chris Lattner99c65742007-10-24 05:38:08 +00004611 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004612
Chris Lattner7e708292002-06-25 16:13:24 +00004613 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004614}
4615
Chris Lattnera96879a2004-09-29 17:40:11 +00004616/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4617/// overflowed for this type.
4618static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004619 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004620 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004621
Reid Spencere4e40032007-03-21 23:19:50 +00004622 if (IsSigned)
4623 if (In2->getValue().isNegative())
4624 return Result->getValue().sgt(In1->getValue());
4625 else
4626 return Result->getValue().slt(In1->getValue());
4627 else
4628 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004629}
4630
Chris Lattner574da9b2005-01-13 20:14:25 +00004631/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4632/// code necessary to compute the offset from the base pointer (without adding
4633/// in the base pointer). Return the result as a signed integer of intptr size.
4634static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4635 TargetData &TD = IC.getTargetData();
4636 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004637 const Type *IntPtrTy = TD.getIntPtrType();
4638 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004639
4640 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004641 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004642 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004643
Gabor Greif177dd3f2008-06-12 21:37:33 +00004644 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4645 ++i, ++GTI) {
4646 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004647 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004648 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4649 if (OpC->isZero()) continue;
4650
4651 // Handle a struct index, which adds its field offset to the pointer.
4652 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4653 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4654
4655 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4656 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004657 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004658 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004659 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004660 ConstantInt::get(IntPtrTy, Size),
4661 GEP->getName()+".offs"), I);
4662 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004663 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004664
4665 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4666 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4667 Scale = ConstantExpr::getMul(OC, Scale);
4668 if (Constant *RC = dyn_cast<Constant>(Result))
4669 Result = ConstantExpr::getAdd(RC, Scale);
4670 else {
4671 // Emit an add instruction.
4672 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004673 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004674 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004675 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004676 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004677 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004678 // Convert to correct type.
4679 if (Op->getType() != IntPtrTy) {
4680 if (Constant *OpC = dyn_cast<Constant>(Op))
4681 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4682 else
4683 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4684 Op->getName()+".c"), I);
4685 }
4686 if (Size != 1) {
4687 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4688 if (Constant *OpC = dyn_cast<Constant>(Op))
4689 Op = ConstantExpr::getMul(OpC, Scale);
4690 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004691 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004692 GEP->getName()+".idx"), I);
4693 }
4694
4695 // Emit an add instruction.
4696 if (isa<Constant>(Op) && isa<Constant>(Result))
4697 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4698 cast<Constant>(Result));
4699 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004700 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004701 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004702 }
4703 return Result;
4704}
4705
Chris Lattner10c0d912008-04-22 02:53:33 +00004706
4707/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4708/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4709/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4710/// complex, and scales are involved. The above expression would also be legal
4711/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4712/// later form is less amenable to optimization though, and we are allowed to
4713/// generate the first by knowing that pointer arithmetic doesn't overflow.
4714///
4715/// If we can't emit an optimized form for this expression, this returns null.
4716///
4717static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4718 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004719 TargetData &TD = IC.getTargetData();
4720 gep_type_iterator GTI = gep_type_begin(GEP);
4721
4722 // Check to see if this gep only has a single variable index. If so, and if
4723 // any constant indices are a multiple of its scale, then we can compute this
4724 // in terms of the scale of the variable index. For example, if the GEP
4725 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4726 // because the expression will cross zero at the same point.
4727 unsigned i, e = GEP->getNumOperands();
4728 int64_t Offset = 0;
4729 for (i = 1; i != e; ++i, ++GTI) {
4730 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4731 // Compute the aggregate offset of constant indices.
4732 if (CI->isZero()) continue;
4733
4734 // Handle a struct index, which adds its field offset to the pointer.
4735 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4736 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4737 } else {
4738 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4739 Offset += Size*CI->getSExtValue();
4740 }
4741 } else {
4742 // Found our variable index.
4743 break;
4744 }
4745 }
4746
4747 // If there are no variable indices, we must have a constant offset, just
4748 // evaluate it the general way.
4749 if (i == e) return 0;
4750
4751 Value *VariableIdx = GEP->getOperand(i);
4752 // Determine the scale factor of the variable element. For example, this is
4753 // 4 if the variable index is into an array of i32.
4754 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4755
4756 // Verify that there are no other variable indices. If so, emit the hard way.
4757 for (++i, ++GTI; i != e; ++i, ++GTI) {
4758 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4759 if (!CI) return 0;
4760
4761 // Compute the aggregate offset of constant indices.
4762 if (CI->isZero()) continue;
4763
4764 // Handle a struct index, which adds its field offset to the pointer.
4765 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4766 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4767 } else {
4768 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4769 Offset += Size*CI->getSExtValue();
4770 }
4771 }
4772
4773 // Okay, we know we have a single variable index, which must be a
4774 // pointer/array/vector index. If there is no offset, life is simple, return
4775 // the index.
4776 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4777 if (Offset == 0) {
4778 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4779 // we don't need to bother extending: the extension won't affect where the
4780 // computation crosses zero.
4781 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4782 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4783 VariableIdx->getNameStart(), &I);
4784 return VariableIdx;
4785 }
4786
4787 // Otherwise, there is an index. The computation we will do will be modulo
4788 // the pointer size, so get it.
4789 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4790
4791 Offset &= PtrSizeMask;
4792 VariableScale &= PtrSizeMask;
4793
4794 // To do this transformation, any constant index must be a multiple of the
4795 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4796 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4797 // multiple of the variable scale.
4798 int64_t NewOffs = Offset / (int64_t)VariableScale;
4799 if (Offset != NewOffs*(int64_t)VariableScale)
4800 return 0;
4801
4802 // Okay, we can do this evaluation. Start by converting the index to intptr.
4803 const Type *IntPtrTy = TD.getIntPtrType();
4804 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004805 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004806 true /*SExt*/,
4807 VariableIdx->getNameStart(), &I);
4808 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004809 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004810}
4811
4812
Reid Spencere4d87aa2006-12-23 06:05:41 +00004813/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004814/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004815Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4816 ICmpInst::Predicate Cond,
4817 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004818 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004819
Chris Lattner10c0d912008-04-22 02:53:33 +00004820 // Look through bitcasts.
4821 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4822 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004823
Chris Lattner574da9b2005-01-13 20:14:25 +00004824 Value *PtrBase = GEPLHS->getOperand(0);
4825 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004826 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004827 // This transformation (ignoring the base and scales) is valid because we
4828 // know pointers can't overflow. See if we can output an optimized form.
4829 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4830
4831 // If not, synthesize the offset the hard way.
4832 if (Offset == 0)
4833 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004834 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4835 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004836 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004837 // If the base pointers are different, but the indices are the same, just
4838 // compare the base pointer.
4839 if (PtrBase != GEPRHS->getOperand(0)) {
4840 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004841 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004842 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004843 if (IndicesTheSame)
4844 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4845 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4846 IndicesTheSame = false;
4847 break;
4848 }
4849
4850 // If all indices are the same, just compare the base pointers.
4851 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004852 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4853 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004854
4855 // Otherwise, the base pointers are different and the indices are
4856 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004857 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004858 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004859
Chris Lattnere9d782b2005-01-13 22:25:21 +00004860 // If one of the GEPs has all zero indices, recurse.
4861 bool AllZeros = true;
4862 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4863 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4864 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4865 AllZeros = false;
4866 break;
4867 }
4868 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4870 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004871
4872 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004873 AllZeros = true;
4874 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4875 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4876 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4877 AllZeros = false;
4878 break;
4879 }
4880 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004881 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004882
Chris Lattner4401c9c2005-01-14 00:20:05 +00004883 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4884 // If the GEPs only differ by one index, compare it.
4885 unsigned NumDifferences = 0; // Keep track of # differences.
4886 unsigned DiffOperand = 0; // The operand that differs.
4887 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4888 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004889 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4890 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004891 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004892 NumDifferences = 2;
4893 break;
4894 } else {
4895 if (NumDifferences++) break;
4896 DiffOperand = i;
4897 }
4898 }
4899
4900 if (NumDifferences == 0) // SAME GEP?
4901 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004902 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004903 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004904
Chris Lattner4401c9c2005-01-14 00:20:05 +00004905 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004906 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4907 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004908 // Make sure we do a signed comparison here.
4909 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004910 }
4911 }
4912
Reid Spencere4d87aa2006-12-23 06:05:41 +00004913 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004914 // the result to fold to a constant!
4915 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4916 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4917 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4918 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4919 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004920 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004921 }
4922 }
4923 return 0;
4924}
4925
Chris Lattnera5406232008-05-19 20:18:56 +00004926/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4927///
4928Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4929 Instruction *LHSI,
4930 Constant *RHSC) {
4931 if (!isa<ConstantFP>(RHSC)) return 0;
4932 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4933
4934 // Get the width of the mantissa. We don't want to hack on conversions that
4935 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004936 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004937 if (MantissaWidth == -1) return 0; // Unknown.
4938
4939 // Check to see that the input is converted from an integer type that is small
4940 // enough that preserves all bits. TODO: check here for "known" sign bits.
4941 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4942 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4943
4944 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4945 if (isa<UIToFPInst>(LHSI))
4946 ++InputSize;
4947
4948 // If the conversion would lose info, don't hack on this.
4949 if ((int)InputSize > MantissaWidth)
4950 return 0;
4951
4952 // Otherwise, we can potentially simplify the comparison. We know that it
4953 // will always come through as an integer value and we know the constant is
4954 // not a NAN (it would have been previously simplified).
4955 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4956
4957 ICmpInst::Predicate Pred;
4958 switch (I.getPredicate()) {
4959 default: assert(0 && "Unexpected predicate!");
4960 case FCmpInst::FCMP_UEQ:
4961 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4962 case FCmpInst::FCMP_UGT:
4963 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4964 case FCmpInst::FCMP_UGE:
4965 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4966 case FCmpInst::FCMP_ULT:
4967 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4968 case FCmpInst::FCMP_ULE:
4969 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4970 case FCmpInst::FCMP_UNE:
4971 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4972 case FCmpInst::FCMP_ORD:
4973 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4974 case FCmpInst::FCMP_UNO:
4975 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4976 }
4977
4978 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4979
4980 // Now we know that the APFloat is a normal number, zero or inf.
4981
Chris Lattner85162782008-05-20 03:50:52 +00004982 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004983 // comparing an i8 to 300.0.
4984 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4985
4986 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4987 // and large values.
4988 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4989 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4990 APFloat::rmNearestTiesToEven);
4991 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004992 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4993 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004994 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4995 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4996 }
4997
4998 // See if the RHS value is < SignedMin.
4999 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5000 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5001 APFloat::rmNearestTiesToEven);
5002 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005003 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5004 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00005005 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5006 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5007 }
5008
5009 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5010 // it may still be fractional. See if it is fractional by casting the FP
5011 // value to the integer value and back, checking for equality. Don't do this
5012 // for zero, because -0.0 is not fractional.
5013 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5014 if (!RHS.isZero() &&
5015 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5016 // If we had a comparison against a fractional value, we have to adjust
5017 // the compare predicate and sometimes the value. RHSC is rounded towards
5018 // zero at this point.
5019 switch (Pred) {
5020 default: assert(0 && "Unexpected integer comparison!");
5021 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5022 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5023 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5024 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5025 case ICmpInst::ICMP_SLE:
5026 // (float)int <= 4.4 --> int <= 4
5027 // (float)int <= -4.4 --> int < -4
5028 if (RHS.isNegative())
5029 Pred = ICmpInst::ICMP_SLT;
5030 break;
5031 case ICmpInst::ICMP_SLT:
5032 // (float)int < -4.4 --> int < -4
5033 // (float)int < 4.4 --> int <= 4
5034 if (!RHS.isNegative())
5035 Pred = ICmpInst::ICMP_SLE;
5036 break;
5037 case ICmpInst::ICMP_SGT:
5038 // (float)int > 4.4 --> int > 4
5039 // (float)int > -4.4 --> int >= -4
5040 if (RHS.isNegative())
5041 Pred = ICmpInst::ICMP_SGE;
5042 break;
5043 case ICmpInst::ICMP_SGE:
5044 // (float)int >= -4.4 --> int >= -4
5045 // (float)int >= 4.4 --> int > 4
5046 if (!RHS.isNegative())
5047 Pred = ICmpInst::ICMP_SGT;
5048 break;
5049 }
5050 }
5051
5052 // Lower this FP comparison into an appropriate integer version of the
5053 // comparison.
5054 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5055}
5056
Reid Spencere4d87aa2006-12-23 06:05:41 +00005057Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5058 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005060
Chris Lattner58e97462007-01-14 19:42:17 +00005061 // Fold trivial predicates.
5062 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5063 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5064 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5065 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5066
5067 // Simplify 'fcmp pred X, X'
5068 if (Op0 == Op1) {
5069 switch (I.getPredicate()) {
5070 default: assert(0 && "Unknown predicate!");
5071 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5072 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5073 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5074 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5075 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5076 case FCmpInst::FCMP_OLT: // True if ordered and less than
5077 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5078 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5079
5080 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5081 case FCmpInst::FCMP_ULT: // True if unordered or less than
5082 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5083 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5084 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5085 I.setPredicate(FCmpInst::FCMP_UNO);
5086 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5087 return &I;
5088
5089 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5090 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5091 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5092 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5093 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5094 I.setPredicate(FCmpInst::FCMP_ORD);
5095 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5096 return &I;
5097 }
5098 }
5099
Reid Spencere4d87aa2006-12-23 06:05:41 +00005100 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005101 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005102
Reid Spencere4d87aa2006-12-23 06:05:41 +00005103 // Handle fcmp with constant RHS
5104 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005105 // If the constant is a nan, see if we can fold the comparison based on it.
5106 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5107 if (CFP->getValueAPF().isNaN()) {
5108 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5109 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005110 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5111 "Comparison must be either ordered or unordered!");
5112 // True if unordered.
5113 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005114 }
5115 }
5116
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5118 switch (LHSI->getOpcode()) {
5119 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005120 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5121 // block. If in the same block, we're encouraging jump threading. If
5122 // not, we are just pessimizing the code by making an i1 phi.
5123 if (LHSI->getParent() == I.getParent())
5124 if (Instruction *NV = FoldOpIntoPhi(I))
5125 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005127 case Instruction::SIToFP:
5128 case Instruction::UIToFP:
5129 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5130 return NV;
5131 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005132 case Instruction::Select:
5133 // If either operand of the select is a constant, we can fold the
5134 // comparison into the select arms, which will cause one to be
5135 // constant folded and the select turned into a bitwise or.
5136 Value *Op1 = 0, *Op2 = 0;
5137 if (LHSI->hasOneUse()) {
5138 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5139 // Fold the known value into the constant operand.
5140 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5141 // Insert a new FCmp of the other select operand.
5142 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5143 LHSI->getOperand(2), RHSC,
5144 I.getName()), I);
5145 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5146 // Fold the known value into the constant operand.
5147 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5148 // Insert a new FCmp of the other select operand.
5149 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5150 LHSI->getOperand(1), RHSC,
5151 I.getName()), I);
5152 }
5153 }
5154
5155 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005156 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005157 break;
5158 }
5159 }
5160
5161 return Changed ? &I : 0;
5162}
5163
5164Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5165 bool Changed = SimplifyCompare(I);
5166 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5167 const Type *Ty = Op0->getType();
5168
5169 // icmp X, X
5170 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005171 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005172 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005173
5174 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005175 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005176
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005178 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005179 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5180 isa<ConstantPointerNull>(Op0)) &&
5181 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005182 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005183 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005184 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005185
Reid Spencere4d87aa2006-12-23 06:05:41 +00005186 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005187 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005188 switch (I.getPredicate()) {
5189 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005190 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005191 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005192 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005193 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005194 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005195 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005196 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005197
Reid Spencere4d87aa2006-12-23 06:05:41 +00005198 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005199 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005200 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005201 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005202 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005203 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005204 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005205 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005206 case ICmpInst::ICMP_SGT:
5207 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005208 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005209 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5210 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5211 InsertNewInstBefore(Not, I);
5212 return BinaryOperator::CreateAnd(Not, Op0);
5213 }
5214 case ICmpInst::ICMP_UGE:
5215 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5216 // FALL THROUGH
5217 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005218 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005219 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005220 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005221 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005222 case ICmpInst::ICMP_SGE:
5223 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5224 // FALL THROUGH
5225 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5226 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5227 InsertNewInstBefore(Not, I);
5228 return BinaryOperator::CreateOr(Not, Op0);
5229 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005230 }
Chris Lattner8b170942002-08-09 23:47:40 +00005231 }
5232
Chris Lattner2be51ae2004-06-09 04:24:29 +00005233 // See if we are doing a comparison between a constant and an instruction that
5234 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005235 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005236 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005237
Chris Lattnerb6566012008-01-05 01:18:20 +00005238 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5239 if (I.isEquality() && CI->isNullValue() &&
5240 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5241 // (icmp cond A B) if cond is equality
5242 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005243 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005244
Chris Lattner84dff672008-07-11 05:08:55 +00005245 // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5246 // icmp lt or icmp gt instruction. This allows us to rely on them being
5247 // folded in the code below.
5248 switch (I.getPredicate()) {
5249 default: break;
5250 case ICmpInst::ICMP_ULE:
5251 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5253 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5254 case ICmpInst::ICMP_SLE:
5255 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5256 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5257 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5258 case ICmpInst::ICMP_UGE:
5259 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5260 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5261 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5262 case ICmpInst::ICMP_SGE:
5263 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5264 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5265 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5266 }
5267
Chris Lattner183661e2008-07-11 05:40:05 +00005268 // See if we can fold the comparison based on range information we can get
5269 // by checking whether bits are known to be zero or one in the input.
5270 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5271 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5272
5273 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005274 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005275 bool UnusedBit;
5276 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5277
Chris Lattner4241e4d2007-07-15 20:54:51 +00005278 if (SimplifyDemandedBits(Op0,
5279 isSignBit ? APInt::getSignBit(BitWidth)
5280 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005281 KnownZero, KnownOne, 0))
5282 return &I;
5283
5284 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005285 // in. Compute the Min, Max and RHS values based on the known bits. For the
5286 // EQ and NE we use unsigned values.
5287 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005288 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5289 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5290 else
5291 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5292
Chris Lattner183661e2008-07-11 05:40:05 +00005293 // If Min and Max are known to be the same, then SimplifyDemandedBits
5294 // figured out that the LHS is a constant. Just constant fold this now so
5295 // that code below can assume that Min != Max.
5296 if (Min == Max)
5297 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5298 ConstantInt::get(Min),
5299 CI));
5300
5301 // Based on the range information we know about the LHS, see if we can
5302 // simplify this comparison. For example, (x&4) < 8 is always true.
5303 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005304 switch (I.getPredicate()) { // LE/GE have been folded already.
5305 default: assert(0 && "Unknown icmp opcode!");
5306 case ICmpInst::ICMP_EQ:
5307 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5308 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5309 break;
5310 case ICmpInst::ICMP_NE:
5311 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5312 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5313 break;
5314 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005315 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005316 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005317 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005318 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005319 if (RHSVal == Max) // A <u MAX -> A != MAX
5320 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5321 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5322 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5323
5324 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5325 if (CI->isMinValue(true))
5326 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5327 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005328 break;
5329 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005330 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005331 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005332 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005333 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005334
5335 if (RHSVal == Min) // A >u MIN -> A != MIN
5336 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5337 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5338 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5339
5340 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5341 if (CI->isMaxValue(true))
5342 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5343 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005344 break;
5345 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005346 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005347 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005348 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005349 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005350 if (RHSVal == Max) // A <s MAX -> A != MAX
5351 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005352 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005353 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005354 break;
5355 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005356 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005357 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005358 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005359 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005360
5361 if (RHSVal == Min) // A >s MIN -> A != MIN
5362 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5363 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5364 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005365 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005366 }
5367
Reid Spencere4d87aa2006-12-23 06:05:41 +00005368 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005369 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005370 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005371 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005372 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5373 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005374 }
5375
Chris Lattner01deb9d2007-04-03 17:43:25 +00005376 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005377 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5378 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5379 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005380 case Instruction::GetElementPtr:
5381 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005382 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005383 bool isAllZeros = true;
5384 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5385 if (!isa<Constant>(LHSI->getOperand(i)) ||
5386 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5387 isAllZeros = false;
5388 break;
5389 }
5390 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005391 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005392 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5393 }
5394 break;
5395
Chris Lattner6970b662005-04-23 15:31:55 +00005396 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005397 // Only fold icmp into the PHI if the phi and fcmp are in the same
5398 // block. If in the same block, we're encouraging jump threading. If
5399 // not, we are just pessimizing the code by making an i1 phi.
5400 if (LHSI->getParent() == I.getParent())
5401 if (Instruction *NV = FoldOpIntoPhi(I))
5402 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005403 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005404 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005405 // If either operand of the select is a constant, we can fold the
5406 // comparison into the select arms, which will cause one to be
5407 // constant folded and the select turned into a bitwise or.
5408 Value *Op1 = 0, *Op2 = 0;
5409 if (LHSI->hasOneUse()) {
5410 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5411 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005412 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5413 // Insert a new ICmp of the other select operand.
5414 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5415 LHSI->getOperand(2), RHSC,
5416 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005417 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5418 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005419 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5420 // Insert a new ICmp of the other select operand.
5421 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5422 LHSI->getOperand(1), RHSC,
5423 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005424 }
5425 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005426
Chris Lattner6970b662005-04-23 15:31:55 +00005427 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005428 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005429 break;
5430 }
Chris Lattner4802d902007-04-06 18:57:34 +00005431 case Instruction::Malloc:
5432 // If we have (malloc != null), and if the malloc has a single use, we
5433 // can assume it is successful and remove the malloc.
5434 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5435 AddToWorkList(LHSI);
5436 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005437 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005438 }
5439 break;
5440 }
Chris Lattner6970b662005-04-23 15:31:55 +00005441 }
5442
Reid Spencere4d87aa2006-12-23 06:05:41 +00005443 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005444 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005445 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005446 return NI;
5447 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005448 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5449 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005450 return NI;
5451
Reid Spencere4d87aa2006-12-23 06:05:41 +00005452 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005453 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5454 // now.
5455 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5456 if (isa<PointerType>(Op0->getType()) &&
5457 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005458 // We keep moving the cast from the left operand over to the right
5459 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005460 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005461
Chris Lattner57d86372007-01-06 01:45:59 +00005462 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5463 // so eliminate it as well.
5464 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5465 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005466
Chris Lattnerde90b762003-11-03 04:25:02 +00005467 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005468 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005469 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005470 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005471 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005472 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005473 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005474 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005475 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005476 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005477 }
Chris Lattner57d86372007-01-06 01:45:59 +00005478 }
5479
5480 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005481 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005482 // This comes up when you have code like
5483 // int X = A < B;
5484 // if (X) ...
5485 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005486 // with a constant or another cast from the same type.
5487 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005488 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005489 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005490 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005491
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005492 // See if it's the same type of instruction on the left and right.
5493 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5494 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky1b344bc2008-08-17 07:34:14 +00005495 if (Op0I->getOpcode() == Op1I->getOpcode() &&
5496 Op0I->getOperand(1) == Op1I->getOperand(1)) {
5497 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005498 default: break;
5499 case Instruction::Add:
5500 case Instruction::Sub:
5501 case Instruction::Xor:
Nick Lewycky1b344bc2008-08-17 07:34:14 +00005502 if (I.isEquality()) {
5503 // icmp eq/ne a+x, b+x --> icmp eq/ne a, b
5504 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5505 Op1I->getOperand(0));
5506 } else {
Nick Lewycky1b344bc2008-08-17 07:34:14 +00005507 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Nick Lewycky91a0f782008-08-17 19:58:24 +00005508 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
Nick Lewycky1b344bc2008-08-17 07:34:14 +00005509 if (CI->getValue().isSignBit()) {
5510 ICmpInst::Predicate Pred = I.isSignedPredicate()
5511 ? I.getUnsignedPredicate()
5512 : I.getSignedPredicate();
5513 return new ICmpInst(Pred, Op0I->getOperand(0),
5514 Op1I->getOperand(0));
5515 }
Nick Lewycky91a0f782008-08-17 19:58:24 +00005516
5517 // icmp u/s (a ^ ~signbit), (b ^ ~signbit) --> icmp s/u b, a
5518 if ((~CI->getValue()).isSignBit()) {
5519 ICmpInst::Predicate Pred = I.isSignedPredicate()
5520 ? I.getUnsignedPredicate()
5521 : I.getSignedPredicate();
5522 Pred = I.getSwappedPredicate(Pred);
5523 return new ICmpInst(Pred, Op0I->getOperand(0),
5524 Op1I->getOperand(0));
5525
5526 }
Nick Lewycky1b344bc2008-08-17 07:34:14 +00005527 }
5528 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005529 break;
5530 case Instruction::Mul:
Nick Lewycky1b344bc2008-08-17 07:34:14 +00005531 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5532 // Mask = -1 >> count-trailing-zeros(Cst).
5533 if (Op0I->hasOneUse() && Op1I->hasOneUse() && I.isEquality()) {
5534 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5535 if (!CI->isZero() && !CI->isOne()) {
5536 const APInt &AP = CI->getValue();
5537 ConstantInt *Mask =
5538 ConstantInt::get(APInt::getLowBitsSet(AP.getBitWidth(),
5539 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005540 AP.countTrailingZeros()));
Nick Lewycky1b344bc2008-08-17 07:34:14 +00005541 Instruction *And1 =
5542 BinaryOperator::CreateAnd(Op0I->getOperand(0), Mask);
5543 Instruction *And2 =
5544 BinaryOperator::CreateAnd(Op1I->getOperand(0), Mask);
5545 InsertNewInstBefore(And1, I);
5546 InsertNewInstBefore(And2, I);
5547 return new ICmpInst(I.getPredicate(), And1, And2);
5548 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005549 }
5550 }
5551 break;
5552 }
5553 }
5554 }
5555 }
5556
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005557 // ~x < ~y --> y < x
5558 { Value *A, *B;
5559 if (match(Op0, m_Not(m_Value(A))) &&
5560 match(Op1, m_Not(m_Value(B))))
5561 return new ICmpInst(I.getPredicate(), B, A);
5562 }
5563
Chris Lattner65b72ba2006-09-18 04:22:48 +00005564 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005565 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005566
5567 // -x == -y --> x == y
5568 if (match(Op0, m_Neg(m_Value(A))) &&
5569 match(Op1, m_Neg(m_Value(B))))
5570 return new ICmpInst(I.getPredicate(), A, B);
5571
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005572 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5573 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5574 Value *OtherVal = A == Op1 ? B : A;
5575 return new ICmpInst(I.getPredicate(), OtherVal,
5576 Constant::getNullValue(A->getType()));
5577 }
5578
5579 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5580 // A^c1 == C^c2 --> A == C^(c1^c2)
5581 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5582 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5583 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005584 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005585 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005586 return new ICmpInst(I.getPredicate(), A,
5587 InsertNewInstBefore(Xor, I));
5588 }
5589
5590 // A^B == A^D -> B == D
5591 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5592 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5593 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5594 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5595 }
5596 }
5597
5598 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5599 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005600 // A == (A^B) -> B == 0
5601 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005602 return new ICmpInst(I.getPredicate(), OtherVal,
5603 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005604 }
5605 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005606 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005607 return new ICmpInst(I.getPredicate(), B,
5608 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005609 }
5610 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005611 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005612 return new ICmpInst(I.getPredicate(), B,
5613 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005614 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005615
Chris Lattner9c2328e2006-11-14 06:06:06 +00005616 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5617 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5618 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5619 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5620 Value *X = 0, *Y = 0, *Z = 0;
5621
5622 if (A == C) {
5623 X = B; Y = D; Z = A;
5624 } else if (A == D) {
5625 X = B; Y = C; Z = A;
5626 } else if (B == C) {
5627 X = A; Y = D; Z = B;
5628 } else if (B == D) {
5629 X = A; Y = C; Z = B;
5630 }
5631
5632 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005633 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5634 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005635 I.setOperand(0, Op1);
5636 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5637 return &I;
5638 }
5639 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005640 }
Chris Lattner7e708292002-06-25 16:13:24 +00005641 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005642}
5643
Chris Lattner562ef782007-06-20 23:46:26 +00005644
5645/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5646/// and CmpRHS are both known to be integer constants.
5647Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5648 ConstantInt *DivRHS) {
5649 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5650 const APInt &CmpRHSV = CmpRHS->getValue();
5651
5652 // FIXME: If the operand types don't match the type of the divide
5653 // then don't attempt this transform. The code below doesn't have the
5654 // logic to deal with a signed divide and an unsigned compare (and
5655 // vice versa). This is because (x /s C1) <s C2 produces different
5656 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5657 // (x /u C1) <u C2. Simply casting the operands and result won't
5658 // work. :( The if statement below tests that condition and bails
5659 // if it finds it.
5660 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5661 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5662 return 0;
5663 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005664 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005665
5666 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5667 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5668 // C2 (CI). By solving for X we can turn this into a range check
5669 // instead of computing a divide.
5670 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5671
5672 // Determine if the product overflows by seeing if the product is
5673 // not equal to the divide. Make sure we do the same kind of divide
5674 // as in the LHS instruction that we're folding.
5675 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5676 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5677
5678 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005679 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005680
Chris Lattner1dbfd482007-06-21 18:11:19 +00005681 // Figure out the interval that is being checked. For example, a comparison
5682 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5683 // Compute this interval based on the constants involved and the signedness of
5684 // the compare/divide. This computes a half-open interval, keeping track of
5685 // whether either value in the interval overflows. After analysis each
5686 // overflow variable is set to 0 if it's corresponding bound variable is valid
5687 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5688 int LoOverflow = 0, HiOverflow = 0;
5689 ConstantInt *LoBound = 0, *HiBound = 0;
5690
5691
Chris Lattner562ef782007-06-20 23:46:26 +00005692 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005693 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005694 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005695 HiOverflow = LoOverflow = ProdOV;
5696 if (!HiOverflow)
5697 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005698 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005699 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005700 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005701 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5702 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005703 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005704 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5705 HiOverflow = LoOverflow = ProdOV;
5706 if (!HiOverflow)
5707 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005708 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005709 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005710 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5711 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005712 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005713 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005714 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005715 }
Dan Gohman76491272008-02-13 22:09:18 +00005716 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005717 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005718 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005719 LoBound = AddOne(DivRHS);
5720 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005721 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5722 HiOverflow = 1; // [INTMIN+1, overflow)
5723 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5724 }
Dan Gohman76491272008-02-13 22:09:18 +00005725 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005726 // e.g. X/-5 op 3 --> [-19, -14)
5727 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005728 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005729 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005730 HiBound = AddOne(Prod);
5731 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005732 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005733 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005734 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005735 HiBound = Subtract(Prod, DivRHS);
5736 }
5737
Chris Lattner1dbfd482007-06-21 18:11:19 +00005738 // Dividing by a negative swaps the condition. LT <-> GT
5739 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005740 }
5741
5742 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005743 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005744 default: assert(0 && "Unhandled icmp opcode!");
5745 case ICmpInst::ICMP_EQ:
5746 if (LoOverflow && HiOverflow)
5747 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5748 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005749 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005750 ICmpInst::ICMP_UGE, X, LoBound);
5751 else if (LoOverflow)
5752 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5753 ICmpInst::ICMP_ULT, X, HiBound);
5754 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005755 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005756 case ICmpInst::ICMP_NE:
5757 if (LoOverflow && HiOverflow)
5758 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5759 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005760 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005761 ICmpInst::ICMP_ULT, X, LoBound);
5762 else if (LoOverflow)
5763 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5764 ICmpInst::ICMP_UGE, X, HiBound);
5765 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005766 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005767 case ICmpInst::ICMP_ULT:
5768 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005769 if (LoOverflow == +1) // Low bound is greater than input range.
5770 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5771 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005772 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005773 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005774 case ICmpInst::ICMP_UGT:
5775 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005776 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005777 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005778 else if (HiOverflow == -1) // High bound less than input range.
5779 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5780 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005781 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5782 else
5783 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5784 }
5785}
5786
5787
Chris Lattner01deb9d2007-04-03 17:43:25 +00005788/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5789///
5790Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5791 Instruction *LHSI,
5792 ConstantInt *RHS) {
5793 const APInt &RHSV = RHS->getValue();
5794
5795 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005796 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005797 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5798 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5799 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005800 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5801 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005802 Value *CompareVal = LHSI->getOperand(0);
5803
5804 // If the sign bit of the XorCST is not set, there is no change to
5805 // the operation, just stop using the Xor.
5806 if (!XorCST->getValue().isNegative()) {
5807 ICI.setOperand(0, CompareVal);
5808 AddToWorkList(LHSI);
5809 return &ICI;
5810 }
5811
5812 // Was the old condition true if the operand is positive?
5813 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5814
5815 // If so, the new one isn't.
5816 isTrueIfPositive ^= true;
5817
5818 if (isTrueIfPositive)
5819 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5820 else
5821 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5822 }
Nick Lewyckycbe23e32008-08-17 07:54:14 +00005823
5824 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
5825 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
5826 const APInt &SignBit = XorCST->getValue();
5827 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
5828 ? ICI.getUnsignedPredicate()
5829 : ICI.getSignedPredicate();
5830 return new ICmpInst(Pred, LHSI->getOperand(0),
5831 ConstantInt::get(RHSV ^ SignBit));
5832 }
Nick Lewycky91a0f782008-08-17 19:58:24 +00005833
Nick Lewyckye86389d2008-08-17 20:02:02 +00005834 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Nick Lewycky91a0f782008-08-17 19:58:24 +00005835 if (!ICI.isEquality() && (~XorCST->getValue()).isSignBit()) {
5836 const APInt &NotSignBit = XorCST->getValue();
5837 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
5838 ? ICI.getUnsignedPredicate()
5839 : ICI.getSignedPredicate();
5840 Pred = ICI.getSwappedPredicate(Pred);
5841 return new ICmpInst(Pred, LHSI->getOperand(0),
5842 ConstantInt::get(RHSV ^ NotSignBit));
5843 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005844 }
5845 break;
5846 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5847 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5848 LHSI->getOperand(0)->hasOneUse()) {
5849 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5850
5851 // If the LHS is an AND of a truncating cast, we can widen the
5852 // and/compare to be the input width without changing the value
5853 // produced, eliminating a cast.
5854 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5855 // We can do this transformation if either the AND constant does not
5856 // have its sign bit set or if it is an equality comparison.
5857 // Extending a relational comparison when we're checking the sign
5858 // bit would not work.
5859 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005860 (ICI.isEquality() ||
5861 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005862 uint32_t BitWidth =
5863 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5864 APInt NewCST = AndCST->getValue();
5865 NewCST.zext(BitWidth);
5866 APInt NewCI = RHSV;
5867 NewCI.zext(BitWidth);
5868 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005869 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005870 ConstantInt::get(NewCST),LHSI->getName());
5871 InsertNewInstBefore(NewAnd, ICI);
5872 return new ICmpInst(ICI.getPredicate(), NewAnd,
5873 ConstantInt::get(NewCI));
5874 }
5875 }
5876
5877 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5878 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5879 // happens a LOT in code produced by the C front-end, for bitfield
5880 // access.
5881 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5882 if (Shift && !Shift->isShift())
5883 Shift = 0;
5884
5885 ConstantInt *ShAmt;
5886 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5887 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5888 const Type *AndTy = AndCST->getType(); // Type of the and.
5889
5890 // We can fold this as long as we can't shift unknown bits
5891 // into the mask. This can only happen with signed shift
5892 // rights, as they sign-extend.
5893 if (ShAmt) {
5894 bool CanFold = Shift->isLogicalShift();
5895 if (!CanFold) {
5896 // To test for the bad case of the signed shr, see if any
5897 // of the bits shifted in could be tested after the mask.
5898 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5899 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5900
5901 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5902 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5903 AndCST->getValue()) == 0)
5904 CanFold = true;
5905 }
5906
5907 if (CanFold) {
5908 Constant *NewCst;
5909 if (Shift->getOpcode() == Instruction::Shl)
5910 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5911 else
5912 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5913
5914 // Check to see if we are shifting out any of the bits being
5915 // compared.
5916 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5917 // If we shifted bits out, the fold is not going to work out.
5918 // As a special case, check to see if this means that the
5919 // result is always true or false now.
5920 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5921 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5922 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5923 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5924 } else {
5925 ICI.setOperand(1, NewCst);
5926 Constant *NewAndCST;
5927 if (Shift->getOpcode() == Instruction::Shl)
5928 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5929 else
5930 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5931 LHSI->setOperand(1, NewAndCST);
5932 LHSI->setOperand(0, Shift->getOperand(0));
5933 AddToWorkList(Shift); // Shift is dead.
5934 AddUsesToWorkList(ICI);
5935 return &ICI;
5936 }
5937 }
5938 }
5939
5940 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5941 // preferable because it allows the C<<Y expression to be hoisted out
5942 // of a loop if Y is invariant and X is not.
5943 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5944 ICI.isEquality() && !Shift->isArithmeticShift() &&
5945 isa<Instruction>(Shift->getOperand(0))) {
5946 // Compute C << Y.
5947 Value *NS;
5948 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005949 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005950 Shift->getOperand(1), "tmp");
5951 } else {
5952 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005953 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005954 Shift->getOperand(1), "tmp");
5955 }
5956 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5957
5958 // Compute X & (C << Y).
5959 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005960 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005961 InsertNewInstBefore(NewAnd, ICI);
5962
5963 ICI.setOperand(0, NewAnd);
5964 return &ICI;
5965 }
5966 }
5967 break;
5968
Chris Lattnera0141b92007-07-15 20:42:37 +00005969 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5970 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5971 if (!ShAmt) break;
5972
5973 uint32_t TypeBits = RHSV.getBitWidth();
5974
5975 // Check that the shift amount is in range. If not, don't perform
5976 // undefined shifts. When the shift is visited it will be
5977 // simplified.
5978 if (ShAmt->uge(TypeBits))
5979 break;
5980
5981 if (ICI.isEquality()) {
5982 // If we are comparing against bits always shifted out, the
5983 // comparison cannot succeed.
5984 Constant *Comp =
5985 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5986 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5987 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5988 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5989 return ReplaceInstUsesWith(ICI, Cst);
5990 }
5991
5992 if (LHSI->hasOneUse()) {
5993 // Otherwise strength reduce the shift into an and.
5994 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5995 Constant *Mask =
5996 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005997
Chris Lattnera0141b92007-07-15 20:42:37 +00005998 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005999 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006000 Mask, LHSI->getName()+".mask");
6001 Value *And = InsertNewInstBefore(AndI, ICI);
6002 return new ICmpInst(ICI.getPredicate(), And,
6003 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006004 }
6005 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006006
6007 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6008 bool TrueIfSigned = false;
6009 if (LHSI->hasOneUse() &&
6010 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6011 // (X << 31) <s 0 --> (X&1) != 0
6012 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6013 (TypeBits-ShAmt->getZExtValue()-1));
6014 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006015 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006016 Mask, LHSI->getName()+".mask");
6017 Value *And = InsertNewInstBefore(AndI, ICI);
6018
6019 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6020 And, Constant::getNullValue(And->getType()));
6021 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006022 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006023 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006024
6025 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006026 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006027 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006028 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006029 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006030
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006031 // Check that the shift amount is in range. If not, don't perform
6032 // undefined shifts. When the shift is visited it will be
6033 // simplified.
6034 uint32_t TypeBits = RHSV.getBitWidth();
6035 if (ShAmt->uge(TypeBits))
6036 break;
6037
6038 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006039
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006040 // If we are comparing against bits always shifted out, the
6041 // comparison cannot succeed.
6042 APInt Comp = RHSV << ShAmtVal;
6043 if (LHSI->getOpcode() == Instruction::LShr)
6044 Comp = Comp.lshr(ShAmtVal);
6045 else
6046 Comp = Comp.ashr(ShAmtVal);
6047
6048 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6049 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6050 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6051 return ReplaceInstUsesWith(ICI, Cst);
6052 }
6053
6054 // Otherwise, check to see if the bits shifted out are known to be zero.
6055 // If so, we can compare against the unshifted value:
6056 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006057 if (LHSI->hasOneUse() &&
6058 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006059 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6060 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6061 ConstantExpr::getShl(RHS, ShAmt));
6062 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006063
Evan Chengf30752c2008-04-23 00:38:06 +00006064 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006065 // Otherwise strength reduce the shift into an and.
6066 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6067 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006068
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006069 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006070 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006071 Mask, LHSI->getName()+".mask");
6072 Value *And = InsertNewInstBefore(AndI, ICI);
6073 return new ICmpInst(ICI.getPredicate(), And,
6074 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006075 }
6076 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006077 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006078
6079 case Instruction::SDiv:
6080 case Instruction::UDiv:
6081 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6082 // Fold this div into the comparison, producing a range check.
6083 // Determine, based on the divide type, what the range is being
6084 // checked. If there is an overflow on the low or high side, remember
6085 // it, otherwise compute the range [low, hi) bounding the new value.
6086 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006087 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6088 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6089 DivRHS))
6090 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006091 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006092
6093 case Instruction::Add:
6094 // Fold: icmp pred (add, X, C1), C2
6095
6096 if (!ICI.isEquality()) {
6097 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6098 if (!LHSC) break;
6099 const APInt &LHSV = LHSC->getValue();
6100
6101 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6102 .subtract(LHSV);
6103
6104 if (ICI.isSignedPredicate()) {
6105 if (CR.getLower().isSignBit()) {
6106 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6107 ConstantInt::get(CR.getUpper()));
6108 } else if (CR.getUpper().isSignBit()) {
6109 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6110 ConstantInt::get(CR.getLower()));
6111 }
6112 } else {
6113 if (CR.getLower().isMinValue()) {
6114 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6115 ConstantInt::get(CR.getUpper()));
6116 } else if (CR.getUpper().isMinValue()) {
6117 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6118 ConstantInt::get(CR.getLower()));
6119 }
6120 }
6121 }
6122 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006123 }
6124
6125 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6126 if (ICI.isEquality()) {
6127 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6128
6129 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6130 // the second operand is a constant, simplify a bit.
6131 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6132 switch (BO->getOpcode()) {
6133 case Instruction::SRem:
6134 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6135 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6136 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6137 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6138 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006139 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006140 BO->getName());
6141 InsertNewInstBefore(NewRem, ICI);
6142 return new ICmpInst(ICI.getPredicate(), NewRem,
6143 Constant::getNullValue(BO->getType()));
6144 }
6145 }
6146 break;
6147 case Instruction::Add:
6148 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6149 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6150 if (BO->hasOneUse())
6151 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6152 Subtract(RHS, BOp1C));
6153 } else if (RHSV == 0) {
6154 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6155 // efficiently invertible, or if the add has just this one use.
6156 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6157
6158 if (Value *NegVal = dyn_castNegVal(BOp1))
6159 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6160 else if (Value *NegVal = dyn_castNegVal(BOp0))
6161 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6162 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006163 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006164 InsertNewInstBefore(Neg, ICI);
6165 Neg->takeName(BO);
6166 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6167 }
6168 }
6169 break;
6170 case Instruction::Xor:
6171 // For the xor case, we can xor two constants together, eliminating
6172 // the explicit xor.
6173 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6174 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6175 ConstantExpr::getXor(RHS, BOC));
6176
6177 // FALLTHROUGH
6178 case Instruction::Sub:
6179 // Replace (([sub|xor] A, B) != 0) with (A != B)
6180 if (RHSV == 0)
6181 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6182 BO->getOperand(1));
6183 break;
6184
6185 case Instruction::Or:
6186 // If bits are being or'd in that are not present in the constant we
6187 // are comparing against, then the comparison could never succeed!
6188 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6189 Constant *NotCI = ConstantExpr::getNot(RHS);
6190 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6191 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6192 isICMP_NE));
6193 }
6194 break;
6195
6196 case Instruction::And:
6197 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6198 // If bits are being compared against that are and'd out, then the
6199 // comparison can never succeed!
6200 if ((RHSV & ~BOC->getValue()) != 0)
6201 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6202 isICMP_NE));
6203
6204 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6205 if (RHS == BOC && RHSV.isPowerOf2())
6206 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6207 ICmpInst::ICMP_NE, LHSI,
6208 Constant::getNullValue(RHS->getType()));
6209
6210 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006211 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006212 Value *X = BO->getOperand(0);
6213 Constant *Zero = Constant::getNullValue(X->getType());
6214 ICmpInst::Predicate pred = isICMP_NE ?
6215 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6216 return new ICmpInst(pred, X, Zero);
6217 }
6218
6219 // ((X & ~7) == 0) --> X < 8
6220 if (RHSV == 0 && isHighOnes(BOC)) {
6221 Value *X = BO->getOperand(0);
6222 Constant *NegX = ConstantExpr::getNeg(BOC);
6223 ICmpInst::Predicate pred = isICMP_NE ?
6224 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6225 return new ICmpInst(pred, X, NegX);
6226 }
6227 }
6228 default: break;
6229 }
6230 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6231 // Handle icmp {eq|ne} <intrinsic>, intcst.
6232 if (II->getIntrinsicID() == Intrinsic::bswap) {
6233 AddToWorkList(II);
6234 ICI.setOperand(0, II->getOperand(1));
6235 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6236 return &ICI;
6237 }
6238 }
6239 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006240 // If the LHS is a cast from an integral value of the same size,
6241 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006242 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6243 Value *CastOp = Cast->getOperand(0);
6244 const Type *SrcTy = CastOp->getType();
6245 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6246 if (SrcTy->isInteger() &&
6247 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6248 // If this is an unsigned comparison, try to make the comparison use
6249 // smaller constant values.
6250 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6251 // X u< 128 => X s> -1
6252 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6253 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6254 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6255 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6256 // X u> 127 => X s< 0
6257 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6258 Constant::getNullValue(SrcTy));
6259 }
6260 }
6261 }
6262 }
6263 return 0;
6264}
6265
6266/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6267/// We only handle extending casts so far.
6268///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006269Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6270 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006271 Value *LHSCIOp = LHSCI->getOperand(0);
6272 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006273 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006274 Value *RHSCIOp;
6275
Chris Lattner8c756c12007-05-05 22:41:33 +00006276 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6277 // integer type is the same size as the pointer type.
6278 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6279 getTargetData().getPointerSizeInBits() ==
6280 cast<IntegerType>(DestTy)->getBitWidth()) {
6281 Value *RHSOp = 0;
6282 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006283 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006284 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6285 RHSOp = RHSC->getOperand(0);
6286 // If the pointer types don't match, insert a bitcast.
6287 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006288 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006289 }
6290
6291 if (RHSOp)
6292 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6293 }
6294
6295 // The code below only handles extension cast instructions, so far.
6296 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006297 if (LHSCI->getOpcode() != Instruction::ZExt &&
6298 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006299 return 0;
6300
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6302 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006303
Reid Spencere4d87aa2006-12-23 06:05:41 +00006304 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006305 // Not an extension from the same type?
6306 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006307 if (RHSCIOp->getType() != LHSCIOp->getType())
6308 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006309
Nick Lewycky4189a532008-01-28 03:48:02 +00006310 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006311 // and the other is a zext), then we can't handle this.
6312 if (CI->getOpcode() != LHSCI->getOpcode())
6313 return 0;
6314
Nick Lewycky4189a532008-01-28 03:48:02 +00006315 // Deal with equality cases early.
6316 if (ICI.isEquality())
6317 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6318
6319 // A signed comparison of sign extended values simplifies into a
6320 // signed comparison.
6321 if (isSignedCmp && isSignedExt)
6322 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6323
6324 // The other three cases all fold into an unsigned comparison.
6325 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006326 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006327
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 // If we aren't dealing with a constant on the RHS, exit early
6329 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6330 if (!CI)
6331 return 0;
6332
6333 // Compute the constant that would happen if we truncated to SrcTy then
6334 // reextended to DestTy.
6335 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6336 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6337
6338 // If the re-extended constant didn't change...
6339 if (Res2 == CI) {
6340 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6341 // For example, we might have:
6342 // %A = sext short %X to uint
6343 // %B = icmp ugt uint %A, 1330
6344 // It is incorrect to transform this into
6345 // %B = icmp ugt short %X, 1330
6346 // because %A may have negative value.
6347 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006348 // However, we allow this when the compare is EQ/NE, because they are
6349 // signless.
6350 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006351 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006352 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006353 }
6354
6355 // The re-extended constant changed so the constant cannot be represented
6356 // in the shorter type. Consequently, we cannot emit a simple comparison.
6357
6358 // First, handle some easy cases. We know the result cannot be equal at this
6359 // point so handle the ICI.isEquality() cases
6360 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006361 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006362 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006363 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006364
6365 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6366 // should have been folded away previously and not enter in here.
6367 Value *Result;
6368 if (isSignedCmp) {
6369 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006370 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006371 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006372 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006373 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006374 } else {
6375 // We're performing an unsigned comparison.
6376 if (isSignedExt) {
6377 // We're performing an unsigned comp with a sign extended value.
6378 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006379 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006380 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6381 NegOne, ICI.getName()), ICI);
6382 } else {
6383 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006384 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006385 }
6386 }
6387
6388 // Finally, return the value computed.
6389 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006390 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006392
6393 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6394 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6395 "ICmp should be folded!");
6396 if (Constant *CI = dyn_cast<Constant>(Result))
6397 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6398 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006399}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006400
Reid Spencer832254e2007-02-02 02:16:23 +00006401Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6402 return commonShiftTransforms(I);
6403}
6404
6405Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6406 return commonShiftTransforms(I);
6407}
6408
6409Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006410 if (Instruction *R = commonShiftTransforms(I))
6411 return R;
6412
6413 Value *Op0 = I.getOperand(0);
6414
6415 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6416 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6417 if (CSI->isAllOnesValue())
6418 return ReplaceInstUsesWith(I, CSI);
6419
6420 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00006421 if (!isa<VectorType>(I.getType()) &&
6422 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00006423 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006424 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006425
6426 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006427}
6428
6429Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6430 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006431 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006432
6433 // shl X, 0 == X and shr X, 0 == X
6434 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006435 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006436 Op0 == Constant::getNullValue(Op0->getType()))
6437 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006438
Reid Spencere4d87aa2006-12-23 06:05:41 +00006439 if (isa<UndefValue>(Op0)) {
6440 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006441 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006442 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006443 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6444 }
6445 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006446 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6447 return ReplaceInstUsesWith(I, Op0);
6448 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006449 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006450 }
6451
Chris Lattner2eefe512004-04-09 19:05:30 +00006452 // Try to fold constant and into select arguments.
6453 if (isa<Constant>(Op0))
6454 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006455 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006456 return R;
6457
Reid Spencerb83eb642006-10-20 07:07:24 +00006458 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006459 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6460 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006461 return 0;
6462}
6463
Reid Spencerb83eb642006-10-20 07:07:24 +00006464Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006465 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006466 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006467
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006468 // See if we can simplify any instructions used by the instruction whose sole
6469 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006470 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6471 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6472 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006473 KnownZero, KnownOne))
6474 return &I;
6475
Chris Lattner4d5542c2006-01-06 07:12:35 +00006476 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6477 // of a signed value.
6478 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006479 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006480 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006481 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6482 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006483 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006484 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006485 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006486 }
6487
6488 // ((X*C1) << C2) == (X * (C1 << C2))
6489 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6490 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6491 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006492 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006493 ConstantExpr::getShl(BOOp, Op1));
6494
6495 // Try to fold constant and into select arguments.
6496 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6497 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6498 return R;
6499 if (isa<PHINode>(Op0))
6500 if (Instruction *NV = FoldOpIntoPhi(I))
6501 return NV;
6502
Chris Lattner8999dd32007-12-22 09:07:47 +00006503 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6504 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6505 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6506 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6507 // place. Don't try to do this transformation in this case. Also, we
6508 // require that the input operand is a shift-by-constant so that we have
6509 // confidence that the shifts will get folded together. We could do this
6510 // xform in more cases, but it is unlikely to be profitable.
6511 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6512 isa<ConstantInt>(TrOp->getOperand(1))) {
6513 // Okay, we'll do this xform. Make the shift of shift.
6514 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006515 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006516 I.getName());
6517 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6518
6519 // For logical shifts, the truncation has the effect of making the high
6520 // part of the register be zeros. Emulate this by inserting an AND to
6521 // clear the top bits as needed. This 'and' will usually be zapped by
6522 // other xforms later if dead.
6523 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6524 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6525 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6526
6527 // The mask we constructed says what the trunc would do if occurring
6528 // between the shifts. We want to know the effect *after* the second
6529 // shift. We know that it is a logical shift by a constant, so adjust the
6530 // mask as appropriate.
6531 if (I.getOpcode() == Instruction::Shl)
6532 MaskV <<= Op1->getZExtValue();
6533 else {
6534 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6535 MaskV = MaskV.lshr(Op1->getZExtValue());
6536 }
6537
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006538 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006539 TI->getName());
6540 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6541
6542 // Return the value truncated to the interesting size.
6543 return new TruncInst(And, I.getType());
6544 }
6545 }
6546
Chris Lattner4d5542c2006-01-06 07:12:35 +00006547 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006548 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6549 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6550 Value *V1, *V2;
6551 ConstantInt *CC;
6552 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006553 default: break;
6554 case Instruction::Add:
6555 case Instruction::And:
6556 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006557 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006558 // These operators commute.
6559 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006560 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6561 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006562 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006563 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006564 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006565 Op0BO->getName());
6566 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006567 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006568 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006569 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006570 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006571 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006572 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006573 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006574 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006575
Chris Lattner150f12a2005-09-18 06:30:59 +00006576 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006577 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006578 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006579 match(Op0BOOp1,
6580 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006581 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6582 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006583 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006584 Op0BO->getOperand(0), Op1,
6585 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006586 InsertNewInstBefore(YS, I); // (Y << C)
6587 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006588 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006589 V1->getName()+".mask");
6590 InsertNewInstBefore(XM, I); // X & (CC << C)
6591
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006592 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006593 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006594 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006595
Reid Spencera07cb7d2007-02-02 14:41:37 +00006596 // FALL THROUGH.
6597 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006598 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006599 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6600 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006601 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006602 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006603 Op0BO->getOperand(1), Op1,
6604 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006605 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006606 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006607 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006608 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006609 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006610 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006611 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006612 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006613 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006614
Chris Lattner13d4ab42006-05-31 21:14:00 +00006615 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006616 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6617 match(Op0BO->getOperand(0),
6618 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006619 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006620 cast<BinaryOperator>(Op0BO->getOperand(0))
6621 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006622 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006623 Op0BO->getOperand(1), Op1,
6624 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006625 InsertNewInstBefore(YS, I); // (Y << C)
6626 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006627 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006628 V1->getName()+".mask");
6629 InsertNewInstBefore(XM, I); // X & (CC << C)
6630
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006631 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006632 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006633
Chris Lattner11021cb2005-09-18 05:12:10 +00006634 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006635 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006636 }
6637
6638
6639 // If the operand is an bitwise operator with a constant RHS, and the
6640 // shift is the only use, we can pull it out of the shift.
6641 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6642 bool isValid = true; // Valid only for And, Or, Xor
6643 bool highBitSet = false; // Transform if high bit of constant set?
6644
6645 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006646 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006647 case Instruction::Add:
6648 isValid = isLeftShift;
6649 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006650 case Instruction::Or:
6651 case Instruction::Xor:
6652 highBitSet = false;
6653 break;
6654 case Instruction::And:
6655 highBitSet = true;
6656 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006657 }
6658
6659 // If this is a signed shift right, and the high bit is modified
6660 // by the logical operation, do not perform the transformation.
6661 // The highBitSet boolean indicates the value of the high bit of
6662 // the constant which would cause it to be modified for this
6663 // operation.
6664 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006665 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006666 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006667
6668 if (isValid) {
6669 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6670
6671 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006672 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006673 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006674 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006675
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006676 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006677 NewRHS);
6678 }
6679 }
6680 }
6681 }
6682
Chris Lattnerad0124c2006-01-06 07:52:12 +00006683 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006684 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6685 if (ShiftOp && !ShiftOp->isShift())
6686 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006687
Reid Spencerb83eb642006-10-20 07:07:24 +00006688 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006689 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006690 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6691 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006692 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6693 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6694 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006695
Zhou Sheng4351c642007-04-02 08:20:41 +00006696 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006697 if (AmtSum > TypeBits)
6698 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006699
6700 const IntegerType *Ty = cast<IntegerType>(I.getType());
6701
6702 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006703 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006704 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006705 ConstantInt::get(Ty, AmtSum));
6706 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6707 I.getOpcode() == Instruction::AShr) {
6708 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006709 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006710 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6711 I.getOpcode() == Instruction::LShr) {
6712 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6713 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006714 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006715 InsertNewInstBefore(Shift, I);
6716
Zhou Shenge9e03f62007-03-28 15:02:20 +00006717 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006718 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006719 }
6720
Chris Lattnerb87056f2007-02-05 00:57:54 +00006721 // Okay, if we get here, one shift must be left, and the other shift must be
6722 // right. See if the amounts are equal.
6723 if (ShiftAmt1 == ShiftAmt2) {
6724 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6725 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006726 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006727 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006728 }
6729 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6730 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006731 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006732 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006733 }
6734 // We can simplify ((X << C) >>s C) into a trunc + sext.
6735 // NOTE: we could do this for any C, but that would make 'unusual' integer
6736 // types. For now, just stick to ones well-supported by the code
6737 // generators.
6738 const Type *SExtType = 0;
6739 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006740 case 1 :
6741 case 8 :
6742 case 16 :
6743 case 32 :
6744 case 64 :
6745 case 128:
6746 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6747 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006748 default: break;
6749 }
6750 if (SExtType) {
6751 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6752 InsertNewInstBefore(NewTrunc, I);
6753 return new SExtInst(NewTrunc, Ty);
6754 }
6755 // Otherwise, we can't handle it yet.
6756 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006757 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006758
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006759 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006760 if (I.getOpcode() == Instruction::Shl) {
6761 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6762 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006763 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006764 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006765 InsertNewInstBefore(Shift, I);
6766
Reid Spencer55702aa2007-03-25 21:11:44 +00006767 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006768 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006769 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006770
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006771 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006772 if (I.getOpcode() == Instruction::LShr) {
6773 assert(ShiftOp->getOpcode() == Instruction::Shl);
6774 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006775 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006776 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006777
Reid Spencerd5e30f02007-03-26 17:18:58 +00006778 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006779 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006780 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006781
6782 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6783 } else {
6784 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006785 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006786
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006787 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006788 if (I.getOpcode() == Instruction::Shl) {
6789 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6790 ShiftOp->getOpcode() == Instruction::AShr);
6791 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006792 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006793 ConstantInt::get(Ty, ShiftDiff));
6794 InsertNewInstBefore(Shift, I);
6795
Reid Spencer55702aa2007-03-25 21:11:44 +00006796 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006797 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006798 }
6799
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006800 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006801 if (I.getOpcode() == Instruction::LShr) {
6802 assert(ShiftOp->getOpcode() == Instruction::Shl);
6803 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006804 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006805 InsertNewInstBefore(Shift, I);
6806
Reid Spencer68d27cf2007-03-26 23:45:51 +00006807 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006808 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006809 }
6810
6811 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006812 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006813 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006814 return 0;
6815}
6816
Chris Lattnera1be5662002-05-02 17:06:02 +00006817
Chris Lattnercfd65102005-10-29 04:36:15 +00006818/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6819/// expression. If so, decompose it, returning some value X, such that Val is
6820/// X*Scale+Offset.
6821///
6822static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006823 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006824 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006825 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006826 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006827 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006828 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006829 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6830 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6831 if (I->getOpcode() == Instruction::Shl) {
6832 // This is a value scaled by '1 << the shift amt'.
6833 Scale = 1U << RHS->getZExtValue();
6834 Offset = 0;
6835 return I->getOperand(0);
6836 } else if (I->getOpcode() == Instruction::Mul) {
6837 // This value is scaled by 'RHS'.
6838 Scale = RHS->getZExtValue();
6839 Offset = 0;
6840 return I->getOperand(0);
6841 } else if (I->getOpcode() == Instruction::Add) {
6842 // We have X+C. Check to see if we really have (X*C2)+C1,
6843 // where C1 is divisible by C2.
6844 unsigned SubScale;
6845 Value *SubVal =
6846 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6847 Offset += RHS->getZExtValue();
6848 Scale = SubScale;
6849 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006850 }
6851 }
6852 }
6853
6854 // Otherwise, we can't look past this.
6855 Scale = 1;
6856 Offset = 0;
6857 return Val;
6858}
6859
6860
Chris Lattnerb3f83972005-10-24 06:03:58 +00006861/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6862/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006863Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006864 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006865 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006866
Chris Lattnerb53c2382005-10-24 06:22:12 +00006867 // Remove any uses of AI that are dead.
6868 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006869
Chris Lattnerb53c2382005-10-24 06:22:12 +00006870 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6871 Instruction *User = cast<Instruction>(*UI++);
6872 if (isInstructionTriviallyDead(User)) {
6873 while (UI != E && *UI == User)
6874 ++UI; // If this instruction uses AI more than once, don't break UI.
6875
Chris Lattnerb53c2382005-10-24 06:22:12 +00006876 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006877 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006878 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006879 }
6880 }
6881
Chris Lattnerb3f83972005-10-24 06:03:58 +00006882 // Get the type really allocated and the type casted to.
6883 const Type *AllocElTy = AI.getAllocatedType();
6884 const Type *CastElTy = PTy->getElementType();
6885 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006886
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006887 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6888 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006889 if (CastElTyAlign < AllocElTyAlign) return 0;
6890
Chris Lattner39387a52005-10-24 06:35:18 +00006891 // If the allocation has multiple uses, only promote it if we are strictly
6892 // increasing the alignment of the resultant allocation. If we keep it the
6893 // same, we open the door to infinite loops of various kinds.
6894 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6895
Duncan Sands514ab342007-11-01 20:53:16 +00006896 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6897 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006898 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006899
Chris Lattner455fcc82005-10-29 03:19:53 +00006900 // See if we can satisfy the modulus by pulling a scale out of the array
6901 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006902 unsigned ArraySizeScale;
6903 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006904 Value *NumElements = // See if the array size is a decomposable linear expr.
6905 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6906
Chris Lattner455fcc82005-10-29 03:19:53 +00006907 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6908 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006909 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6910 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006911
Chris Lattner455fcc82005-10-29 03:19:53 +00006912 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6913 Value *Amt = 0;
6914 if (Scale == 1) {
6915 Amt = NumElements;
6916 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006917 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006918 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6919 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006920 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006921 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006922 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006923 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006924 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006925 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006926 }
6927
Jeff Cohen86796be2007-04-04 16:58:57 +00006928 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6929 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006930 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006931 Amt = InsertNewInstBefore(Tmp, AI);
6932 }
6933
Chris Lattnerb3f83972005-10-24 06:03:58 +00006934 AllocationInst *New;
6935 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006936 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006937 else
Chris Lattner6934a042007-02-11 01:23:03 +00006938 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006939 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006940 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006941
6942 // If the allocation has multiple uses, insert a cast and change all things
6943 // that used it to use the new cast. This will also hack on CI, but it will
6944 // die soon.
6945 if (!AI.hasOneUse()) {
6946 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006947 // New is the allocation instruction, pointer typed. AI is the original
6948 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6949 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006950 InsertNewInstBefore(NewCast, AI);
6951 AI.replaceAllUsesWith(NewCast);
6952 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006953 return ReplaceInstUsesWith(CI, New);
6954}
6955
Chris Lattner70074e02006-05-13 02:06:03 +00006956/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006957/// and return it as type Ty without inserting any new casts and without
6958/// changing the computed value. This is used by code that tries to decide
6959/// whether promoting or shrinking integer operations to wider or smaller types
6960/// will allow us to eliminate a truncate or extend.
6961///
6962/// This is a truncation operation if Ty is smaller than V->getType(), or an
6963/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00006964///
6965/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6966/// should return true if trunc(V) can be computed by computing V in the smaller
6967/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6968/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6969/// efficiently truncated.
6970///
6971/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6972/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6973/// the final result.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006974bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6975 unsigned CastOpc,
6976 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006977 // We can always evaluate constants in another type.
6978 if (isa<ConstantInt>(V))
6979 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006980
6981 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006982 if (!I) return false;
6983
6984 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006985
Chris Lattner951626b2007-08-02 06:11:14 +00006986 // If this is an extension or truncate, we can often eliminate it.
6987 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6988 // If this is a cast from the destination type, we can trivially eliminate
6989 // it, and this will remove a cast overall.
6990 if (I->getOperand(0)->getType() == Ty) {
6991 // If the first operand is itself a cast, and is eliminable, do not count
6992 // this as an eliminable cast. We would prefer to eliminate those two
6993 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00006994 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00006995 ++NumCastsRemoved;
6996 return true;
6997 }
6998 }
6999
7000 // We can't extend or shrink something that has multiple uses: doing so would
7001 // require duplicating the instruction in general, which isn't profitable.
7002 if (!I->hasOneUse()) return false;
7003
Chris Lattner70074e02006-05-13 02:06:03 +00007004 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007005 case Instruction::Add:
7006 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007007 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007008 case Instruction::And:
7009 case Instruction::Or:
7010 case Instruction::Xor:
7011 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007012 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7013 NumCastsRemoved) &&
7014 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7015 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007016
Chris Lattner46b96052006-11-29 07:18:39 +00007017 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007018 // If we are truncating the result of this SHL, and if it's a shift of a
7019 // constant amount, we can always perform a SHL in a smaller type.
7020 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007021 uint32_t BitWidth = Ty->getBitWidth();
7022 if (BitWidth < OrigTy->getBitWidth() &&
7023 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007024 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7025 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007026 }
7027 break;
7028 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007029 // If this is a truncate of a logical shr, we can truncate it to a smaller
7030 // lshr iff we know that the bits we would otherwise be shifting in are
7031 // already zeros.
7032 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007033 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7034 uint32_t BitWidth = Ty->getBitWidth();
7035 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007036 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007037 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7038 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007039 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7040 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007041 }
7042 }
Chris Lattner46b96052006-11-29 07:18:39 +00007043 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007044 case Instruction::ZExt:
7045 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007046 case Instruction::Trunc:
7047 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007048 // can safely replace it. Note that replacing it does not reduce the number
7049 // of casts in the input.
7050 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007051 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007052 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007053 case Instruction::Select: {
7054 SelectInst *SI = cast<SelectInst>(I);
7055 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7056 NumCastsRemoved) &&
7057 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7058 NumCastsRemoved);
7059 }
Chris Lattner8114b712008-06-18 04:00:49 +00007060 case Instruction::PHI: {
7061 // We can change a phi if we can change all operands.
7062 PHINode *PN = cast<PHINode>(I);
7063 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7064 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7065 NumCastsRemoved))
7066 return false;
7067 return true;
7068 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007069 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007070 // TODO: Can handle more cases here.
7071 break;
7072 }
7073
7074 return false;
7075}
7076
7077/// EvaluateInDifferentType - Given an expression that
7078/// CanEvaluateInDifferentType returns true for, actually insert the code to
7079/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007080Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007081 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007082 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007083 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007084
7085 // Otherwise, it must be an instruction.
7086 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007087 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007088 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007089 case Instruction::Add:
7090 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007091 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007092 case Instruction::And:
7093 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007094 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007095 case Instruction::AShr:
7096 case Instruction::LShr:
7097 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007098 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007099 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007100 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner8114b712008-06-18 04:00:49 +00007101 LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007102 break;
7103 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007104 case Instruction::Trunc:
7105 case Instruction::ZExt:
7106 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007107 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007108 // just return the source. There's no need to insert it because it is not
7109 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007110 if (I->getOperand(0)->getType() == Ty)
7111 return I->getOperand(0);
7112
Chris Lattner8114b712008-06-18 04:00:49 +00007113 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007114 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007115 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007116 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007117 case Instruction::Select: {
7118 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7119 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7120 Res = SelectInst::Create(I->getOperand(0), True, False);
7121 break;
7122 }
Chris Lattner8114b712008-06-18 04:00:49 +00007123 case Instruction::PHI: {
7124 PHINode *OPN = cast<PHINode>(I);
7125 PHINode *NPN = PHINode::Create(Ty);
7126 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7127 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7128 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7129 }
7130 Res = NPN;
7131 break;
7132 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007133 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007134 // TODO: Can handle more cases here.
7135 assert(0 && "Unreachable!");
7136 break;
7137 }
7138
Chris Lattner8114b712008-06-18 04:00:49 +00007139 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007140 return InsertNewInstBefore(Res, *I);
7141}
7142
Reid Spencer3da59db2006-11-27 01:05:10 +00007143/// @brief Implement the transforms common to all CastInst visitors.
7144Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007145 Value *Src = CI.getOperand(0);
7146
Dan Gohman23d9d272007-05-11 21:10:54 +00007147 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007148 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007149 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007150 if (Instruction::CastOps opc =
7151 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7152 // The first cast (CSrc) is eliminable so we need to fix up or replace
7153 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007154 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007155 }
7156 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007157
Reid Spencer3da59db2006-11-27 01:05:10 +00007158 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007159 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7160 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7161 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007162
7163 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007164 if (isa<PHINode>(Src))
7165 if (Instruction *NV = FoldOpIntoPhi(CI))
7166 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007167
Reid Spencer3da59db2006-11-27 01:05:10 +00007168 return 0;
7169}
7170
Chris Lattnerd3e28342007-04-27 17:44:50 +00007171/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7172Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7173 Value *Src = CI.getOperand(0);
7174
Chris Lattnerd3e28342007-04-27 17:44:50 +00007175 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007176 // If casting the result of a getelementptr instruction with no offset, turn
7177 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007178 if (GEP->hasAllZeroIndices()) {
7179 // Changing the cast operand is usually not a good idea but it is safe
7180 // here because the pointer operand is being replaced with another
7181 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007182 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007183 CI.setOperand(0, GEP->getOperand(0));
7184 return &CI;
7185 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007186
7187 // If the GEP has a single use, and the base pointer is a bitcast, and the
7188 // GEP computes a constant offset, see if we can convert these three
7189 // instructions into fewer. This typically happens with unions and other
7190 // non-type-safe code.
7191 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7192 if (GEP->hasAllConstantIndices()) {
7193 // We are guaranteed to get a constant from EmitGEPOffset.
7194 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7195 int64_t Offset = OffsetV->getSExtValue();
7196
7197 // Get the base pointer input of the bitcast, and the type it points to.
7198 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7199 const Type *GEPIdxTy =
7200 cast<PointerType>(OrigBase->getType())->getElementType();
7201 if (GEPIdxTy->isSized()) {
7202 SmallVector<Value*, 8> NewIndices;
7203
Chris Lattnerc42e2262007-05-05 01:59:31 +00007204 // Start with the index over the outer type. Note that the type size
7205 // might be zero (even if the offset isn't zero) if the indexed type
7206 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007207 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007208 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007209 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007210 FirstIdx = Offset/TySize;
7211 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007212
Chris Lattnerc42e2262007-05-05 01:59:31 +00007213 // Handle silly modulus not returning values values [0..TySize).
7214 if (Offset < 0) {
7215 --FirstIdx;
7216 Offset += TySize;
7217 assert(Offset >= 0);
7218 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007219 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007220 }
7221
7222 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007223
7224 // Index into the types. If we fail, set OrigBase to null.
7225 while (Offset) {
7226 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7227 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007228 if (Offset < (int64_t)SL->getSizeInBytes()) {
7229 unsigned Elt = SL->getElementContainingOffset(Offset);
7230 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007231
Chris Lattner6b6aef82007-05-15 00:16:00 +00007232 Offset -= SL->getElementOffset(Elt);
7233 GEPIdxTy = STy->getElementType(Elt);
7234 } else {
7235 // Otherwise, we can't index into this, bail out.
7236 Offset = 0;
7237 OrigBase = 0;
7238 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007239 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7240 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007241 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007242 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7243 Offset %= EltSize;
7244 } else {
7245 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7246 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007247 GEPIdxTy = STy->getElementType();
7248 } else {
7249 // Otherwise, we can't index into this, bail out.
7250 Offset = 0;
7251 OrigBase = 0;
7252 }
7253 }
7254 if (OrigBase) {
7255 // If we were able to index down into an element, create the GEP
7256 // and bitcast the result. This eliminates one bitcast, potentially
7257 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007258 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7259 NewIndices.begin(),
7260 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007261 InsertNewInstBefore(NGEP, CI);
7262 NGEP->takeName(GEP);
7263
Chris Lattner9bc14642007-04-28 00:57:34 +00007264 if (isa<BitCastInst>(CI))
7265 return new BitCastInst(NGEP, CI.getType());
7266 assert(isa<PtrToIntInst>(CI));
7267 return new PtrToIntInst(NGEP, CI.getType());
7268 }
7269 }
7270 }
7271 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007272 }
7273
7274 return commonCastTransforms(CI);
7275}
7276
7277
7278
Chris Lattnerc739cd62007-03-03 05:27:34 +00007279/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7280/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007281/// cases.
7282/// @brief Implement the transforms common to CastInst with integer operands
7283Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7284 if (Instruction *Result = commonCastTransforms(CI))
7285 return Result;
7286
7287 Value *Src = CI.getOperand(0);
7288 const Type *SrcTy = Src->getType();
7289 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007290 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7291 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007292
Reid Spencer3da59db2006-11-27 01:05:10 +00007293 // See if we can simplify any instructions used by the LHS whose sole
7294 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007295 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7296 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007297 KnownZero, KnownOne))
7298 return &CI;
7299
7300 // If the source isn't an instruction or has more than one use then we
7301 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007302 Instruction *SrcI = dyn_cast<Instruction>(Src);
7303 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007304 return 0;
7305
Chris Lattnerc739cd62007-03-03 05:27:34 +00007306 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007307 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007308 if (!isa<BitCastInst>(CI) &&
7309 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007310 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007311 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007312 // eliminates the cast, so it is always a win. If this is a zero-extension,
7313 // we need to do an AND to maintain the clear top-part of the computation,
7314 // so we require that the input have eliminated at least one cast. If this
7315 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007316 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007317 bool DoXForm;
7318 switch (CI.getOpcode()) {
7319 default:
7320 // All the others use floating point so we shouldn't actually
7321 // get here because of the check above.
7322 assert(0 && "Unknown cast type");
7323 case Instruction::Trunc:
7324 DoXForm = true;
7325 break;
7326 case Instruction::ZExt:
7327 DoXForm = NumCastsRemoved >= 1;
7328 break;
7329 case Instruction::SExt:
7330 DoXForm = NumCastsRemoved >= 2;
7331 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007332 }
7333
7334 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007335 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7336 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007337 assert(Res->getType() == DestTy);
7338 switch (CI.getOpcode()) {
7339 default: assert(0 && "Unknown cast type!");
7340 case Instruction::Trunc:
7341 case Instruction::BitCast:
7342 // Just replace this cast with the result.
7343 return ReplaceInstUsesWith(CI, Res);
7344 case Instruction::ZExt: {
7345 // We need to emit an AND to clear the high bits.
7346 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007347 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7348 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007349 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007350 }
7351 case Instruction::SExt:
7352 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007353 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007354 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7355 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007356 }
7357 }
7358 }
7359
7360 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7361 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7362
7363 switch (SrcI->getOpcode()) {
7364 case Instruction::Add:
7365 case Instruction::Mul:
7366 case Instruction::And:
7367 case Instruction::Or:
7368 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007369 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007370 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7371 // Don't insert two casts if they cannot be eliminated. We allow
7372 // two casts to be inserted if the sizes are the same. This could
7373 // only be converting signedness, which is a noop.
7374 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007375 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7376 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007377 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007378 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7379 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007380 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007381 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007382 }
7383 }
7384
7385 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7386 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7387 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007388 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007389 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007390 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007391 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007392 }
7393 break;
7394 case Instruction::SDiv:
7395 case Instruction::UDiv:
7396 case Instruction::SRem:
7397 case Instruction::URem:
7398 // If we are just changing the sign, rewrite.
7399 if (DestBitSize == SrcBitSize) {
7400 // Don't insert two casts if they cannot be eliminated. We allow
7401 // two casts to be inserted if the sizes are the same. This could
7402 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007403 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7404 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007405 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7406 Op0, DestTy, SrcI);
7407 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7408 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007409 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007410 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7411 }
7412 }
7413 break;
7414
7415 case Instruction::Shl:
7416 // Allow changing the sign of the source operand. Do not allow
7417 // changing the size of the shift, UNLESS the shift amount is a
7418 // constant. We must not change variable sized shifts to a smaller
7419 // size, because it is undefined to shift more bits out than exist
7420 // in the value.
7421 if (DestBitSize == SrcBitSize ||
7422 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007423 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7424 Instruction::BitCast : Instruction::Trunc);
7425 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007426 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007427 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007428 }
7429 break;
7430 case Instruction::AShr:
7431 // If this is a signed shr, and if all bits shifted in are about to be
7432 // truncated off, turn it into an unsigned shr to allow greater
7433 // simplifications.
7434 if (DestBitSize < SrcBitSize &&
7435 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007436 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007437 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7438 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007439 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007440 }
7441 }
7442 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007443 }
7444 return 0;
7445}
7446
Chris Lattner8a9f5712007-04-11 06:57:46 +00007447Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007448 if (Instruction *Result = commonIntCastTransforms(CI))
7449 return Result;
7450
7451 Value *Src = CI.getOperand(0);
7452 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007453 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7454 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007455
7456 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7457 switch (SrcI->getOpcode()) {
7458 default: break;
7459 case Instruction::LShr:
7460 // We can shrink lshr to something smaller if we know the bits shifted in
7461 // are already zeros.
7462 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007463 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007464
7465 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007466 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007467 Value* SrcIOp0 = SrcI->getOperand(0);
7468 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007469 if (ShAmt >= DestBitWidth) // All zeros.
7470 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7471
7472 // Okay, we can shrink this. Truncate the input, then return a new
7473 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007474 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7475 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7476 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007477 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007478 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007479 } else { // This is a variable shr.
7480
7481 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7482 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7483 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007484 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007485 Value *One = ConstantInt::get(SrcI->getType(), 1);
7486
Reid Spencer832254e2007-02-02 02:16:23 +00007487 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007488 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007489 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007490 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007491 SrcI->getOperand(0),
7492 "tmp"), CI);
7493 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007494 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007495 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007496 }
7497 break;
7498 }
7499 }
7500
7501 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007502}
7503
Evan Chengb98a10e2008-03-24 00:21:34 +00007504/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7505/// in order to eliminate the icmp.
7506Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7507 bool DoXform) {
7508 // If we are just checking for a icmp eq of a single bit and zext'ing it
7509 // to an integer, then shift the bit to the appropriate place and then
7510 // cast to integer to avoid the comparison.
7511 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7512 const APInt &Op1CV = Op1C->getValue();
7513
7514 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7515 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7516 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7517 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7518 if (!DoXform) return ICI;
7519
7520 Value *In = ICI->getOperand(0);
7521 Value *Sh = ConstantInt::get(In->getType(),
7522 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007523 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007524 In->getName()+".lobit"),
7525 CI);
7526 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007527 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007528 false/*ZExt*/, "tmp", &CI);
7529
7530 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7531 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007532 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007533 In->getName()+".not"),
7534 CI);
7535 }
7536
7537 return ReplaceInstUsesWith(CI, In);
7538 }
7539
7540
7541
7542 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7543 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7544 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7545 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7546 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7547 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7548 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7549 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7550 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7551 // This only works for EQ and NE
7552 ICI->isEquality()) {
7553 // If Op1C some other power of two, convert:
7554 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7555 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7556 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7557 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7558
7559 APInt KnownZeroMask(~KnownZero);
7560 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7561 if (!DoXform) return ICI;
7562
7563 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7564 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7565 // (X&4) == 2 --> false
7566 // (X&4) != 2 --> true
7567 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7568 Res = ConstantExpr::getZExt(Res, CI.getType());
7569 return ReplaceInstUsesWith(CI, Res);
7570 }
7571
7572 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7573 Value *In = ICI->getOperand(0);
7574 if (ShiftAmt) {
7575 // Perform a logical shr by shiftamt.
7576 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007577 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007578 ConstantInt::get(In->getType(), ShiftAmt),
7579 In->getName()+".lobit"), CI);
7580 }
7581
7582 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7583 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007584 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007585 InsertNewInstBefore(cast<Instruction>(In), CI);
7586 }
7587
7588 if (CI.getType() == In->getType())
7589 return ReplaceInstUsesWith(CI, In);
7590 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007591 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007592 }
7593 }
7594 }
7595
7596 return 0;
7597}
7598
Chris Lattner8a9f5712007-04-11 06:57:46 +00007599Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007600 // If one of the common conversion will work ..
7601 if (Instruction *Result = commonIntCastTransforms(CI))
7602 return Result;
7603
7604 Value *Src = CI.getOperand(0);
7605
7606 // If this is a cast of a cast
7607 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007608 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7609 // types and if the sizes are just right we can convert this into a logical
7610 // 'and' which will be much cheaper than the pair of casts.
7611 if (isa<TruncInst>(CSrc)) {
7612 // Get the sizes of the types involved
7613 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007614 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7615 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7616 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007617 // If we're actually extending zero bits and the trunc is a no-op
7618 if (MidSize < DstSize && SrcSize == DstSize) {
7619 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007620 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007621 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007622 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007623 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007624 // Unfortunately, if the type changed, we need to cast it back.
7625 if (And->getType() != CI.getType()) {
7626 And->setName(CSrc->getName()+".mask");
7627 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007628 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007629 }
7630 return And;
7631 }
7632 }
7633 }
7634
Evan Chengb98a10e2008-03-24 00:21:34 +00007635 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7636 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007637
Evan Chengb98a10e2008-03-24 00:21:34 +00007638 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7639 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7640 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7641 // of the (zext icmp) will be transformed.
7642 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7643 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7644 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7645 (transformZExtICmp(LHS, CI, false) ||
7646 transformZExtICmp(RHS, CI, false))) {
7647 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7648 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007649 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007650 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007651 }
7652
Reid Spencer3da59db2006-11-27 01:05:10 +00007653 return 0;
7654}
7655
Chris Lattner8a9f5712007-04-11 06:57:46 +00007656Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007657 if (Instruction *I = commonIntCastTransforms(CI))
7658 return I;
7659
Chris Lattner8a9f5712007-04-11 06:57:46 +00007660 Value *Src = CI.getOperand(0);
7661
7662 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7663 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7664 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7665 // If we are just checking for a icmp eq of a single bit and zext'ing it
7666 // to an integer, then shift the bit to the appropriate place and then
7667 // cast to integer to avoid the comparison.
7668 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7669 const APInt &Op1CV = Op1C->getValue();
7670
7671 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7672 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7673 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7674 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7675 Value *In = ICI->getOperand(0);
7676 Value *Sh = ConstantInt::get(In->getType(),
7677 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007678 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007679 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007680 CI);
7681 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007682 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007683 true/*SExt*/, "tmp", &CI);
7684
7685 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007686 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007687 In->getName()+".not"), CI);
7688
7689 return ReplaceInstUsesWith(CI, In);
7690 }
7691 }
7692 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007693
7694 // See if the value being truncated is already sign extended. If so, just
7695 // eliminate the trunc/sext pair.
7696 if (getOpcode(Src) == Instruction::Trunc) {
7697 Value *Op = cast<User>(Src)->getOperand(0);
7698 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7699 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7700 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7701 unsigned NumSignBits = ComputeNumSignBits(Op);
7702
7703 if (OpBits == DestBits) {
7704 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7705 // bits, it is already ready.
7706 if (NumSignBits > DestBits-MidBits)
7707 return ReplaceInstUsesWith(CI, Op);
7708 } else if (OpBits < DestBits) {
7709 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7710 // bits, just sext from i32.
7711 if (NumSignBits > OpBits-MidBits)
7712 return new SExtInst(Op, CI.getType(), "tmp");
7713 } else {
7714 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7715 // bits, just truncate to i32.
7716 if (NumSignBits > OpBits-MidBits)
7717 return new TruncInst(Op, CI.getType(), "tmp");
7718 }
7719 }
Chris Lattner46bbad22008-08-06 07:35:52 +00007720
7721 // If the input is a shl/ashr pair of a same constant, then this is a sign
7722 // extension from a smaller value. If we could trust arbitrary bitwidth
7723 // integers, we could turn this into a truncate to the smaller bit and then
7724 // use a sext for the whole extension. Since we don't, look deeper and check
7725 // for a truncate. If the source and dest are the same type, eliminate the
7726 // trunc and extend and just do shifts. For example, turn:
7727 // %a = trunc i32 %i to i8
7728 // %b = shl i8 %a, 6
7729 // %c = ashr i8 %b, 6
7730 // %d = sext i8 %c to i32
7731 // into:
7732 // %a = shl i32 %i, 30
7733 // %d = ashr i32 %a, 30
7734 Value *A = 0;
7735 ConstantInt *BA = 0, *CA = 0;
7736 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7737 m_ConstantInt(CA))) &&
7738 BA == CA && isa<TruncInst>(A)) {
7739 Value *I = cast<TruncInst>(A)->getOperand(0);
7740 if (I->getType() == CI.getType()) {
7741 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7742 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7743 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7744 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7745 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7746 CI.getName()), CI);
7747 return BinaryOperator::CreateAShr(I, ShAmtV);
7748 }
7749 }
7750
Chris Lattnerba417832007-04-11 06:12:58 +00007751 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007752}
7753
Chris Lattnerb7530652008-01-27 05:29:54 +00007754/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7755/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007756static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007757 APFloat F = CFP->getValueAPF();
7758 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007759 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007760 return 0;
7761}
7762
7763/// LookThroughFPExtensions - If this is an fp extension instruction, look
7764/// through it until we get the source value.
7765static Value *LookThroughFPExtensions(Value *V) {
7766 if (Instruction *I = dyn_cast<Instruction>(V))
7767 if (I->getOpcode() == Instruction::FPExt)
7768 return LookThroughFPExtensions(I->getOperand(0));
7769
7770 // If this value is a constant, return the constant in the smallest FP type
7771 // that can accurately represent it. This allows us to turn
7772 // (float)((double)X+2.0) into x+2.0f.
7773 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7774 if (CFP->getType() == Type::PPC_FP128Ty)
7775 return V; // No constant folding of this.
7776 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007777 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007778 return V;
7779 if (CFP->getType() == Type::DoubleTy)
7780 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007781 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007782 return V;
7783 // Don't try to shrink to various long double types.
7784 }
7785
7786 return V;
7787}
7788
7789Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7790 if (Instruction *I = commonCastTransforms(CI))
7791 return I;
7792
7793 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7794 // smaller than the destination type, we can eliminate the truncate by doing
7795 // the add as the smaller type. This applies to add/sub/mul/div as well as
7796 // many builtins (sqrt, etc).
7797 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7798 if (OpI && OpI->hasOneUse()) {
7799 switch (OpI->getOpcode()) {
7800 default: break;
7801 case Instruction::Add:
7802 case Instruction::Sub:
7803 case Instruction::Mul:
7804 case Instruction::FDiv:
7805 case Instruction::FRem:
7806 const Type *SrcTy = OpI->getType();
7807 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7808 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7809 if (LHSTrunc->getType() != SrcTy &&
7810 RHSTrunc->getType() != SrcTy) {
7811 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7812 // If the source types were both smaller than the destination type of
7813 // the cast, do this xform.
7814 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7815 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7816 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7817 CI.getType(), CI);
7818 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7819 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007820 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007821 }
7822 }
7823 break;
7824 }
7825 }
7826 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007827}
7828
7829Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7830 return commonCastTransforms(CI);
7831}
7832
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007833Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00007834 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7835 if (OpI == 0)
7836 return commonCastTransforms(FI);
7837
7838 // fptoui(uitofp(X)) --> X
7839 // fptoui(sitofp(X)) --> X
7840 // This is safe if the intermediate type has enough bits in its mantissa to
7841 // accurately represent all values of X. For example, do not do this with
7842 // i64->float->i64. This is also safe for sitofp case, because any negative
7843 // 'X' value would cause an undefined result for the fptoui.
7844 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7845 OpI->getOperand(0)->getType() == FI.getType() &&
7846 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7847 OpI->getType()->getFPMantissaWidth())
7848 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007849
7850 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007851}
7852
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007853Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00007854 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7855 if (OpI == 0)
7856 return commonCastTransforms(FI);
7857
7858 // fptosi(sitofp(X)) --> X
7859 // fptosi(uitofp(X)) --> X
7860 // This is safe if the intermediate type has enough bits in its mantissa to
7861 // accurately represent all values of X. For example, do not do this with
7862 // i64->float->i64. This is also safe for sitofp case, because any negative
7863 // 'X' value would cause an undefined result for the fptoui.
7864 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7865 OpI->getOperand(0)->getType() == FI.getType() &&
7866 (int)FI.getType()->getPrimitiveSizeInBits() <=
7867 OpI->getType()->getFPMantissaWidth())
7868 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007869
7870 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007871}
7872
7873Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7874 return commonCastTransforms(CI);
7875}
7876
7877Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7878 return commonCastTransforms(CI);
7879}
7880
7881Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007882 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007883}
7884
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007885Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7886 if (Instruction *I = commonCastTransforms(CI))
7887 return I;
7888
7889 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7890 if (!DestPointee->isSized()) return 0;
7891
7892 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7893 ConstantInt *Cst;
7894 Value *X;
7895 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7896 m_ConstantInt(Cst)))) {
7897 // If the source and destination operands have the same type, see if this
7898 // is a single-index GEP.
7899 if (X->getType() == CI.getType()) {
7900 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007901 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007902
7903 // Convert the constant to intptr type.
7904 APInt Offset = Cst->getValue();
7905 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7906
7907 // If Offset is evenly divisible by Size, we can do this xform.
7908 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7909 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007910 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007911 }
7912 }
7913 // TODO: Could handle other cases, e.g. where add is indexing into field of
7914 // struct etc.
7915 } else if (CI.getOperand(0)->hasOneUse() &&
7916 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7917 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7918 // "inttoptr+GEP" instead of "add+intptr".
7919
7920 // Get the size of the pointee type.
7921 uint64_t Size = TD->getABITypeSize(DestPointee);
7922
7923 // Convert the constant to intptr type.
7924 APInt Offset = Cst->getValue();
7925 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7926
7927 // If Offset is evenly divisible by Size, we can do this xform.
7928 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7929 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7930
7931 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7932 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007933 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007934 }
7935 }
7936 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007937}
7938
Chris Lattnerd3e28342007-04-27 17:44:50 +00007939Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007940 // If the operands are integer typed then apply the integer transforms,
7941 // otherwise just apply the common ones.
7942 Value *Src = CI.getOperand(0);
7943 const Type *SrcTy = Src->getType();
7944 const Type *DestTy = CI.getType();
7945
Chris Lattner42a75512007-01-15 02:27:26 +00007946 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007947 if (Instruction *Result = commonIntCastTransforms(CI))
7948 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007949 } else if (isa<PointerType>(SrcTy)) {
7950 if (Instruction *I = commonPointerCastTransforms(CI))
7951 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007952 } else {
7953 if (Instruction *Result = commonCastTransforms(CI))
7954 return Result;
7955 }
7956
7957
7958 // Get rid of casts from one type to the same type. These are useless and can
7959 // be replaced by the operand.
7960 if (DestTy == Src->getType())
7961 return ReplaceInstUsesWith(CI, Src);
7962
Reid Spencer3da59db2006-11-27 01:05:10 +00007963 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007964 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7965 const Type *DstElTy = DstPTy->getElementType();
7966 const Type *SrcElTy = SrcPTy->getElementType();
7967
Nate Begeman83ad90a2008-03-31 00:22:16 +00007968 // If the address spaces don't match, don't eliminate the bitcast, which is
7969 // required for changing types.
7970 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7971 return 0;
7972
Chris Lattnerd3e28342007-04-27 17:44:50 +00007973 // If we are casting a malloc or alloca to a pointer to a type of the same
7974 // size, rewrite the allocation instruction to allocate the "right" type.
7975 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7976 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7977 return V;
7978
Chris Lattnerd717c182007-05-05 22:32:24 +00007979 // If the source and destination are pointers, and this cast is equivalent
7980 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007981 // This can enhance SROA and other transforms that want type-safe pointers.
7982 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7983 unsigned NumZeros = 0;
7984 while (SrcElTy != DstElTy &&
7985 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7986 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7987 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7988 ++NumZeros;
7989 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007990
Chris Lattnerd3e28342007-04-27 17:44:50 +00007991 // If we found a path from the src to dest, create the getelementptr now.
7992 if (SrcElTy == DstElTy) {
7993 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007994 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7995 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007996 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007997 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007998
Reid Spencer3da59db2006-11-27 01:05:10 +00007999 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8000 if (SVI->hasOneUse()) {
8001 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8002 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008003 if (isa<VectorType>(DestTy) &&
8004 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008005 SVI->getType()->getNumElements()) {
8006 CastInst *Tmp;
8007 // If either of the operands is a cast from CI.getType(), then
8008 // evaluating the shuffle in the casted destination's type will allow
8009 // us to eliminate at least one cast.
8010 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8011 Tmp->getOperand(0)->getType() == DestTy) ||
8012 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8013 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008014 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8015 SVI->getOperand(0), DestTy, &CI);
8016 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8017 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008018 // Return a new shuffle vector. Use the same element ID's, as we
8019 // know the vector types match #elts.
8020 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008021 }
8022 }
8023 }
8024 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008025 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008026}
8027
Chris Lattnere576b912004-04-09 23:46:01 +00008028/// GetSelectFoldableOperands - We want to turn code that looks like this:
8029/// %C = or %A, %B
8030/// %D = select %cond, %C, %A
8031/// into:
8032/// %C = select %cond, %B, 0
8033/// %D = or %A, %C
8034///
8035/// Assuming that the specified instruction is an operand to the select, return
8036/// a bitmask indicating which operands of this instruction are foldable if they
8037/// equal the other incoming value of the select.
8038///
8039static unsigned GetSelectFoldableOperands(Instruction *I) {
8040 switch (I->getOpcode()) {
8041 case Instruction::Add:
8042 case Instruction::Mul:
8043 case Instruction::And:
8044 case Instruction::Or:
8045 case Instruction::Xor:
8046 return 3; // Can fold through either operand.
8047 case Instruction::Sub: // Can only fold on the amount subtracted.
8048 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008049 case Instruction::LShr:
8050 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008051 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008052 default:
8053 return 0; // Cannot fold
8054 }
8055}
8056
8057/// GetSelectFoldableConstant - For the same transformation as the previous
8058/// function, return the identity constant that goes into the select.
8059static Constant *GetSelectFoldableConstant(Instruction *I) {
8060 switch (I->getOpcode()) {
8061 default: assert(0 && "This cannot happen!"); abort();
8062 case Instruction::Add:
8063 case Instruction::Sub:
8064 case Instruction::Or:
8065 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008066 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008067 case Instruction::LShr:
8068 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008069 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008070 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008071 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008072 case Instruction::Mul:
8073 return ConstantInt::get(I->getType(), 1);
8074 }
8075}
8076
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008077/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8078/// have the same opcode and only one use each. Try to simplify this.
8079Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8080 Instruction *FI) {
8081 if (TI->getNumOperands() == 1) {
8082 // If this is a non-volatile load or a cast from the same type,
8083 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008084 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008085 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8086 return 0;
8087 } else {
8088 return 0; // unknown unary op.
8089 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008090
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008091 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008092 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8093 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008094 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008095 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008097 }
8098
Reid Spencer832254e2007-02-02 02:16:23 +00008099 // Only handle binary operators here.
8100 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008101 return 0;
8102
8103 // Figure out if the operations have any operands in common.
8104 Value *MatchOp, *OtherOpT, *OtherOpF;
8105 bool MatchIsOpZero;
8106 if (TI->getOperand(0) == FI->getOperand(0)) {
8107 MatchOp = TI->getOperand(0);
8108 OtherOpT = TI->getOperand(1);
8109 OtherOpF = FI->getOperand(1);
8110 MatchIsOpZero = true;
8111 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8112 MatchOp = TI->getOperand(1);
8113 OtherOpT = TI->getOperand(0);
8114 OtherOpF = FI->getOperand(0);
8115 MatchIsOpZero = false;
8116 } else if (!TI->isCommutative()) {
8117 return 0;
8118 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8119 MatchOp = TI->getOperand(0);
8120 OtherOpT = TI->getOperand(1);
8121 OtherOpF = FI->getOperand(0);
8122 MatchIsOpZero = true;
8123 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8124 MatchOp = TI->getOperand(1);
8125 OtherOpT = TI->getOperand(0);
8126 OtherOpF = FI->getOperand(1);
8127 MatchIsOpZero = true;
8128 } else {
8129 return 0;
8130 }
8131
8132 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008133 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8134 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008135 InsertNewInstBefore(NewSI, SI);
8136
8137 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8138 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008139 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008140 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008141 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008142 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008143 assert(0 && "Shouldn't get here");
8144 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008145}
8146
Chris Lattner3d69f462004-03-12 05:52:32 +00008147Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008148 Value *CondVal = SI.getCondition();
8149 Value *TrueVal = SI.getTrueValue();
8150 Value *FalseVal = SI.getFalseValue();
8151
8152 // select true, X, Y -> X
8153 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008154 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008155 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008156
8157 // select C, X, X -> X
8158 if (TrueVal == FalseVal)
8159 return ReplaceInstUsesWith(SI, TrueVal);
8160
Chris Lattnere87597f2004-10-16 18:11:37 +00008161 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8162 return ReplaceInstUsesWith(SI, FalseVal);
8163 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8164 return ReplaceInstUsesWith(SI, TrueVal);
8165 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8166 if (isa<Constant>(TrueVal))
8167 return ReplaceInstUsesWith(SI, TrueVal);
8168 else
8169 return ReplaceInstUsesWith(SI, FalseVal);
8170 }
8171
Reid Spencer4fe16d62007-01-11 18:21:29 +00008172 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008173 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008174 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008175 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008176 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008177 } else {
8178 // Change: A = select B, false, C --> A = and !B, C
8179 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008180 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008181 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008182 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008183 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008184 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008185 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008186 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008187 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008188 } else {
8189 // Change: A = select B, C, true --> A = or !B, C
8190 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008191 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008192 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008193 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008194 }
8195 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008196
8197 // select a, b, a -> a&b
8198 // select a, a, b -> a|b
8199 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008200 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008201 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008202 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008203 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008204
Chris Lattner2eefe512004-04-09 19:05:30 +00008205 // Selecting between two integer constants?
8206 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8207 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008208 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008209 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008210 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008211 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008212 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008213 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008214 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008215 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008216 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008217 }
Chris Lattnerba417832007-04-11 06:12:58 +00008218
8219 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008220
Reid Spencere4d87aa2006-12-23 06:05:41 +00008221 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008222
Reid Spencere4d87aa2006-12-23 06:05:41 +00008223 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008224 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008225 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008226 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008227 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008228 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008229 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008230 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008231 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008232 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008233 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008234 InsertNewInstBefore(SRA, SI);
8235
Reid Spencer3da59db2006-11-27 01:05:10 +00008236 // Finally, convert to the type of the select RHS. We figure out
8237 // if this requires a SExt, Trunc or BitCast based on the sizes.
8238 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008239 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8240 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008241 if (SRASize < SISize)
8242 opc = Instruction::SExt;
8243 else if (SRASize > SISize)
8244 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008245 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008246 }
8247 }
8248
8249
8250 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008251 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008252 // non-constant value, eliminate this whole mess. This corresponds to
8253 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008254 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008255 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008256 cast<Constant>(IC->getOperand(1))->isNullValue())
8257 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8258 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008259 isa<ConstantInt>(ICA->getOperand(1)) &&
8260 (ICA->getOperand(1) == TrueValC ||
8261 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008262 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8263 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008264 // know whether we have a icmp_ne or icmp_eq and whether the
8265 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008266 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008267 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008268 Value *V = ICA;
8269 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008270 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008271 Instruction::Xor, V, ICA->getOperand(1)), SI);
8272 return ReplaceInstUsesWith(SI, V);
8273 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008274 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008275 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008276
8277 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008278 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8279 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008280 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008281 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8282 // This is not safe in general for floating point:
8283 // consider X== -0, Y== +0.
8284 // It becomes safe if either operand is a nonzero constant.
8285 ConstantFP *CFPt, *CFPf;
8286 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8287 !CFPt->getValueAPF().isZero()) ||
8288 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8289 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008290 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008291 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008292 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008293 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008294 return ReplaceInstUsesWith(SI, TrueVal);
8295 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8296
Reid Spencere4d87aa2006-12-23 06:05:41 +00008297 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008298 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008299 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8300 // This is not safe in general for floating point:
8301 // consider X== -0, Y== +0.
8302 // It becomes safe if either operand is a nonzero constant.
8303 ConstantFP *CFPt, *CFPf;
8304 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8305 !CFPt->getValueAPF().isZero()) ||
8306 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8307 !CFPf->getValueAPF().isZero()))
8308 return ReplaceInstUsesWith(SI, FalseVal);
8309 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008310 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008311 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8312 return ReplaceInstUsesWith(SI, TrueVal);
8313 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8314 }
8315 }
8316
8317 // See if we are selecting two values based on a comparison of the two values.
8318 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8319 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8320 // Transform (X == Y) ? X : Y -> Y
8321 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8322 return ReplaceInstUsesWith(SI, FalseVal);
8323 // Transform (X != Y) ? X : Y -> X
8324 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8325 return ReplaceInstUsesWith(SI, TrueVal);
8326 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8327
8328 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8329 // Transform (X == Y) ? Y : X -> X
8330 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8331 return ReplaceInstUsesWith(SI, FalseVal);
8332 // Transform (X != Y) ? Y : X -> Y
8333 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008334 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008335 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8336 }
8337 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008338
Chris Lattner87875da2005-01-13 22:52:24 +00008339 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8340 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8341 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008342 Instruction *AddOp = 0, *SubOp = 0;
8343
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008344 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8345 if (TI->getOpcode() == FI->getOpcode())
8346 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8347 return IV;
8348
8349 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8350 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008351 if (TI->getOpcode() == Instruction::Sub &&
8352 FI->getOpcode() == Instruction::Add) {
8353 AddOp = FI; SubOp = TI;
8354 } else if (FI->getOpcode() == Instruction::Sub &&
8355 TI->getOpcode() == Instruction::Add) {
8356 AddOp = TI; SubOp = FI;
8357 }
8358
8359 if (AddOp) {
8360 Value *OtherAddOp = 0;
8361 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8362 OtherAddOp = AddOp->getOperand(1);
8363 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8364 OtherAddOp = AddOp->getOperand(0);
8365 }
8366
8367 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008368 // So at this point we know we have (Y -> OtherAddOp):
8369 // select C, (add X, Y), (sub X, Z)
8370 Value *NegVal; // Compute -Z
8371 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8372 NegVal = ConstantExpr::getNeg(C);
8373 } else {
8374 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008375 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008376 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008377
8378 Value *NewTrueOp = OtherAddOp;
8379 Value *NewFalseOp = NegVal;
8380 if (AddOp != TI)
8381 std::swap(NewTrueOp, NewFalseOp);
8382 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008383 SelectInst::Create(CondVal, NewTrueOp,
8384 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008385
8386 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008387 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008388 }
8389 }
8390 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008391
Chris Lattnere576b912004-04-09 23:46:01 +00008392 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008393 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008394 // See the comment above GetSelectFoldableOperands for a description of the
8395 // transformation we are doing here.
8396 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8397 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8398 !isa<Constant>(FalseVal))
8399 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8400 unsigned OpToFold = 0;
8401 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8402 OpToFold = 1;
8403 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8404 OpToFold = 2;
8405 }
8406
8407 if (OpToFold) {
8408 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008409 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008410 SelectInst::Create(SI.getCondition(),
8411 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008412 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008413 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008414 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008415 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008416 else {
8417 assert(0 && "Unknown instruction!!");
8418 }
8419 }
8420 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008421
Chris Lattnere576b912004-04-09 23:46:01 +00008422 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8423 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8424 !isa<Constant>(TrueVal))
8425 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8426 unsigned OpToFold = 0;
8427 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8428 OpToFold = 1;
8429 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8430 OpToFold = 2;
8431 }
8432
8433 if (OpToFold) {
8434 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008435 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008436 SelectInst::Create(SI.getCondition(), C,
8437 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008438 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008439 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008440 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008441 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008442 else
Chris Lattnere576b912004-04-09 23:46:01 +00008443 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008444 }
8445 }
8446 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008447
8448 if (BinaryOperator::isNot(CondVal)) {
8449 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8450 SI.setOperand(1, FalseVal);
8451 SI.setOperand(2, TrueVal);
8452 return &SI;
8453 }
8454
Chris Lattner3d69f462004-03-12 05:52:32 +00008455 return 0;
8456}
8457
Dan Gohmaneee962e2008-04-10 18:43:06 +00008458/// EnforceKnownAlignment - If the specified pointer points to an object that
8459/// we control, modify the object's alignment to PrefAlign. This isn't
8460/// often possible though. If alignment is important, a more reliable approach
8461/// is to simply align all global variables and allocation instructions to
8462/// their preferred alignment from the beginning.
8463///
8464static unsigned EnforceKnownAlignment(Value *V,
8465 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008466
Dan Gohmaneee962e2008-04-10 18:43:06 +00008467 User *U = dyn_cast<User>(V);
8468 if (!U) return Align;
8469
8470 switch (getOpcode(U)) {
8471 default: break;
8472 case Instruction::BitCast:
8473 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8474 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008475 // If all indexes are zero, it is just the alignment of the base pointer.
8476 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008477 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008478 if (!isa<Constant>(*i) ||
8479 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008480 AllZeroOperands = false;
8481 break;
8482 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008483
8484 if (AllZeroOperands) {
8485 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008486 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008487 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008488 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008489 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008490 }
8491
8492 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8493 // If there is a large requested alignment and we can, bump up the alignment
8494 // of the global.
8495 if (!GV->isDeclaration()) {
8496 GV->setAlignment(PrefAlign);
8497 Align = PrefAlign;
8498 }
8499 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8500 // If there is a requested alignment and if this is an alloca, round up. We
8501 // don't do this for malloc, because some systems can't respect the request.
8502 if (isa<AllocaInst>(AI)) {
8503 AI->setAlignment(PrefAlign);
8504 Align = PrefAlign;
8505 }
8506 }
8507
8508 return Align;
8509}
8510
8511/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8512/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8513/// and it is more than the alignment of the ultimate object, see if we can
8514/// increase the alignment of the ultimate object, making this check succeed.
8515unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8516 unsigned PrefAlign) {
8517 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8518 sizeof(PrefAlign) * CHAR_BIT;
8519 APInt Mask = APInt::getAllOnesValue(BitWidth);
8520 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8521 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8522 unsigned TrailZ = KnownZero.countTrailingOnes();
8523 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8524
8525 if (PrefAlign > Align)
8526 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8527
8528 // We don't need to make any adjustment.
8529 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008530}
8531
Chris Lattnerf497b022008-01-13 23:50:23 +00008532Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008533 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8534 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008535 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8536 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8537
8538 if (CopyAlign < MinAlign) {
8539 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8540 return MI;
8541 }
8542
8543 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8544 // load/store.
8545 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8546 if (MemOpLength == 0) return 0;
8547
Chris Lattner37ac6082008-01-14 00:28:35 +00008548 // Source and destination pointer types are always "i8*" for intrinsic. See
8549 // if the size is something we can handle with a single primitive load/store.
8550 // A single load+store correctly handles overlapping memory in the memmove
8551 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008552 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008553 if (Size == 0) return MI; // Delete this mem transfer.
8554
8555 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008556 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008557
Chris Lattner37ac6082008-01-14 00:28:35 +00008558 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008559 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008560
8561 // Memcpy forces the use of i8* for the source and destination. That means
8562 // that if you're using memcpy to move one double around, you'll get a cast
8563 // from double* to i8*. We'd much rather use a double load+store rather than
8564 // an i64 load+store, here because this improves the odds that the source or
8565 // dest address will be promotable. See if we can find a better type than the
8566 // integer datatype.
8567 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8568 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8569 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8570 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8571 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008572 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008573 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8574 if (STy->getNumElements() == 1)
8575 SrcETy = STy->getElementType(0);
8576 else
8577 break;
8578 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8579 if (ATy->getNumElements() == 1)
8580 SrcETy = ATy->getElementType();
8581 else
8582 break;
8583 } else
8584 break;
8585 }
8586
Dan Gohman8f8e2692008-05-23 01:52:21 +00008587 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008588 NewPtrTy = PointerType::getUnqual(SrcETy);
8589 }
8590 }
8591
8592
Chris Lattnerf497b022008-01-13 23:50:23 +00008593 // If the memcpy/memmove provides better alignment info than we can
8594 // infer, use it.
8595 SrcAlign = std::max(SrcAlign, CopyAlign);
8596 DstAlign = std::max(DstAlign, CopyAlign);
8597
8598 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8599 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008600 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8601 InsertNewInstBefore(L, *MI);
8602 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8603
8604 // Set the size of the copy to 0, it will be deleted on the next iteration.
8605 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8606 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008607}
Chris Lattner3d69f462004-03-12 05:52:32 +00008608
Chris Lattner69ea9d22008-04-30 06:39:11 +00008609Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8610 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8611 if (MI->getAlignment()->getZExtValue() < Alignment) {
8612 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8613 return MI;
8614 }
8615
8616 // Extract the length and alignment and fill if they are constant.
8617 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8618 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8619 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8620 return 0;
8621 uint64_t Len = LenC->getZExtValue();
8622 Alignment = MI->getAlignment()->getZExtValue();
8623
8624 // If the length is zero, this is a no-op
8625 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8626
8627 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8628 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8629 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8630
8631 Value *Dest = MI->getDest();
8632 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8633
8634 // Alignment 0 is identity for alignment 1 for memset, but not store.
8635 if (Alignment == 0) Alignment = 1;
8636
8637 // Extract the fill value and store.
8638 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8639 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8640 Alignment), *MI);
8641
8642 // Set the size of the copy to 0, it will be deleted on the next iteration.
8643 MI->setLength(Constant::getNullValue(LenC->getType()));
8644 return MI;
8645 }
8646
8647 return 0;
8648}
8649
8650
Chris Lattner8b0ea312006-01-13 20:11:04 +00008651/// visitCallInst - CallInst simplification. This mostly only handles folding
8652/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8653/// the heavy lifting.
8654///
Chris Lattner9fe38862003-06-19 17:00:31 +00008655Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008656 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8657 if (!II) return visitCallSite(&CI);
8658
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008659 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8660 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008661 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008662 bool Changed = false;
8663
8664 // memmove/cpy/set of zero bytes is a noop.
8665 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8666 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8667
Chris Lattner35b9e482004-10-12 04:52:52 +00008668 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008669 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008670 // Replace the instruction with just byte operations. We would
8671 // transform other cases to loads/stores, but we don't know if
8672 // alignment is sufficient.
8673 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008674 }
8675
Chris Lattner35b9e482004-10-12 04:52:52 +00008676 // If we have a memmove and the source operation is a constant global,
8677 // then the source and dest pointers can't alias, so we can change this
8678 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008679 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008680 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8681 if (GVSrc->isConstant()) {
8682 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008683 Intrinsic::ID MemCpyID;
8684 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8685 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008686 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008687 MemCpyID = Intrinsic::memcpy_i64;
8688 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008689 Changed = true;
8690 }
Chris Lattnera935db82008-05-28 05:30:41 +00008691
8692 // memmove(x,x,size) -> noop.
8693 if (MMI->getSource() == MMI->getDest())
8694 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008695 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008696
Chris Lattner95a959d2006-03-06 20:18:44 +00008697 // If we can determine a pointer alignment that is bigger than currently
8698 // set, update the alignment.
8699 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008700 if (Instruction *I = SimplifyMemTransfer(MI))
8701 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008702 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8703 if (Instruction *I = SimplifyMemSet(MSI))
8704 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008705 }
8706
Chris Lattner8b0ea312006-01-13 20:11:04 +00008707 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00008708 }
8709
8710 switch (II->getIntrinsicID()) {
8711 default: break;
8712 case Intrinsic::bswap:
8713 // bswap(bswap(x)) -> x
8714 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8715 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8716 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8717 break;
8718 case Intrinsic::ppc_altivec_lvx:
8719 case Intrinsic::ppc_altivec_lvxl:
8720 case Intrinsic::x86_sse_loadu_ps:
8721 case Intrinsic::x86_sse2_loadu_pd:
8722 case Intrinsic::x86_sse2_loadu_dq:
8723 // Turn PPC lvx -> load if the pointer is known aligned.
8724 // Turn X86 loadups -> load if the pointer is known aligned.
8725 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8726 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8727 PointerType::getUnqual(II->getType()),
8728 CI);
8729 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00008730 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008731 break;
8732 case Intrinsic::ppc_altivec_stvx:
8733 case Intrinsic::ppc_altivec_stvxl:
8734 // Turn stvx -> store if the pointer is known aligned.
8735 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8736 const Type *OpPtrTy =
8737 PointerType::getUnqual(II->getOperand(1)->getType());
8738 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8739 return new StoreInst(II->getOperand(1), Ptr);
8740 }
8741 break;
8742 case Intrinsic::x86_sse_storeu_ps:
8743 case Intrinsic::x86_sse2_storeu_pd:
8744 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00008745 // Turn X86 storeu -> store if the pointer is known aligned.
8746 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8747 const Type *OpPtrTy =
8748 PointerType::getUnqual(II->getOperand(2)->getType());
8749 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8750 return new StoreInst(II->getOperand(2), Ptr);
8751 }
8752 break;
8753
8754 case Intrinsic::x86_sse_cvttss2si: {
8755 // These intrinsics only demands the 0th element of its input vector. If
8756 // we can simplify the input based on that, do so now.
8757 uint64_t UndefElts;
8758 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8759 UndefElts)) {
8760 II->setOperand(1, V);
8761 return II;
8762 }
8763 break;
8764 }
8765
8766 case Intrinsic::ppc_altivec_vperm:
8767 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8768 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8769 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00008770
Chris Lattner0521e3c2008-06-18 04:33:20 +00008771 // Check that all of the elements are integer constants or undefs.
8772 bool AllEltsOk = true;
8773 for (unsigned i = 0; i != 16; ++i) {
8774 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8775 !isa<UndefValue>(Mask->getOperand(i))) {
8776 AllEltsOk = false;
8777 break;
8778 }
8779 }
8780
8781 if (AllEltsOk) {
8782 // Cast the input vectors to byte vectors.
8783 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8784 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8785 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008786
Chris Lattner0521e3c2008-06-18 04:33:20 +00008787 // Only extract each element once.
8788 Value *ExtractedElts[32];
8789 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8790
Chris Lattnere2ed0572006-04-06 19:19:17 +00008791 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00008792 if (isa<UndefValue>(Mask->getOperand(i)))
8793 continue;
8794 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8795 Idx &= 31; // Match the hardware behavior.
8796
8797 if (ExtractedElts[Idx] == 0) {
8798 Instruction *Elt =
8799 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8800 InsertNewInstBefore(Elt, CI);
8801 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008802 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00008803
Chris Lattner0521e3c2008-06-18 04:33:20 +00008804 // Insert this value into the result vector.
8805 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8806 i, "tmp");
8807 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008808 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008809 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008810 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008811 }
8812 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008813
Chris Lattner0521e3c2008-06-18 04:33:20 +00008814 case Intrinsic::stackrestore: {
8815 // If the save is right next to the restore, remove the restore. This can
8816 // happen when variable allocas are DCE'd.
8817 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8818 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8819 BasicBlock::iterator BI = SS;
8820 if (&*++BI == II)
8821 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008822 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008823 }
8824
8825 // Scan down this block to see if there is another stack restore in the
8826 // same block without an intervening call/alloca.
8827 BasicBlock::iterator BI = II;
8828 TerminatorInst *TI = II->getParent()->getTerminator();
8829 bool CannotRemove = false;
8830 for (++BI; &*BI != TI; ++BI) {
8831 if (isa<AllocaInst>(BI)) {
8832 CannotRemove = true;
8833 break;
8834 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00008835 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8836 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8837 // If there is a stackrestore below this one, remove this one.
8838 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8839 return EraseInstFromFunction(CI);
8840 // Otherwise, ignore the intrinsic.
8841 } else {
8842 // If we found a non-intrinsic call, we can't remove the stack
8843 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008844 CannotRemove = true;
8845 break;
8846 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008847 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008848 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008849
8850 // If the stack restore is in a return/unwind block and if there are no
8851 // allocas or calls between the restore and the return, nuke the restore.
8852 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8853 return EraseInstFromFunction(CI);
8854 break;
8855 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008856 }
8857
Chris Lattner8b0ea312006-01-13 20:11:04 +00008858 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008859}
8860
8861// InvokeInst simplification
8862//
8863Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008864 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008865}
8866
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008867/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8868/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008869static bool isSafeToEliminateVarargsCast(const CallSite CS,
8870 const CastInst * const CI,
8871 const TargetData * const TD,
8872 const int ix) {
8873 if (!CI->isLosslessCast())
8874 return false;
8875
8876 // The size of ByVal arguments is derived from the type, so we
8877 // can't change to a type with a different size. If the size were
8878 // passed explicitly we could avoid this check.
8879 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8880 return true;
8881
8882 const Type* SrcTy =
8883 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8884 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8885 if (!SrcTy->isSized() || !DstTy->isSized())
8886 return false;
8887 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8888 return false;
8889 return true;
8890}
8891
Chris Lattnera44d8a22003-10-07 22:32:43 +00008892// visitCallSite - Improvements for call and invoke instructions.
8893//
8894Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008895 bool Changed = false;
8896
8897 // If the callee is a constexpr cast of a function, attempt to move the cast
8898 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008899 if (transformConstExprCastCall(CS)) return 0;
8900
Chris Lattner6c266db2003-10-07 22:54:13 +00008901 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008902
Chris Lattner08b22ec2005-05-13 07:09:09 +00008903 if (Function *CalleeF = dyn_cast<Function>(Callee))
8904 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8905 Instruction *OldCall = CS.getInstruction();
8906 // If the call and callee calling conventions don't match, this call must
8907 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008908 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008909 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8910 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008911 if (!OldCall->use_empty())
8912 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8913 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8914 return EraseInstFromFunction(*OldCall);
8915 return 0;
8916 }
8917
Chris Lattner17be6352004-10-18 02:59:09 +00008918 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8919 // This instruction is not reachable, just remove it. We insert a store to
8920 // undef so that we know that this code is not reachable, despite the fact
8921 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008922 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008923 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008924 CS.getInstruction());
8925
8926 if (!CS.getInstruction()->use_empty())
8927 CS.getInstruction()->
8928 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8929
8930 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8931 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008932 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8933 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008934 }
Chris Lattner17be6352004-10-18 02:59:09 +00008935 return EraseInstFromFunction(*CS.getInstruction());
8936 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008937
Duncan Sandscdb6d922007-09-17 10:26:40 +00008938 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8939 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8940 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8941 return transformCallThroughTrampoline(CS);
8942
Chris Lattner6c266db2003-10-07 22:54:13 +00008943 const PointerType *PTy = cast<PointerType>(Callee->getType());
8944 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8945 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008946 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008947 // See if we can optimize any arguments passed through the varargs area of
8948 // the call.
8949 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008950 E = CS.arg_end(); I != E; ++I, ++ix) {
8951 CastInst *CI = dyn_cast<CastInst>(*I);
8952 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8953 *I = CI->getOperand(0);
8954 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008955 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008956 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008957 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008958
Duncan Sandsf0c33542007-12-19 21:13:37 +00008959 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008960 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008961 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008962 Changed = true;
8963 }
8964
Chris Lattner6c266db2003-10-07 22:54:13 +00008965 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008966}
8967
Chris Lattner9fe38862003-06-19 17:00:31 +00008968// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8969// attempt to move the cast to the arguments of the call/invoke.
8970//
8971bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8972 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8973 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008974 if (CE->getOpcode() != Instruction::BitCast ||
8975 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008976 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008977 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008978 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008979 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008980
8981 // Okay, this is a cast from a function to a different type. Unless doing so
8982 // would cause a type conversion of one of our arguments, change this call to
8983 // be a direct call with arguments casted to the appropriate types.
8984 //
8985 const FunctionType *FT = Callee->getFunctionType();
8986 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008987 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008988
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008989 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008990 return false; // TODO: Handle multiple return values.
8991
Chris Lattnerf78616b2004-01-14 06:06:08 +00008992 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008993 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008994 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008995 // Conversion is ok if changing from one pointer type to another or from
8996 // a pointer to an integer of the same size.
8997 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00008998 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00008999 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009000
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009001 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009002 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009003 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009004 return false; // Cannot transform this return value.
9005
Chris Lattner58d74912008-03-12 17:45:29 +00009006 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9007 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009008 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009009 return false; // Attribute not compatible with transformed value.
9010 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009011
Chris Lattnerf78616b2004-01-14 06:06:08 +00009012 // If the callsite is an invoke instruction, and the return value is used by
9013 // a PHI node in a successor, we cannot change the return type of the call
9014 // because there is no place to put the cast instruction (without breaking
9015 // the critical edge). Bail out in this case.
9016 if (!Caller->use_empty())
9017 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9018 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9019 UI != E; ++UI)
9020 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9021 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009022 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009023 return false;
9024 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009025
9026 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9027 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009028
Chris Lattner9fe38862003-06-19 17:00:31 +00009029 CallSite::arg_iterator AI = CS.arg_begin();
9030 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9031 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009032 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009033
9034 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009035 return false; // Cannot transform this parameter value.
9036
Chris Lattner58d74912008-03-12 17:45:29 +00009037 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9038 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009039
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009040 // Converting from one pointer type to another or between a pointer and an
9041 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009042 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009043 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9044 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009045 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009046 }
9047
9048 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009049 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009050 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009051
Chris Lattner58d74912008-03-12 17:45:29 +00009052 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9053 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009054 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009055 // won't be dropping them. Check that these extra arguments have attributes
9056 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009057 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9058 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009059 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009060 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009061 if (PAttrs & ParamAttr::VarArgsIncompatible)
9062 return false;
9063 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009064
Chris Lattner9fe38862003-06-19 17:00:31 +00009065 // Okay, we decided that this is a safe thing to do: go ahead and start
9066 // inserting cast instructions as necessary...
9067 std::vector<Value*> Args;
9068 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009069 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009070 attrVec.reserve(NumCommonArgs);
9071
9072 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009073 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009074
9075 // If the return value is not being used, the type may not be compatible
9076 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009077 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009078
9079 // Add the new return attributes.
9080 if (RAttrs)
9081 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009082
9083 AI = CS.arg_begin();
9084 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9085 const Type *ParamTy = FT->getParamType(i);
9086 if ((*AI)->getType() == ParamTy) {
9087 Args.push_back(*AI);
9088 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009089 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009090 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009091 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009092 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009093 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009094
9095 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009096 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009097 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009098 }
9099
9100 // If the function takes more arguments than the call was taking, add them
9101 // now...
9102 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9103 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9104
9105 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009106 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009107 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009108 cerr << "WARNING: While resolving call to function '"
9109 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009110 } else {
9111 // Add all of the arguments in their promoted form to the arg list...
9112 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9113 const Type *PTy = getPromotedType((*AI)->getType());
9114 if (PTy != (*AI)->getType()) {
9115 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009116 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9117 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009118 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009119 InsertNewInstBefore(Cast, *Caller);
9120 Args.push_back(Cast);
9121 } else {
9122 Args.push_back(*AI);
9123 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009124
Duncan Sandse1e520f2008-01-13 08:02:44 +00009125 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009126 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009127 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9128 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009129 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009130 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009131
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009132 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009133 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009134
Chris Lattner58d74912008-03-12 17:45:29 +00009135 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009136
Chris Lattner9fe38862003-06-19 17:00:31 +00009137 Instruction *NC;
9138 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009139 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009140 Args.begin(), Args.end(),
9141 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009142 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009143 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009144 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009145 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9146 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009147 CallInst *CI = cast<CallInst>(Caller);
9148 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009149 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009150 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009151 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009152 }
9153
Chris Lattner6934a042007-02-11 01:23:03 +00009154 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009155 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009156 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009157 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009158 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009159 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009160 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009161
9162 // If this is an invoke instruction, we should insert it after the first
9163 // non-phi, instruction in the normal successor block.
9164 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009165 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009166 InsertNewInstBefore(NC, *I);
9167 } else {
9168 // Otherwise, it's a call, just insert cast right after the call instr
9169 InsertNewInstBefore(NC, *Caller);
9170 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009171 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009172 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009173 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009174 }
9175 }
9176
9177 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9178 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009179 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009180 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009181 return true;
9182}
9183
Duncan Sandscdb6d922007-09-17 10:26:40 +00009184// transformCallThroughTrampoline - Turn a call to a function created by the
9185// init_trampoline intrinsic into a direct call to the underlying function.
9186//
9187Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9188 Value *Callee = CS.getCalledValue();
9189 const PointerType *PTy = cast<PointerType>(Callee->getType());
9190 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009191 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009192
9193 // If the call already has the 'nest' attribute somewhere then give up -
9194 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009195 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009196 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009197
9198 IntrinsicInst *Tramp =
9199 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9200
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009201 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009202 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9203 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9204
Chris Lattner58d74912008-03-12 17:45:29 +00009205 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9206 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009207 unsigned NestIdx = 1;
9208 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009209 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009210
9211 // Look for a parameter marked with the 'nest' attribute.
9212 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9213 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009214 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009215 // Record the parameter type and any other attributes.
9216 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009217 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009218 break;
9219 }
9220
9221 if (NestTy) {
9222 Instruction *Caller = CS.getInstruction();
9223 std::vector<Value*> NewArgs;
9224 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9225
Chris Lattner58d74912008-03-12 17:45:29 +00009226 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9227 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009228
Duncan Sandscdb6d922007-09-17 10:26:40 +00009229 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009230 // mean appending it. Likewise for attributes.
9231
9232 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009233 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9234 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009235
Duncan Sandscdb6d922007-09-17 10:26:40 +00009236 {
9237 unsigned Idx = 1;
9238 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9239 do {
9240 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009241 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009242 Value *NestVal = Tramp->getOperand(3);
9243 if (NestVal->getType() != NestTy)
9244 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9245 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009246 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009247 }
9248
9249 if (I == E)
9250 break;
9251
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009252 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009253 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009254 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009255 NewAttrs.push_back
9256 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009257
9258 ++Idx, ++I;
9259 } while (1);
9260 }
9261
9262 // The trampoline may have been bitcast to a bogus type (FTy).
9263 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009264 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009265
Duncan Sandscdb6d922007-09-17 10:26:40 +00009266 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009267 NewTypes.reserve(FTy->getNumParams()+1);
9268
Duncan Sandscdb6d922007-09-17 10:26:40 +00009269 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009270 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009271 {
9272 unsigned Idx = 1;
9273 FunctionType::param_iterator I = FTy->param_begin(),
9274 E = FTy->param_end();
9275
9276 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009277 if (Idx == NestIdx)
9278 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009279 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009280
9281 if (I == E)
9282 break;
9283
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009284 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009285 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009286
9287 ++Idx, ++I;
9288 } while (1);
9289 }
9290
9291 // Replace the trampoline call with a direct call. Let the generic
9292 // code sort out any function type mismatches.
9293 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009294 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009295 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9296 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009297 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009298
9299 Instruction *NewCaller;
9300 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009301 NewCaller = InvokeInst::Create(NewCallee,
9302 II->getNormalDest(), II->getUnwindDest(),
9303 NewArgs.begin(), NewArgs.end(),
9304 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009305 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009306 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009307 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009308 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9309 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009310 if (cast<CallInst>(Caller)->isTailCall())
9311 cast<CallInst>(NewCaller)->setTailCall();
9312 cast<CallInst>(NewCaller)->
9313 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009314 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009315 }
9316 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9317 Caller->replaceAllUsesWith(NewCaller);
9318 Caller->eraseFromParent();
9319 RemoveFromWorkList(Caller);
9320 return 0;
9321 }
9322 }
9323
9324 // Replace the trampoline call with a direct call. Since there is no 'nest'
9325 // parameter, there is no need to adjust the argument list. Let the generic
9326 // code sort out any function type mismatches.
9327 Constant *NewCallee =
9328 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9329 CS.setCalledFunction(NewCallee);
9330 return CS.getInstruction();
9331}
9332
Chris Lattner7da52b22006-11-01 04:51:18 +00009333/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9334/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9335/// and a single binop.
9336Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9337 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009338 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9339 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009340 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009341 Value *LHSVal = FirstInst->getOperand(0);
9342 Value *RHSVal = FirstInst->getOperand(1);
9343
9344 const Type *LHSType = LHSVal->getType();
9345 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009346
9347 // Scan to see if all operands are the same opcode, all have one use, and all
9348 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009349 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009350 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009351 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009352 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009353 // types or GEP's with different index types.
9354 I->getOperand(0)->getType() != LHSType ||
9355 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009356 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009357
9358 // If they are CmpInst instructions, check their predicates
9359 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9360 if (cast<CmpInst>(I)->getPredicate() !=
9361 cast<CmpInst>(FirstInst)->getPredicate())
9362 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009363
9364 // Keep track of which operand needs a phi node.
9365 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9366 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009367 }
9368
Chris Lattner53738a42006-11-08 19:42:28 +00009369 // Otherwise, this is safe to transform, determine if it is profitable.
9370
9371 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9372 // Indexes are often folded into load/store instructions, so we don't want to
9373 // hide them behind a phi.
9374 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9375 return 0;
9376
Chris Lattner7da52b22006-11-01 04:51:18 +00009377 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009378 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009379 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009380 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009381 NewLHS = PHINode::Create(LHSType,
9382 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009383 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9384 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009385 InsertNewInstBefore(NewLHS, PN);
9386 LHSVal = NewLHS;
9387 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009388
9389 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009390 NewRHS = PHINode::Create(RHSType,
9391 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009392 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9393 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009394 InsertNewInstBefore(NewRHS, PN);
9395 RHSVal = NewRHS;
9396 }
9397
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009398 // Add all operands to the new PHIs.
9399 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9400 if (NewLHS) {
9401 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9402 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9403 }
9404 if (NewRHS) {
9405 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9406 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9407 }
9408 }
9409
Chris Lattner7da52b22006-11-01 04:51:18 +00009410 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009411 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009412 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009413 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009414 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009415 else {
9416 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009417 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009418 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009419}
9420
Chris Lattner76c73142006-11-01 07:13:54 +00009421/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9422/// of the block that defines it. This means that it must be obvious the value
9423/// of the load is not changed from the point of the load to the end of the
9424/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009425///
9426/// Finally, it is safe, but not profitable, to sink a load targetting a
9427/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9428/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009429static bool isSafeToSinkLoad(LoadInst *L) {
9430 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9431
9432 for (++BBI; BBI != E; ++BBI)
9433 if (BBI->mayWriteToMemory())
9434 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009435
9436 // Check for non-address taken alloca. If not address-taken already, it isn't
9437 // profitable to do this xform.
9438 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9439 bool isAddressTaken = false;
9440 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9441 UI != E; ++UI) {
9442 if (isa<LoadInst>(UI)) continue;
9443 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9444 // If storing TO the alloca, then the address isn't taken.
9445 if (SI->getOperand(1) == AI) continue;
9446 }
9447 isAddressTaken = true;
9448 break;
9449 }
9450
9451 if (!isAddressTaken)
9452 return false;
9453 }
9454
Chris Lattner76c73142006-11-01 07:13:54 +00009455 return true;
9456}
9457
Chris Lattner9fe38862003-06-19 17:00:31 +00009458
Chris Lattnerbac32862004-11-14 19:13:23 +00009459// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9460// operator and they all are only used by the PHI, PHI together their
9461// inputs, and do the operation once, to the result of the PHI.
9462Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9463 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9464
9465 // Scan the instruction, looking for input operations that can be folded away.
9466 // If all input operands to the phi are the same instruction (e.g. a cast from
9467 // the same type or "+42") we can pull the operation through the PHI, reducing
9468 // code size and simplifying code.
9469 Constant *ConstantOp = 0;
9470 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009471 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009472 if (isa<CastInst>(FirstInst)) {
9473 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009474 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009475 // Can fold binop, compare or shift here if the RHS is a constant,
9476 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009477 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009478 if (ConstantOp == 0)
9479 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009480 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9481 isVolatile = LI->isVolatile();
9482 // We can't sink the load if the loaded value could be modified between the
9483 // load and the PHI.
9484 if (LI->getParent() != PN.getIncomingBlock(0) ||
9485 !isSafeToSinkLoad(LI))
9486 return 0;
Chris Lattner71042962008-07-08 17:18:32 +00009487
9488 // If the PHI is of volatile loads and the load block has multiple
9489 // successors, sinking it would remove a load of the volatile value from
9490 // the path through the other successor.
9491 if (isVolatile &&
9492 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9493 return 0;
9494
Chris Lattner9c080502006-11-01 07:43:41 +00009495 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009496 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009497 return FoldPHIArgBinOpIntoPHI(PN);
9498 // Can't handle general GEPs yet.
9499 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009500 } else {
9501 return 0; // Cannot fold this operation.
9502 }
9503
9504 // Check to see if all arguments are the same operation.
9505 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9506 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9507 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009508 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009509 return 0;
9510 if (CastSrcTy) {
9511 if (I->getOperand(0)->getType() != CastSrcTy)
9512 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009513 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009514 // We can't sink the load if the loaded value could be modified between
9515 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009516 if (LI->isVolatile() != isVolatile ||
9517 LI->getParent() != PN.getIncomingBlock(i) ||
9518 !isSafeToSinkLoad(LI))
9519 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009520
Chris Lattner71042962008-07-08 17:18:32 +00009521 // If the PHI is of volatile loads and the load block has multiple
9522 // successors, sinking it would remove a load of the volatile value from
9523 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +00009524 if (isVolatile &&
9525 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9526 return 0;
9527
9528
Chris Lattnerbac32862004-11-14 19:13:23 +00009529 } else if (I->getOperand(1) != ConstantOp) {
9530 return 0;
9531 }
9532 }
9533
9534 // Okay, they are all the same operation. Create a new PHI node of the
9535 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009536 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9537 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009538 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009539
9540 Value *InVal = FirstInst->getOperand(0);
9541 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009542
9543 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009544 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9545 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9546 if (NewInVal != InVal)
9547 InVal = 0;
9548 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9549 }
9550
9551 Value *PhiVal;
9552 if (InVal) {
9553 // The new PHI unions all of the same values together. This is really
9554 // common, so we handle it intelligently here for compile-time speed.
9555 PhiVal = InVal;
9556 delete NewPN;
9557 } else {
9558 InsertNewInstBefore(NewPN, PN);
9559 PhiVal = NewPN;
9560 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009561
Chris Lattnerbac32862004-11-14 19:13:23 +00009562 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009563 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009564 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009565 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009566 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009567 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009568 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009569 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009570 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9571
9572 // If this was a volatile load that we are merging, make sure to loop through
9573 // and mark all the input loads as non-volatile. If we don't do this, we will
9574 // insert a new volatile load and the old ones will not be deletable.
9575 if (isVolatile)
9576 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9577 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9578
9579 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009580}
Chris Lattnera1be5662002-05-02 17:06:02 +00009581
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009582/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9583/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009584static bool DeadPHICycle(PHINode *PN,
9585 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009586 if (PN->use_empty()) return true;
9587 if (!PN->hasOneUse()) return false;
9588
9589 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009590 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009591 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009592
9593 // Don't scan crazily complex things.
9594 if (PotentiallyDeadPHIs.size() == 16)
9595 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009596
9597 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9598 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009599
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009600 return false;
9601}
9602
Chris Lattnercf5008a2007-11-06 21:52:06 +00009603/// PHIsEqualValue - Return true if this phi node is always equal to
9604/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9605/// z = some value; x = phi (y, z); y = phi (x, z)
9606static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9607 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9608 // See if we already saw this PHI node.
9609 if (!ValueEqualPHIs.insert(PN))
9610 return true;
9611
9612 // Don't scan crazily complex things.
9613 if (ValueEqualPHIs.size() == 16)
9614 return false;
9615
9616 // Scan the operands to see if they are either phi nodes or are equal to
9617 // the value.
9618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9619 Value *Op = PN->getIncomingValue(i);
9620 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9621 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9622 return false;
9623 } else if (Op != NonPhiInVal)
9624 return false;
9625 }
9626
9627 return true;
9628}
9629
9630
Chris Lattner473945d2002-05-06 18:06:38 +00009631// PHINode simplification
9632//
Chris Lattner7e708292002-06-25 16:13:24 +00009633Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009634 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009635 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009636
Owen Anderson7e057142006-07-10 22:03:18 +00009637 if (Value *V = PN.hasConstantValue())
9638 return ReplaceInstUsesWith(PN, V);
9639
Owen Anderson7e057142006-07-10 22:03:18 +00009640 // If all PHI operands are the same operation, pull them through the PHI,
9641 // reducing code size.
9642 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9643 PN.getIncomingValue(0)->hasOneUse())
9644 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9645 return Result;
9646
9647 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9648 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9649 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009650 if (PN.hasOneUse()) {
9651 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9652 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009653 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009654 PotentiallyDeadPHIs.insert(&PN);
9655 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9656 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9657 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009658
9659 // If this phi has a single use, and if that use just computes a value for
9660 // the next iteration of a loop, delete the phi. This occurs with unused
9661 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9662 // common case here is good because the only other things that catch this
9663 // are induction variable analysis (sometimes) and ADCE, which is only run
9664 // late.
9665 if (PHIUser->hasOneUse() &&
9666 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9667 PHIUser->use_back() == &PN) {
9668 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9669 }
9670 }
Owen Anderson7e057142006-07-10 22:03:18 +00009671
Chris Lattnercf5008a2007-11-06 21:52:06 +00009672 // We sometimes end up with phi cycles that non-obviously end up being the
9673 // same value, for example:
9674 // z = some value; x = phi (y, z); y = phi (x, z)
9675 // where the phi nodes don't necessarily need to be in the same block. Do a
9676 // quick check to see if the PHI node only contains a single non-phi value, if
9677 // so, scan to see if the phi cycle is actually equal to that value.
9678 {
9679 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9680 // Scan for the first non-phi operand.
9681 while (InValNo != NumOperandVals &&
9682 isa<PHINode>(PN.getIncomingValue(InValNo)))
9683 ++InValNo;
9684
9685 if (InValNo != NumOperandVals) {
9686 Value *NonPhiInVal = PN.getOperand(InValNo);
9687
9688 // Scan the rest of the operands to see if there are any conflicts, if so
9689 // there is no need to recursively scan other phis.
9690 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9691 Value *OpVal = PN.getIncomingValue(InValNo);
9692 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9693 break;
9694 }
9695
9696 // If we scanned over all operands, then we have one unique value plus
9697 // phi values. Scan PHI nodes to see if they all merge in each other or
9698 // the value.
9699 if (InValNo == NumOperandVals) {
9700 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9701 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9702 return ReplaceInstUsesWith(PN, NonPhiInVal);
9703 }
9704 }
9705 }
Chris Lattner60921c92003-12-19 05:58:40 +00009706 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009707}
9708
Reid Spencer17212df2006-12-12 09:18:51 +00009709static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9710 Instruction *InsertPoint,
9711 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009712 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9713 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009714 // We must cast correctly to the pointer type. Ensure that we
9715 // sign extend the integer value if it is smaller as this is
9716 // used for address computation.
9717 Instruction::CastOps opcode =
9718 (VTySize < PtrSize ? Instruction::SExt :
9719 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9720 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009721}
9722
Chris Lattnera1be5662002-05-02 17:06:02 +00009723
Chris Lattner7e708292002-06-25 16:13:24 +00009724Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009725 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009726 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009727 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009728 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009729 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009730
Chris Lattnere87597f2004-10-16 18:11:37 +00009731 if (isa<UndefValue>(GEP.getOperand(0)))
9732 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9733
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009734 bool HasZeroPointerIndex = false;
9735 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9736 HasZeroPointerIndex = C->isNullValue();
9737
9738 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009739 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009740
Chris Lattner28977af2004-04-05 01:30:19 +00009741 // Eliminate unneeded casts for indices.
9742 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009743
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009744 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009745 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9746 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009747 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009748 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009749 if (CI->getOpcode() == Instruction::ZExt ||
9750 CI->getOpcode() == Instruction::SExt) {
9751 const Type *SrcTy = CI->getOperand(0)->getType();
9752 // We can eliminate a cast from i32 to i64 iff the target
9753 // is a 32-bit pointer target.
9754 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9755 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009756 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009757 }
9758 }
9759 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009760 // If we are using a wider index than needed for this platform, shrink it
9761 // to what we need. If the incoming value needs a cast instruction,
9762 // insert it. This explicit cast can make subsequent optimizations more
9763 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009764 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009765 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009766 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009767 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009768 MadeChange = true;
9769 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009770 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9771 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009772 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009773 MadeChange = true;
9774 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009775 }
Chris Lattner28977af2004-04-05 01:30:19 +00009776 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009777 }
Chris Lattner28977af2004-04-05 01:30:19 +00009778 if (MadeChange) return &GEP;
9779
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009780 // If this GEP instruction doesn't move the pointer, and if the input operand
9781 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9782 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009783 if (GEP.hasAllZeroIndices()) {
9784 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9785 // If the bitcast is of an allocation, and the allocation will be
9786 // converted to match the type of the cast, don't touch this.
9787 if (isa<AllocationInst>(BCI->getOperand(0))) {
9788 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009789 if (Instruction *I = visitBitCast(*BCI)) {
9790 if (I != BCI) {
9791 I->takeName(BCI);
9792 BCI->getParent()->getInstList().insert(BCI, I);
9793 ReplaceInstUsesWith(*BCI, I);
9794 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009795 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009796 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009797 }
9798 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9799 }
9800 }
9801
Chris Lattner90ac28c2002-08-02 19:29:35 +00009802 // Combine Indices - If the source pointer to this getelementptr instruction
9803 // is a getelementptr instruction, combine the indices of the two
9804 // getelementptr instructions into a single instruction.
9805 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009806 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009807 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009808 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009809
9810 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009811 // Note that if our source is a gep chain itself that we wait for that
9812 // chain to be resolved before we perform this transformation. This
9813 // avoids us creating a TON of code in some cases.
9814 //
9815 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9816 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9817 return 0; // Wait until our source is folded to completion.
9818
Chris Lattner72588fc2007-02-15 22:48:32 +00009819 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009820
9821 // Find out whether the last index in the source GEP is a sequential idx.
9822 bool EndsWithSequential = false;
9823 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9824 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009825 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009826
Chris Lattner90ac28c2002-08-02 19:29:35 +00009827 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009828 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009829 // Replace: gep (gep %P, long B), long A, ...
9830 // With: T = long A+B; gep %P, T, ...
9831 //
Chris Lattner620ce142004-05-07 22:09:22 +00009832 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009833 if (SO1 == Constant::getNullValue(SO1->getType())) {
9834 Sum = GO1;
9835 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9836 Sum = SO1;
9837 } else {
9838 // If they aren't the same type, convert both to an integer of the
9839 // target's pointer size.
9840 if (SO1->getType() != GO1->getType()) {
9841 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009842 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009843 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009844 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009845 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009846 unsigned PS = TD->getPointerSizeInBits();
9847 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009848 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009849 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009850
Duncan Sands514ab342007-11-01 20:53:16 +00009851 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009852 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009853 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009854 } else {
9855 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009856 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9857 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009858 }
9859 }
9860 }
Chris Lattner620ce142004-05-07 22:09:22 +00009861 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9862 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9863 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009864 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009865 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009866 }
Chris Lattner28977af2004-04-05 01:30:19 +00009867 }
Chris Lattner620ce142004-05-07 22:09:22 +00009868
9869 // Recycle the GEP we already have if possible.
9870 if (SrcGEPOperands.size() == 2) {
9871 GEP.setOperand(0, SrcGEPOperands[0]);
9872 GEP.setOperand(1, Sum);
9873 return &GEP;
9874 } else {
9875 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9876 SrcGEPOperands.end()-1);
9877 Indices.push_back(Sum);
9878 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9879 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009880 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009881 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009882 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009883 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009884 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9885 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009886 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9887 }
9888
9889 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009890 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9891 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009892
Chris Lattner620ce142004-05-07 22:09:22 +00009893 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009894 // GEP of global variable. If all of the indices for this GEP are
9895 // constants, we can promote this to a constexpr instead of an instruction.
9896
9897 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009898 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009899 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9900 for (; I != E && isa<Constant>(*I); ++I)
9901 Indices.push_back(cast<Constant>(*I));
9902
9903 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009904 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9905 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009906
9907 // Replace all uses of the GEP with the new constexpr...
9908 return ReplaceInstUsesWith(GEP, CE);
9909 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009910 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009911 if (!isa<PointerType>(X->getType())) {
9912 // Not interesting. Source pointer must be a cast from pointer.
9913 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009914 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9915 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009916 //
9917 // This occurs when the program declares an array extern like "int X[];"
9918 //
9919 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9920 const PointerType *XTy = cast<PointerType>(X->getType());
9921 if (const ArrayType *XATy =
9922 dyn_cast<ArrayType>(XTy->getElementType()))
9923 if (const ArrayType *CATy =
9924 dyn_cast<ArrayType>(CPTy->getElementType()))
9925 if (CATy->getElementType() == XATy->getElementType()) {
9926 // At this point, we know that the cast source type is a pointer
9927 // to an array of the same type as the destination pointer
9928 // array. Because the array type is never stepped over (there
9929 // is a leading zero) we can fold the cast into this GEP.
9930 GEP.setOperand(0, X);
9931 return &GEP;
9932 }
9933 } else if (GEP.getNumOperands() == 2) {
9934 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009935 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9936 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009937 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9938 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9939 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009940 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9941 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009942 Value *Idx[2];
9943 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9944 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009945 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009946 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009947 // V and GEP are both pointer types --> BitCast
9948 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009949 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009950
9951 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009952 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009953 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009954 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009955
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009956 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009957 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009958 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009959
9960 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9961 // allow either a mul, shift, or constant here.
9962 Value *NewIdx = 0;
9963 ConstantInt *Scale = 0;
9964 if (ArrayEltSize == 1) {
9965 NewIdx = GEP.getOperand(1);
9966 Scale = ConstantInt::get(NewIdx->getType(), 1);
9967 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009968 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009969 Scale = CI;
9970 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9971 if (Inst->getOpcode() == Instruction::Shl &&
9972 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009973 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9974 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9975 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009976 NewIdx = Inst->getOperand(0);
9977 } else if (Inst->getOpcode() == Instruction::Mul &&
9978 isa<ConstantInt>(Inst->getOperand(1))) {
9979 Scale = cast<ConstantInt>(Inst->getOperand(1));
9980 NewIdx = Inst->getOperand(0);
9981 }
9982 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009983
Chris Lattner7835cdd2005-09-13 18:36:04 +00009984 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009985 // out, perform the transformation. Note, we don't know whether Scale is
9986 // signed or not. We'll use unsigned version of division/modulo
9987 // operation after making sure Scale doesn't have the sign bit set.
9988 if (Scale && Scale->getSExtValue() >= 0LL &&
9989 Scale->getZExtValue() % ArrayEltSize == 0) {
9990 Scale = ConstantInt::get(Scale->getType(),
9991 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009992 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009993 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009994 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009995 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009996 NewIdx = InsertNewInstBefore(Sc, GEP);
9997 }
9998
9999 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010000 Value *Idx[2];
10001 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10002 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010003 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010004 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010005 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10006 // The NewGEP must be pointer typed, so must the old one -> BitCast
10007 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010008 }
10009 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010010 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010011 }
10012
Chris Lattner8a2a3112001-12-14 16:52:21 +000010013 return 0;
10014}
10015
Chris Lattner0864acf2002-11-04 16:18:53 +000010016Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10017 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010018 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010019 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10020 const Type *NewTy =
10021 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010022 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010023
10024 // Create and insert the replacement instruction...
10025 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010026 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010027 else {
10028 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010029 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010030 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010031
10032 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010033
Chris Lattner0864acf2002-11-04 16:18:53 +000010034 // Scan to the end of the allocation instructions, to skip over a block of
10035 // allocas if possible...
10036 //
10037 BasicBlock::iterator It = New;
10038 while (isa<AllocationInst>(*It)) ++It;
10039
10040 // Now that I is pointing to the first non-allocation-inst in the block,
10041 // insert our getelementptr instruction...
10042 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010043 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010044 Value *Idx[2];
10045 Idx[0] = NullIdx;
10046 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010047 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10048 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010049
10050 // Now make everything use the getelementptr instead of the original
10051 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010052 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010053 } else if (isa<UndefValue>(AI.getArraySize())) {
10054 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010055 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010056 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010057
10058 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10059 // Note that we only do this for alloca's, because malloc should allocate and
10060 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010061 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010062 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010063 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10064
Chris Lattner0864acf2002-11-04 16:18:53 +000010065 return 0;
10066}
10067
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010068Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10069 Value *Op = FI.getOperand(0);
10070
Chris Lattner17be6352004-10-18 02:59:09 +000010071 // free undef -> unreachable.
10072 if (isa<UndefValue>(Op)) {
10073 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010074 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010075 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010076 return EraseInstFromFunction(FI);
10077 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010078
Chris Lattner6160e852004-02-28 04:57:37 +000010079 // If we have 'free null' delete the instruction. This can happen in stl code
10080 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010081 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010082 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010083
10084 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10085 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10086 FI.setOperand(0, CI->getOperand(0));
10087 return &FI;
10088 }
10089
10090 // Change free (gep X, 0,0,0,0) into free(X)
10091 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10092 if (GEPI->hasAllZeroIndices()) {
10093 AddToWorkList(GEPI);
10094 FI.setOperand(0, GEPI->getOperand(0));
10095 return &FI;
10096 }
10097 }
10098
10099 // Change free(malloc) into nothing, if the malloc has a single use.
10100 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10101 if (MI->hasOneUse()) {
10102 EraseInstFromFunction(FI);
10103 return EraseInstFromFunction(*MI);
10104 }
Chris Lattner6160e852004-02-28 04:57:37 +000010105
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010106 return 0;
10107}
10108
10109
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010110/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010111static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010112 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010113 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010114 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010115
Devang Patel99db6ad2007-10-18 19:52:32 +000010116 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10117 // Instead of loading constant c string, use corresponding integer value
10118 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010119 std::string Str;
10120 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010121 unsigned len = Str.length();
10122 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10123 unsigned numBits = Ty->getPrimitiveSizeInBits();
10124 // Replace LI with immediate integer store.
10125 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010126 APInt StrVal(numBits, 0);
10127 APInt SingleChar(numBits, 0);
10128 if (TD->isLittleEndian()) {
10129 for (signed i = len-1; i >= 0; i--) {
10130 SingleChar = (uint64_t) Str[i];
10131 StrVal = (StrVal << 8) | SingleChar;
10132 }
10133 } else {
10134 for (unsigned i = 0; i < len; i++) {
10135 SingleChar = (uint64_t) Str[i];
10136 StrVal = (StrVal << 8) | SingleChar;
10137 }
10138 // Append NULL at the end.
10139 SingleChar = 0;
10140 StrVal = (StrVal << 8) | SingleChar;
10141 }
10142 Value *NL = ConstantInt::get(StrVal);
10143 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010144 }
10145 }
10146 }
10147
Chris Lattnerb89e0712004-07-13 01:49:43 +000010148 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010149 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010150 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010151
Reid Spencer42230162007-01-22 05:51:25 +000010152 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010153 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010154 // If the source is an array, the code below will not succeed. Check to
10155 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10156 // constants.
10157 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10158 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10159 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010160 Value *Idxs[2];
10161 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10162 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010163 SrcTy = cast<PointerType>(CastOp->getType());
10164 SrcPTy = SrcTy->getElementType();
10165 }
10166
Reid Spencer42230162007-01-22 05:51:25 +000010167 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010168 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010169 // Do not allow turning this into a load of an integer, which is then
10170 // casted to a pointer, this pessimizes pointer analysis a lot.
10171 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010172 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10173 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010174
Chris Lattnerf9527852005-01-31 04:50:46 +000010175 // Okay, we are casting from one integer or pointer type to another of
10176 // the same size. Instead of casting the pointer before the load, cast
10177 // the result of the loaded value.
10178 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10179 CI->getName(),
10180 LI.isVolatile()),LI);
10181 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010182 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010183 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010184 }
10185 }
10186 return 0;
10187}
10188
Chris Lattnerc10aced2004-09-19 18:43:46 +000010189/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010190/// from this value cannot trap. If it is not obviously safe to load from the
10191/// specified pointer, we do a quick local scan of the basic block containing
10192/// ScanFrom, to determine if the address is already accessed.
10193static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010194 // If it is an alloca it is always safe to load from.
10195 if (isa<AllocaInst>(V)) return true;
10196
Duncan Sands46318cd2007-09-19 10:25:38 +000010197 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010198 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010199 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010200 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010201
10202 // Otherwise, be a little bit agressive by scanning the local block where we
10203 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010204 // from/to. If so, the previous load or store would have already trapped,
10205 // so there is no harm doing an extra load (also, CSE will later eliminate
10206 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010207 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10208
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010209 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010210 --BBI;
10211
Chris Lattner2de3fec2008-06-20 05:12:56 +000010212 // If we see a free or a call (which might do a free) the pointer could be
10213 // marked invalid.
10214 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10215 return false;
10216
Chris Lattner8a375202004-09-19 19:18:10 +000010217 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10218 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010219 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000010220 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010221 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010222
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010223 }
Chris Lattner8a375202004-09-19 19:18:10 +000010224 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010225}
10226
Chris Lattner8d2e8882007-08-11 18:48:48 +000010227/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10228/// until we find the underlying object a pointer is referring to or something
10229/// we don't understand. Note that the returned pointer may be offset from the
10230/// input, because we ignore GEP indices.
10231static Value *GetUnderlyingObject(Value *Ptr) {
10232 while (1) {
10233 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10234 if (CE->getOpcode() == Instruction::BitCast ||
10235 CE->getOpcode() == Instruction::GetElementPtr)
10236 Ptr = CE->getOperand(0);
10237 else
10238 return Ptr;
10239 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10240 Ptr = BCI->getOperand(0);
10241 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10242 Ptr = GEP->getOperand(0);
10243 } else {
10244 return Ptr;
10245 }
10246 }
10247}
10248
Chris Lattner833b8a42003-06-26 05:06:25 +000010249Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10250 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010251
Dan Gohman9941f742007-07-20 16:34:21 +000010252 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010253 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10254 if (KnownAlign >
10255 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10256 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010257 LI.setAlignment(KnownAlign);
10258
Chris Lattner37366c12005-05-01 04:24:53 +000010259 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010260 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010261 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010262 return Res;
10263
10264 // None of the following transforms are legal for volatile loads.
10265 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010266
Chris Lattner62f254d2005-09-12 22:00:15 +000010267 if (&LI.getParent()->front() != &LI) {
10268 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010269 // If the instruction immediately before this is a store to the same
10270 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010271 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10272 if (SI->getOperand(1) == LI.getOperand(0))
10273 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010274 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10275 if (LIB->getOperand(0) == LI.getOperand(0))
10276 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010277 }
Chris Lattner37366c12005-05-01 04:24:53 +000010278
Christopher Lambb15147e2007-12-29 07:56:53 +000010279 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10280 const Value *GEPI0 = GEPI->getOperand(0);
10281 // TODO: Consider a target hook for valid address spaces for this xform.
10282 if (isa<ConstantPointerNull>(GEPI0) &&
10283 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010284 // Insert a new store to null instruction before the load to indicate
10285 // that this code is not reachable. We do this instead of inserting
10286 // an unreachable instruction directly because we cannot modify the
10287 // CFG.
10288 new StoreInst(UndefValue::get(LI.getType()),
10289 Constant::getNullValue(Op->getType()), &LI);
10290 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10291 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010292 }
Chris Lattner37366c12005-05-01 04:24:53 +000010293
Chris Lattnere87597f2004-10-16 18:11:37 +000010294 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010295 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010296 // TODO: Consider a target hook for valid address spaces for this xform.
10297 if (isa<UndefValue>(C) || (C->isNullValue() &&
10298 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010299 // Insert a new store to null instruction before the load to indicate that
10300 // this code is not reachable. We do this instead of inserting an
10301 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010302 new StoreInst(UndefValue::get(LI.getType()),
10303 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010304 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010305 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010306
Chris Lattnere87597f2004-10-16 18:11:37 +000010307 // Instcombine load (constant global) into the value loaded.
10308 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010309 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010310 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010311
Chris Lattnere87597f2004-10-16 18:11:37 +000010312 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010314 if (CE->getOpcode() == Instruction::GetElementPtr) {
10315 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010316 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010317 if (Constant *V =
10318 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010319 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010320 if (CE->getOperand(0)->isNullValue()) {
10321 // Insert a new store to null instruction before the load to indicate
10322 // that this code is not reachable. We do this instead of inserting
10323 // an unreachable instruction directly because we cannot modify the
10324 // CFG.
10325 new StoreInst(UndefValue::get(LI.getType()),
10326 Constant::getNullValue(Op->getType()), &LI);
10327 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10328 }
10329
Reid Spencer3da59db2006-11-27 01:05:10 +000010330 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010331 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010332 return Res;
10333 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010334 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010335 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010336
10337 // If this load comes from anywhere in a constant global, and if the global
10338 // is all undef or zero, we know what it loads.
10339 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10340 if (GV->isConstant() && GV->hasInitializer()) {
10341 if (GV->getInitializer()->isNullValue())
10342 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10343 else if (isa<UndefValue>(GV->getInitializer()))
10344 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10345 }
10346 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010347
Chris Lattner37366c12005-05-01 04:24:53 +000010348 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010349 // Change select and PHI nodes to select values instead of addresses: this
10350 // helps alias analysis out a lot, allows many others simplifications, and
10351 // exposes redundancy in the code.
10352 //
10353 // Note that we cannot do the transformation unless we know that the
10354 // introduced loads cannot trap! Something like this is valid as long as
10355 // the condition is always false: load (select bool %C, int* null, int* %G),
10356 // but it would not be valid if we transformed it to load from null
10357 // unconditionally.
10358 //
10359 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10360 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010361 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10362 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010363 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010364 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010365 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010366 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010367 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010368 }
10369
Chris Lattner684fe212004-09-23 15:46:00 +000010370 // load (select (cond, null, P)) -> load P
10371 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10372 if (C->isNullValue()) {
10373 LI.setOperand(0, SI->getOperand(2));
10374 return &LI;
10375 }
10376
10377 // load (select (cond, P, null)) -> load P
10378 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10379 if (C->isNullValue()) {
10380 LI.setOperand(0, SI->getOperand(1));
10381 return &LI;
10382 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010383 }
10384 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010385 return 0;
10386}
10387
Reid Spencer55af2b52007-01-19 21:20:31 +000010388/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010389/// when possible.
10390static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10391 User *CI = cast<User>(SI.getOperand(1));
10392 Value *CastOp = CI->getOperand(0);
10393
10394 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10395 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10396 const Type *SrcPTy = SrcTy->getElementType();
10397
Reid Spencer42230162007-01-22 05:51:25 +000010398 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010399 // If the source is an array, the code below will not succeed. Check to
10400 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10401 // constants.
10402 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10403 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10404 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010405 Value* Idxs[2];
10406 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10407 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010408 SrcTy = cast<PointerType>(CastOp->getType());
10409 SrcPTy = SrcTy->getElementType();
10410 }
10411
Reid Spencer67f827c2007-01-20 23:35:48 +000010412 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10413 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10414 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010415
10416 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010417 // the same size. Instead of casting the pointer before
10418 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010419 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010420 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010421 Instruction::CastOps opcode = Instruction::BitCast;
10422 const Type* CastSrcTy = SIOp0->getType();
10423 const Type* CastDstTy = SrcPTy;
10424 if (isa<PointerType>(CastDstTy)) {
10425 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010426 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010427 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010428 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010429 opcode = Instruction::PtrToInt;
10430 }
10431 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010432 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010433 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010434 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010435 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010436 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010437 return new StoreInst(NewCast, CastOp);
10438 }
10439 }
10440 }
10441 return 0;
10442}
10443
Chris Lattner2f503e62005-01-31 05:36:43 +000010444Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10445 Value *Val = SI.getOperand(0);
10446 Value *Ptr = SI.getOperand(1);
10447
10448 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010449 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010450 ++NumCombined;
10451 return 0;
10452 }
Chris Lattner836692d2007-01-15 06:51:56 +000010453
10454 // If the RHS is an alloca with a single use, zapify the store, making the
10455 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010456 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010457 if (isa<AllocaInst>(Ptr)) {
10458 EraseInstFromFunction(SI);
10459 ++NumCombined;
10460 return 0;
10461 }
10462
10463 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10464 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10465 GEP->getOperand(0)->hasOneUse()) {
10466 EraseInstFromFunction(SI);
10467 ++NumCombined;
10468 return 0;
10469 }
10470 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010471
Dan Gohman9941f742007-07-20 16:34:21 +000010472 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010473 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10474 if (KnownAlign >
10475 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10476 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010477 SI.setAlignment(KnownAlign);
10478
Chris Lattner9ca96412006-02-08 03:25:32 +000010479 // Do really simple DSE, to catch cases where there are several consequtive
10480 // stores to the same location, separated by a few arithmetic operations. This
10481 // situation often occurs with bitfield accesses.
10482 BasicBlock::iterator BBI = &SI;
10483 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10484 --ScanInsts) {
10485 --BBI;
10486
10487 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10488 // Prev store isn't volatile, and stores to the same location?
10489 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10490 ++NumDeadStore;
10491 ++BBI;
10492 EraseInstFromFunction(*PrevSI);
10493 continue;
10494 }
10495 break;
10496 }
10497
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010498 // If this is a load, we have to stop. However, if the loaded value is from
10499 // the pointer we're loading and is producing the pointer we're storing,
10500 // then *this* store is dead (X = load P; store X -> P).
10501 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010502 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010503 EraseInstFromFunction(SI);
10504 ++NumCombined;
10505 return 0;
10506 }
10507 // Otherwise, this is a load from some other location. Stores before it
10508 // may not be dead.
10509 break;
10510 }
10511
Chris Lattner9ca96412006-02-08 03:25:32 +000010512 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010513 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010514 break;
10515 }
10516
10517
10518 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010519
10520 // store X, null -> turns into 'unreachable' in SimplifyCFG
10521 if (isa<ConstantPointerNull>(Ptr)) {
10522 if (!isa<UndefValue>(Val)) {
10523 SI.setOperand(0, UndefValue::get(Val->getType()));
10524 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010525 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010526 ++NumCombined;
10527 }
10528 return 0; // Do not modify these!
10529 }
10530
10531 // store undef, Ptr -> noop
10532 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010533 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010534 ++NumCombined;
10535 return 0;
10536 }
10537
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010538 // If the pointer destination is a cast, see if we can fold the cast into the
10539 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010540 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010541 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10542 return Res;
10543 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010544 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010545 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10546 return Res;
10547
Chris Lattner408902b2005-09-12 23:23:25 +000010548
10549 // If this store is the last instruction in the basic block, and if the block
10550 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010551 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010552 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010553 if (BI->isUnconditional())
10554 if (SimplifyStoreAtEndOfBlock(SI))
10555 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010556
Chris Lattner2f503e62005-01-31 05:36:43 +000010557 return 0;
10558}
10559
Chris Lattner3284d1f2007-04-15 00:07:55 +000010560/// SimplifyStoreAtEndOfBlock - Turn things like:
10561/// if () { *P = v1; } else { *P = v2 }
10562/// into a phi node with a store in the successor.
10563///
Chris Lattner31755a02007-04-15 01:02:18 +000010564/// Simplify things like:
10565/// *P = v1; if () { *P = v2; }
10566/// into a phi node with a store in the successor.
10567///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010568bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10569 BasicBlock *StoreBB = SI.getParent();
10570
10571 // Check to see if the successor block has exactly two incoming edges. If
10572 // so, see if the other predecessor contains a store to the same location.
10573 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010574 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010575
10576 // Determine whether Dest has exactly two predecessors and, if so, compute
10577 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010578 pred_iterator PI = pred_begin(DestBB);
10579 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010580 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010581 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010582 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010583 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010584 return false;
10585
10586 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010587 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010588 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010589 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010590 }
Chris Lattner31755a02007-04-15 01:02:18 +000010591 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010592 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000010593
10594 // Bail out if all the relevant blocks aren't distinct (this can happen,
10595 // for example, if SI is in an infinite loop)
10596 if (StoreBB == DestBB || OtherBB == DestBB)
10597 return false;
10598
Chris Lattner31755a02007-04-15 01:02:18 +000010599 // Verify that the other block ends in a branch and is not otherwise empty.
10600 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010601 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010602 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010603 return false;
10604
Chris Lattner31755a02007-04-15 01:02:18 +000010605 // If the other block ends in an unconditional branch, check for the 'if then
10606 // else' case. there is an instruction before the branch.
10607 StoreInst *OtherStore = 0;
10608 if (OtherBr->isUnconditional()) {
10609 // If this isn't a store, or isn't a store to the same location, bail out.
10610 --BBI;
10611 OtherStore = dyn_cast<StoreInst>(BBI);
10612 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10613 return false;
10614 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010615 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010616 // destinations is StoreBB, then we have the if/then case.
10617 if (OtherBr->getSuccessor(0) != StoreBB &&
10618 OtherBr->getSuccessor(1) != StoreBB)
10619 return false;
10620
10621 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010622 // if/then triangle. See if there is a store to the same ptr as SI that
10623 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010624 for (;; --BBI) {
10625 // Check to see if we find the matching store.
10626 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10627 if (OtherStore->getOperand(1) != SI.getOperand(1))
10628 return false;
10629 break;
10630 }
Eli Friedman6903a242008-06-13 22:02:12 +000010631 // If we find something that may be using or overwriting the stored
10632 // value, or if we run out of instructions, we can't do the xform.
10633 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000010634 BBI == OtherBB->begin())
10635 return false;
10636 }
10637
10638 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000010639 // make sure nothing reads or overwrites the stored value in
10640 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010641 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10642 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000010643 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000010644 return false;
10645 }
10646 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010647
Chris Lattner31755a02007-04-15 01:02:18 +000010648 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010649 Value *MergedVal = OtherStore->getOperand(0);
10650 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010651 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010652 PN->reserveOperandSpace(2);
10653 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010654 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10655 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010656 }
10657
10658 // Advance to a place where it is safe to insert the new store and
10659 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010660 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010661 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10662 OtherStore->isVolatile()), *BBI);
10663
10664 // Nuke the old stores.
10665 EraseInstFromFunction(SI);
10666 EraseInstFromFunction(*OtherStore);
10667 ++NumCombined;
10668 return true;
10669}
10670
Chris Lattner2f503e62005-01-31 05:36:43 +000010671
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010672Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10673 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010674 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010675 BasicBlock *TrueDest;
10676 BasicBlock *FalseDest;
10677 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10678 !isa<Constant>(X)) {
10679 // Swap Destinations and condition...
10680 BI.setCondition(X);
10681 BI.setSuccessor(0, FalseDest);
10682 BI.setSuccessor(1, TrueDest);
10683 return &BI;
10684 }
10685
Reid Spencere4d87aa2006-12-23 06:05:41 +000010686 // Cannonicalize fcmp_one -> fcmp_oeq
10687 FCmpInst::Predicate FPred; Value *Y;
10688 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10689 TrueDest, FalseDest)))
10690 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10691 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10692 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010693 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010694 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10695 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010696 // Swap Destinations and condition...
10697 BI.setCondition(NewSCC);
10698 BI.setSuccessor(0, FalseDest);
10699 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010700 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010701 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010702 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010703 return &BI;
10704 }
10705
10706 // Cannonicalize icmp_ne -> icmp_eq
10707 ICmpInst::Predicate IPred;
10708 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10709 TrueDest, FalseDest)))
10710 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10711 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10712 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10713 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010714 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010715 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10716 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010717 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010718 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010719 BI.setSuccessor(0, FalseDest);
10720 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010721 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010722 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010723 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010724 return &BI;
10725 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010726
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010727 return 0;
10728}
Chris Lattner0864acf2002-11-04 16:18:53 +000010729
Chris Lattner46238a62004-07-03 00:26:11 +000010730Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10731 Value *Cond = SI.getCondition();
10732 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10733 if (I->getOpcode() == Instruction::Add)
10734 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10735 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10736 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010737 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010738 AddRHS));
10739 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010740 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010741 return &SI;
10742 }
10743 }
10744 return 0;
10745}
10746
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010747Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000010748 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010749
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000010750 if (!EV.hasIndices())
10751 return ReplaceInstUsesWith(EV, Agg);
10752
10753 if (Constant *C = dyn_cast<Constant>(Agg)) {
10754 if (isa<UndefValue>(C))
10755 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10756
10757 if (isa<ConstantAggregateZero>(C))
10758 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10759
10760 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10761 // Extract the element indexed by the first index out of the constant
10762 Value *V = C->getOperand(*EV.idx_begin());
10763 if (EV.getNumIndices() > 1)
10764 // Extract the remaining indices out of the constant indexed by the
10765 // first index
10766 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10767 else
10768 return ReplaceInstUsesWith(EV, V);
10769 }
10770 return 0; // Can't handle other constants
10771 }
10772 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10773 // We're extracting from an insertvalue instruction, compare the indices
10774 const unsigned *exti, *exte, *insi, *inse;
10775 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10776 exte = EV.idx_end(), inse = IV->idx_end();
10777 exti != exte && insi != inse;
10778 ++exti, ++insi) {
10779 if (*insi != *exti)
10780 // The insert and extract both reference distinctly different elements.
10781 // This means the extract is not influenced by the insert, and we can
10782 // replace the aggregate operand of the extract with the aggregate
10783 // operand of the insert. i.e., replace
10784 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10785 // %E = extractvalue { i32, { i32 } } %I, 0
10786 // with
10787 // %E = extractvalue { i32, { i32 } } %A, 0
10788 return ExtractValueInst::Create(IV->getAggregateOperand(),
10789 EV.idx_begin(), EV.idx_end());
10790 }
10791 if (exti == exte && insi == inse)
10792 // Both iterators are at the end: Index lists are identical. Replace
10793 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10794 // %C = extractvalue { i32, { i32 } } %B, 1, 0
10795 // with "i32 42"
10796 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10797 if (exti == exte) {
10798 // The extract list is a prefix of the insert list. i.e. replace
10799 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10800 // %E = extractvalue { i32, { i32 } } %I, 1
10801 // with
10802 // %X = extractvalue { i32, { i32 } } %A, 1
10803 // %E = insertvalue { i32 } %X, i32 42, 0
10804 // by switching the order of the insert and extract (though the
10805 // insertvalue should be left in, since it may have other uses).
10806 Value *NewEV = InsertNewInstBefore(
10807 ExtractValueInst::Create(IV->getAggregateOperand(),
10808 EV.idx_begin(), EV.idx_end()),
10809 EV);
10810 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10811 insi, inse);
10812 }
10813 if (insi == inse)
10814 // The insert list is a prefix of the extract list
10815 // We can simply remove the common indices from the extract and make it
10816 // operate on the inserted value instead of the insertvalue result.
10817 // i.e., replace
10818 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10819 // %E = extractvalue { i32, { i32 } } %I, 1, 0
10820 // with
10821 // %E extractvalue { i32 } { i32 42 }, 0
10822 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
10823 exti, exte);
10824 }
10825 // Can't simplify extracts from other values. Note that nested extracts are
10826 // already simplified implicitely by the above (extract ( extract (insert) )
10827 // will be translated into extract ( insert ( extract ) ) first and then just
10828 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010829 return 0;
10830}
10831
Chris Lattner220b0cf2006-03-05 00:22:33 +000010832/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10833/// is to leave as a vector operation.
10834static bool CheapToScalarize(Value *V, bool isConstant) {
10835 if (isa<ConstantAggregateZero>(V))
10836 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010837 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010838 if (isConstant) return true;
10839 // If all elts are the same, we can extract.
10840 Constant *Op0 = C->getOperand(0);
10841 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10842 if (C->getOperand(i) != Op0)
10843 return false;
10844 return true;
10845 }
10846 Instruction *I = dyn_cast<Instruction>(V);
10847 if (!I) return false;
10848
10849 // Insert element gets simplified to the inserted element or is deleted if
10850 // this is constant idx extract element and its a constant idx insertelt.
10851 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10852 isa<ConstantInt>(I->getOperand(2)))
10853 return true;
10854 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10855 return true;
10856 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10857 if (BO->hasOneUse() &&
10858 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10859 CheapToScalarize(BO->getOperand(1), isConstant)))
10860 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010861 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10862 if (CI->hasOneUse() &&
10863 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10864 CheapToScalarize(CI->getOperand(1), isConstant)))
10865 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010866
10867 return false;
10868}
10869
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010870/// Read and decode a shufflevector mask.
10871///
10872/// It turns undef elements into values that are larger than the number of
10873/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010874static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10875 unsigned NElts = SVI->getType()->getNumElements();
10876 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10877 return std::vector<unsigned>(NElts, 0);
10878 if (isa<UndefValue>(SVI->getOperand(2)))
10879 return std::vector<unsigned>(NElts, 2*NElts);
10880
10881 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010882 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000010883 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10884 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000010885 Result.push_back(NElts*2); // undef -> 8
10886 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000010887 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010888 return Result;
10889}
10890
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010891/// FindScalarElement - Given a vector and an element number, see if the scalar
10892/// value is already around as a register, for example if it were inserted then
10893/// extracted from the vector.
10894static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010895 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10896 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010897 unsigned Width = PTy->getNumElements();
10898 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010899 return UndefValue::get(PTy->getElementType());
10900
10901 if (isa<UndefValue>(V))
10902 return UndefValue::get(PTy->getElementType());
10903 else if (isa<ConstantAggregateZero>(V))
10904 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010905 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010906 return CP->getOperand(EltNo);
10907 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10908 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010909 if (!isa<ConstantInt>(III->getOperand(2)))
10910 return 0;
10911 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010912
10913 // If this is an insert to the element we are looking for, return the
10914 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010915 if (EltNo == IIElt)
10916 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010917
10918 // Otherwise, the insertelement doesn't modify the value, recurse on its
10919 // vector input.
10920 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010921 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010922 unsigned InEl = getShuffleMask(SVI)[EltNo];
10923 if (InEl < Width)
10924 return FindScalarElement(SVI->getOperand(0), InEl);
10925 else if (InEl < Width*2)
10926 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10927 else
10928 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010929 }
10930
10931 // Otherwise, we don't know.
10932 return 0;
10933}
10934
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010935Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010936 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010937 if (isa<UndefValue>(EI.getOperand(0)))
10938 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10939
Dan Gohman07a96762007-07-16 14:29:03 +000010940 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010941 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10942 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10943
Reid Spencer9d6565a2007-02-15 02:26:10 +000010944 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010945 // If vector val is constant with all elements the same, replace EI with
10946 // that element. When the elements are not identical, we cannot replace yet
10947 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010948 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010949 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010950 if (C->getOperand(i) != op0) {
10951 op0 = 0;
10952 break;
10953 }
10954 if (op0)
10955 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010956 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010957
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010958 // If extracting a specified index from the vector, see if we can recursively
10959 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010960 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010961 unsigned IndexVal = IdxC->getZExtValue();
10962 unsigned VectorWidth =
10963 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10964
10965 // If this is extracting an invalid index, turn this into undef, to avoid
10966 // crashing the code below.
10967 if (IndexVal >= VectorWidth)
10968 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10969
Chris Lattner867b99f2006-10-05 06:55:50 +000010970 // This instruction only demands the single element from the input vector.
10971 // If the input vector has a single use, simplify it based on this use
10972 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010973 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010974 uint64_t UndefElts;
10975 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010976 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010977 UndefElts)) {
10978 EI.setOperand(0, V);
10979 return &EI;
10980 }
10981 }
10982
Reid Spencerb83eb642006-10-20 07:07:24 +000010983 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010984 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010985
10986 // If the this extractelement is directly using a bitcast from a vector of
10987 // the same number of elements, see if we can find the source element from
10988 // it. In this case, we will end up needing to bitcast the scalars.
10989 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10990 if (const VectorType *VT =
10991 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10992 if (VT->getNumElements() == VectorWidth)
10993 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10994 return new BitCastInst(Elt, EI.getType());
10995 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010996 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010997
Chris Lattner73fa49d2006-05-25 22:53:38 +000010998 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010999 if (I->hasOneUse()) {
11000 // Push extractelement into predecessor operation if legal and
11001 // profitable to do so
11002 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011003 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11004 if (CheapToScalarize(BO, isConstantElt)) {
11005 ExtractElementInst *newEI0 =
11006 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11007 EI.getName()+".lhs");
11008 ExtractElementInst *newEI1 =
11009 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11010 EI.getName()+".rhs");
11011 InsertNewInstBefore(newEI0, EI);
11012 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011013 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011014 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011015 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011016 unsigned AS =
11017 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011018 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11019 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011020 GetElementPtrInst *GEP =
11021 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011022 InsertNewInstBefore(GEP, EI);
11023 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011024 }
11025 }
11026 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11027 // Extracting the inserted element?
11028 if (IE->getOperand(2) == EI.getOperand(1))
11029 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11030 // If the inserted and extracted elements are constants, they must not
11031 // be the same value, extract from the pre-inserted value instead.
11032 if (isa<Constant>(IE->getOperand(2)) &&
11033 isa<Constant>(EI.getOperand(1))) {
11034 AddUsesToWorkList(EI);
11035 EI.setOperand(0, IE->getOperand(0));
11036 return &EI;
11037 }
11038 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11039 // If this is extracting an element from a shufflevector, figure out where
11040 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011041 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11042 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011043 Value *Src;
11044 if (SrcIdx < SVI->getType()->getNumElements())
11045 Src = SVI->getOperand(0);
11046 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11047 SrcIdx -= SVI->getType()->getNumElements();
11048 Src = SVI->getOperand(1);
11049 } else {
11050 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011051 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011052 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011053 }
11054 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011055 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011056 return 0;
11057}
11058
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011059/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11060/// elements from either LHS or RHS, return the shuffle mask and true.
11061/// Otherwise, return false.
11062static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11063 std::vector<Constant*> &Mask) {
11064 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11065 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011066 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011067
11068 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011069 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011070 return true;
11071 } else if (V == LHS) {
11072 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011073 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011074 return true;
11075 } else if (V == RHS) {
11076 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011077 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011078 return true;
11079 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11080 // If this is an insert of an extract from some other vector, include it.
11081 Value *VecOp = IEI->getOperand(0);
11082 Value *ScalarOp = IEI->getOperand(1);
11083 Value *IdxOp = IEI->getOperand(2);
11084
Chris Lattnerd929f062006-04-27 21:14:21 +000011085 if (!isa<ConstantInt>(IdxOp))
11086 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011087 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011088
11089 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11090 // Okay, we can handle this if the vector we are insertinting into is
11091 // transitively ok.
11092 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11093 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011094 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011095 return true;
11096 }
11097 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11098 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011099 EI->getOperand(0)->getType() == V->getType()) {
11100 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011101 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011102
11103 // This must be extracting from either LHS or RHS.
11104 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11105 // Okay, we can handle this if the vector we are insertinting into is
11106 // transitively ok.
11107 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11108 // If so, update the mask to reflect the inserted value.
11109 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011110 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011111 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011112 } else {
11113 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011114 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011115 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011116
11117 }
11118 return true;
11119 }
11120 }
11121 }
11122 }
11123 }
11124 // TODO: Handle shufflevector here!
11125
11126 return false;
11127}
11128
11129/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11130/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11131/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011132static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011133 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011134 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011135 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011136 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011137 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011138
11139 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011140 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011141 return V;
11142 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011143 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011144 return V;
11145 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11146 // If this is an insert of an extract from some other vector, include it.
11147 Value *VecOp = IEI->getOperand(0);
11148 Value *ScalarOp = IEI->getOperand(1);
11149 Value *IdxOp = IEI->getOperand(2);
11150
11151 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11152 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11153 EI->getOperand(0)->getType() == V->getType()) {
11154 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011155 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11156 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011157
11158 // Either the extracted from or inserted into vector must be RHSVec,
11159 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011160 if (EI->getOperand(0) == RHS || RHS == 0) {
11161 RHS = EI->getOperand(0);
11162 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011163 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011164 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011165 return V;
11166 }
11167
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011168 if (VecOp == RHS) {
11169 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011170 // Everything but the extracted element is replaced with the RHS.
11171 for (unsigned i = 0; i != NumElts; ++i) {
11172 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011173 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011174 }
11175 return V;
11176 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011177
11178 // If this insertelement is a chain that comes from exactly these two
11179 // vectors, return the vector and the effective shuffle.
11180 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11181 return EI->getOperand(0);
11182
Chris Lattnerefb47352006-04-15 01:39:45 +000011183 }
11184 }
11185 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011186 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011187
11188 // Otherwise, can't do anything fancy. Return an identity vector.
11189 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011190 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011191 return V;
11192}
11193
11194Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11195 Value *VecOp = IE.getOperand(0);
11196 Value *ScalarOp = IE.getOperand(1);
11197 Value *IdxOp = IE.getOperand(2);
11198
Chris Lattner599ded12007-04-09 01:11:16 +000011199 // Inserting an undef or into an undefined place, remove this.
11200 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11201 ReplaceInstUsesWith(IE, VecOp);
11202
Chris Lattnerefb47352006-04-15 01:39:45 +000011203 // If the inserted element was extracted from some other vector, and if the
11204 // indexes are constant, try to turn this into a shufflevector operation.
11205 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11206 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11207 EI->getOperand(0)->getType() == IE.getType()) {
11208 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011209 unsigned ExtractedIdx =
11210 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011211 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011212
11213 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11214 return ReplaceInstUsesWith(IE, VecOp);
11215
11216 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11217 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11218
11219 // If we are extracting a value from a vector, then inserting it right
11220 // back into the same place, just use the input vector.
11221 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11222 return ReplaceInstUsesWith(IE, VecOp);
11223
11224 // We could theoretically do this for ANY input. However, doing so could
11225 // turn chains of insertelement instructions into a chain of shufflevector
11226 // instructions, and right now we do not merge shufflevectors. As such,
11227 // only do this in a situation where it is clear that there is benefit.
11228 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11229 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11230 // the values of VecOp, except then one read from EIOp0.
11231 // Build a new shuffle mask.
11232 std::vector<Constant*> Mask;
11233 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011234 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011235 else {
11236 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011237 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011238 NumVectorElts));
11239 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011240 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011241 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011242 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011243 }
11244
11245 // If this insertelement isn't used by some other insertelement, turn it
11246 // (and any insertelements it points to), into one big shuffle.
11247 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11248 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011249 Value *RHS = 0;
11250 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11251 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11252 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011253 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011254 }
11255 }
11256 }
11257
11258 return 0;
11259}
11260
11261
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011262Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11263 Value *LHS = SVI.getOperand(0);
11264 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011265 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011266
11267 bool MadeChange = false;
11268
Chris Lattner867b99f2006-10-05 06:55:50 +000011269 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011270 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011271 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11272
Chris Lattnere4929dd2007-01-05 07:36:08 +000011273 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011274 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011275 if (isa<UndefValue>(SVI.getOperand(1))) {
11276 // Scan to see if there are any references to the RHS. If so, replace them
11277 // with undef element refs and set MadeChange to true.
11278 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11279 if (Mask[i] >= e && Mask[i] != 2*e) {
11280 Mask[i] = 2*e;
11281 MadeChange = true;
11282 }
11283 }
11284
11285 if (MadeChange) {
11286 // Remap any references to RHS to use LHS.
11287 std::vector<Constant*> Elts;
11288 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11289 if (Mask[i] == 2*e)
11290 Elts.push_back(UndefValue::get(Type::Int32Ty));
11291 else
11292 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11293 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011294 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011295 }
11296 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011297
Chris Lattner863bcff2006-05-25 23:48:38 +000011298 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11299 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11300 if (LHS == RHS || isa<UndefValue>(LHS)) {
11301 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011302 // shuffle(undef,undef,mask) -> undef.
11303 return ReplaceInstUsesWith(SVI, LHS);
11304 }
11305
Chris Lattner863bcff2006-05-25 23:48:38 +000011306 // Remap any references to RHS to use LHS.
11307 std::vector<Constant*> Elts;
11308 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011309 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011310 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011311 else {
11312 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000011313 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011314 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000011315 Elts.push_back(UndefValue::get(Type::Int32Ty));
11316 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011317 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000011318 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11319 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000011320 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011321 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011322 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011323 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011324 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011325 LHS = SVI.getOperand(0);
11326 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011327 MadeChange = true;
11328 }
11329
Chris Lattner7b2e27922006-05-26 00:29:06 +000011330 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011331 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011332
Chris Lattner863bcff2006-05-25 23:48:38 +000011333 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11334 if (Mask[i] >= e*2) continue; // Ignore undef values.
11335 // Is this an identity shuffle of the LHS value?
11336 isLHSID &= (Mask[i] == i);
11337
11338 // Is this an identity shuffle of the RHS value?
11339 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011340 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011341
Chris Lattner863bcff2006-05-25 23:48:38 +000011342 // Eliminate identity shuffles.
11343 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11344 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011345
Chris Lattner7b2e27922006-05-26 00:29:06 +000011346 // If the LHS is a shufflevector itself, see if we can combine it with this
11347 // one without producing an unusual shuffle. Here we are really conservative:
11348 // we are absolutely afraid of producing a shuffle mask not in the input
11349 // program, because the code gen may not be smart enough to turn a merged
11350 // shuffle into two specific shuffles: it may produce worse code. As such,
11351 // we only merge two shuffles if the result is one of the two input shuffle
11352 // masks. In this case, merging the shuffles just removes one instruction,
11353 // which we know is safe. This is good for things like turning:
11354 // (splat(splat)) -> splat.
11355 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11356 if (isa<UndefValue>(RHS)) {
11357 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11358
11359 std::vector<unsigned> NewMask;
11360 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11361 if (Mask[i] >= 2*e)
11362 NewMask.push_back(2*e);
11363 else
11364 NewMask.push_back(LHSMask[Mask[i]]);
11365
11366 // If the result mask is equal to the src shuffle or this shuffle mask, do
11367 // the replacement.
11368 if (NewMask == LHSMask || NewMask == Mask) {
11369 std::vector<Constant*> Elts;
11370 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11371 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011372 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011373 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011374 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011375 }
11376 }
11377 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11378 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011379 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011380 }
11381 }
11382 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011383
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011384 return MadeChange ? &SVI : 0;
11385}
11386
11387
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011388
Chris Lattnerea1c4542004-12-08 23:43:58 +000011389
11390/// TryToSinkInstruction - Try to move the specified instruction from its
11391/// current block into the beginning of DestBlock, which can only happen if it's
11392/// safe to move the instruction past all of the instructions between it and the
11393/// end of its block.
11394static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11395 assert(I->hasOneUse() && "Invariants didn't hold!");
11396
Chris Lattner108e9022005-10-27 17:13:11 +000011397 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011398 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11399 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011400
Chris Lattnerea1c4542004-12-08 23:43:58 +000011401 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011402 if (isa<AllocaInst>(I) && I->getParent() ==
11403 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011404 return false;
11405
Chris Lattner96a52a62004-12-09 07:14:34 +000011406 // We can only sink load instructions if there is nothing between the load and
11407 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011408 if (I->mayReadFromMemory()) {
11409 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011410 Scan != E; ++Scan)
11411 if (Scan->mayWriteToMemory())
11412 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011413 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011414
Dan Gohman02dea8b2008-05-23 21:05:58 +000011415 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011416
Chris Lattner4bc5f802005-08-08 19:11:57 +000011417 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011418 ++NumSunkInst;
11419 return true;
11420}
11421
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011422
11423/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11424/// all reachable code to the worklist.
11425///
11426/// This has a couple of tricks to make the code faster and more powerful. In
11427/// particular, we constant fold and DCE instructions as we go, to avoid adding
11428/// them to the worklist (this significantly speeds up instcombine on code where
11429/// many instructions are dead or constant). Additionally, if we find a branch
11430/// whose condition is a known constant, we only visit the reachable successors.
11431///
11432static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011433 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011434 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011435 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000011436 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000011437 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011438
Chris Lattner2c7718a2007-03-23 19:17:18 +000011439 while (!Worklist.empty()) {
11440 BB = Worklist.back();
11441 Worklist.pop_back();
11442
11443 // We have now visited this block! If we've already been here, ignore it.
11444 if (!Visited.insert(BB)) continue;
11445
11446 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11447 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011448
Chris Lattner2c7718a2007-03-23 19:17:18 +000011449 // DCE instruction if trivially dead.
11450 if (isInstructionTriviallyDead(Inst)) {
11451 ++NumDeadInst;
11452 DOUT << "IC: DCE: " << *Inst;
11453 Inst->eraseFromParent();
11454 continue;
11455 }
11456
11457 // ConstantProp instruction if trivially constant.
11458 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11459 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11460 Inst->replaceAllUsesWith(C);
11461 ++NumConstProp;
11462 Inst->eraseFromParent();
11463 continue;
11464 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011465
Chris Lattner2c7718a2007-03-23 19:17:18 +000011466 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011467 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011468
11469 // Recursively visit successors. If this is a branch or switch on a
11470 // constant, only visit the reachable successor.
11471 TerminatorInst *TI = BB->getTerminator();
11472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11473 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11474 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011475 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011476 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011477 continue;
11478 }
11479 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11480 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11481 // See if this is an explicit destination.
11482 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11483 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011484 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011485 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011486 continue;
11487 }
11488
11489 // Otherwise it is the default destination.
11490 Worklist.push_back(SI->getSuccessor(0));
11491 continue;
11492 }
11493 }
11494
11495 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11496 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011497 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011498}
11499
Chris Lattnerec9c3582007-03-03 02:04:50 +000011500bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011501 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011502 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011503
11504 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11505 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011506
Chris Lattnerb3d59702005-07-07 20:40:38 +000011507 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011508 // Do a depth-first traversal of the function, populate the worklist with
11509 // the reachable instructions. Ignore blocks that are not reachable. Keep
11510 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011511 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011512 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011513
Chris Lattnerb3d59702005-07-07 20:40:38 +000011514 // Do a quick scan over the function. If we find any blocks that are
11515 // unreachable, remove any instructions inside of them. This prevents
11516 // the instcombine code from having to deal with some bad special cases.
11517 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11518 if (!Visited.count(BB)) {
11519 Instruction *Term = BB->getTerminator();
11520 while (Term != BB->begin()) { // Remove instrs bottom-up
11521 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011522
Bill Wendlingb7427032006-11-26 09:46:52 +000011523 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011524 ++NumDeadInst;
11525
11526 if (!I->use_empty())
11527 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11528 I->eraseFromParent();
11529 }
11530 }
11531 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011532
Chris Lattnerdbab3862007-03-02 21:28:56 +000011533 while (!Worklist.empty()) {
11534 Instruction *I = RemoveOneFromWorkList();
11535 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011536
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011537 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011538 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011539 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011540 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011541 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011542 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011543
Bill Wendlingb7427032006-11-26 09:46:52 +000011544 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011545
11546 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011547 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011548 continue;
11549 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011550
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011551 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011552 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011553 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011554
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011555 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011556 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011557 ReplaceInstUsesWith(*I, C);
11558
Chris Lattner62b14df2002-09-02 04:59:56 +000011559 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011560 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011561 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011562 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011563 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011564
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011565 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11566 // See if we can constant fold its operands.
11567 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11569 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11570 i->set(NewC);
11571 }
11572 }
11573 }
11574
Chris Lattnerea1c4542004-12-08 23:43:58 +000011575 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000011576 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011577 BasicBlock *BB = I->getParent();
11578 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11579 if (UserParent != BB) {
11580 bool UserIsSuccessor = false;
11581 // See if the user is one of our successors.
11582 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11583 if (*SI == UserParent) {
11584 UserIsSuccessor = true;
11585 break;
11586 }
11587
11588 // If the user is one of our immediate successors, and if that successor
11589 // only has us as a predecessors (we'd have to split the critical edge
11590 // otherwise), we can keep going.
11591 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11592 next(pred_begin(UserParent)) == pred_end(UserParent))
11593 // Okay, the CFG is simple enough, try to sink this instruction.
11594 Changed |= TryToSinkInstruction(I, UserParent);
11595 }
11596 }
11597
Chris Lattner8a2a3112001-12-14 16:52:21 +000011598 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011599#ifndef NDEBUG
11600 std::string OrigI;
11601#endif
11602 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011603 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011604 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011605 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011606 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011607 DOUT << "IC: Old = " << *I
11608 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011609
Chris Lattnerf523d062004-06-09 05:08:07 +000011610 // Everything uses the new instruction now.
11611 I->replaceAllUsesWith(Result);
11612
11613 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011614 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011615 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011616
Chris Lattner6934a042007-02-11 01:23:03 +000011617 // Move the name to the new instruction first.
11618 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011619
11620 // Insert the new instruction into the basic block...
11621 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011622 BasicBlock::iterator InsertPos = I;
11623
11624 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11625 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11626 ++InsertPos;
11627
11628 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011629
Chris Lattner00d51312004-05-01 23:27:23 +000011630 // Make sure that we reprocess all operands now that we reduced their
11631 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011632 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011633
Chris Lattnerf523d062004-06-09 05:08:07 +000011634 // Instructions can end up on the worklist more than once. Make sure
11635 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011636 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011637
11638 // Erase the old instruction.
11639 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011640 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011641#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011642 DOUT << "IC: Mod = " << OrigI
11643 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011644#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011645
Chris Lattner90ac28c2002-08-02 19:29:35 +000011646 // If the instruction was modified, it's possible that it is now dead.
11647 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011648 if (isInstructionTriviallyDead(I)) {
11649 // Make sure we process all operands now that we are reducing their
11650 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011651 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011652
Chris Lattner00d51312004-05-01 23:27:23 +000011653 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011654 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011655 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011656 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011657 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011658 AddToWorkList(I);
11659 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011660 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011661 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011662 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011663 }
11664 }
11665
Chris Lattnerec9c3582007-03-03 02:04:50 +000011666 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011667
11668 // Do an explicit clear, this shrinks the map if needed.
11669 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011670 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011671}
11672
Chris Lattnerec9c3582007-03-03 02:04:50 +000011673
11674bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011675 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11676
Chris Lattnerec9c3582007-03-03 02:04:50 +000011677 bool EverMadeChange = false;
11678
11679 // Iterate while there is work to do.
11680 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011681 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011682 EverMadeChange = true;
11683 return EverMadeChange;
11684}
11685
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011686FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011687 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011688}
Brian Gaeked0fde302003-11-11 22:41:34 +000011689
Chris Lattnerb8cd4d32008-08-11 22:06:05 +000011690