blob: 88421db8267d5a2f0663aa3b9abe356a9cbe1e1b [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"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez83d63912009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.h"
Chris Lattner173234a2008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000055#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000057#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058#include "llvm/Support/PatternMatch.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000059#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000060#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000061#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000062#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000064#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000065#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000066#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000093 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
94 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000095 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000096 }
Chris Lattner873ff012009-08-30 05:55:36 +000097 }
98
Chris Lattner3c4e38e2009-08-30 06:27:41 +000099 void AddValue(Value *V) {
100 if (Instruction *I = dyn_cast<Instruction>(V))
101 Add(I);
102 }
103
Chris Lattner67f7d542009-10-12 03:58:40 +0000104 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
105 /// which should only be done when the worklist is empty and when the group
106 /// has no duplicates.
107 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
108 assert(Worklist.empty() && "Worklist must be empty to add initial group");
109 Worklist.reserve(NumEntries+16);
110 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
111 for (; NumEntries; --NumEntries) {
112 Instruction *I = List[NumEntries-1];
113 WorklistMap.insert(std::make_pair(I, Worklist.size()));
114 Worklist.push_back(I);
115 }
116 }
117
Chris Lattner7a1e9242009-08-30 06:13:40 +0000118 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000119 void Remove(Instruction *I) {
120 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
121 if (It == WorklistMap.end()) return; // Not in worklist.
122
123 // Don't bother moving everything down, just null out the slot.
124 Worklist[It->second] = 0;
125
126 WorklistMap.erase(It);
127 }
128
129 Instruction *RemoveOne() {
130 Instruction *I = Worklist.back();
131 Worklist.pop_back();
132 WorklistMap.erase(I);
133 return I;
134 }
135
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000136 /// AddUsersToWorkList - When an instruction is simplified, add all users of
137 /// the instruction to the work lists because they might get more simplified
138 /// now.
139 ///
140 void AddUsersToWorkList(Instruction &I) {
141 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
142 UI != UE; ++UI)
143 Add(cast<Instruction>(*UI));
144 }
145
Chris Lattner873ff012009-08-30 05:55:36 +0000146
147 /// Zap - check that the worklist is empty and nuke the backing store for
148 /// the map if it is large.
149 void Zap() {
150 assert(WorklistMap.empty() && "Worklist empty, but map not?");
151
152 // Do an explicit clear, this shrinks the map if needed.
153 WorklistMap.clear();
154 }
155 };
156} // end anonymous namespace.
157
158
159namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000160 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
161 /// just like the normal insertion helper, but also adds any new instructions
162 /// to the instcombine worklist.
163 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
164 InstCombineWorklist &Worklist;
165 public:
166 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
167
168 void InsertHelper(Instruction *I, const Twine &Name,
169 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
170 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
171 Worklist.Add(I);
172 }
173 };
174} // end anonymous namespace
175
176
177namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000178 class InstCombiner : public FunctionPass,
179 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000180 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000181 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000182 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000183 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000184 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000185 InstCombineWorklist Worklist;
186
Chris Lattner74381062009-08-30 07:44:24 +0000187 /// Builder - This is an IRBuilder that automatically inserts new
188 /// instructions into the worklist when they are created.
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000189 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
190 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000191
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000192 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000193 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000194
Owen Andersone922c022009-07-22 00:24:57 +0000195 LLVMContext *Context;
196 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000197
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000198 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000199 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000200
201 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000202
Chris Lattner97e52e42002-04-28 21:27:06 +0000203 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000204 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000205 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000206 }
207
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000208 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000209
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000210 // Visitation implementation - Implement instruction combining for different
211 // instruction types. The semantics are as follows:
212 // Return Value:
213 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000214 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000215 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000216 //
Chris Lattner7e708292002-06-25 16:13:24 +0000217 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000218 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000219 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000220 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000222 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000223 Instruction *visitURem(BinaryOperator &I);
224 Instruction *visitSRem(BinaryOperator &I);
225 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000226 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000227 Instruction *commonRemTransforms(BinaryOperator &I);
228 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000229 Instruction *commonDivTransforms(BinaryOperator &I);
230 Instruction *commonIDivTransforms(BinaryOperator &I);
231 Instruction *visitUDiv(BinaryOperator &I);
232 Instruction *visitSDiv(BinaryOperator &I);
233 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000234 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000235 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000236 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000237 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000238 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000239 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000240 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000241 Instruction *visitOr (BinaryOperator &I);
242 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000243 Instruction *visitShl(BinaryOperator &I);
244 Instruction *visitAShr(BinaryOperator &I);
245 Instruction *visitLShr(BinaryOperator &I);
246 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000247 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
248 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000249 Instruction *visitFCmpInst(FCmpInst &I);
250 Instruction *visitICmpInst(ICmpInst &I);
251 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000252 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
253 Instruction *LHS,
254 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000255 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
256 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000257
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000258 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000259 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000260 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000261 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000262 Instruction *commonCastTransforms(CastInst &CI);
263 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000264 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000265 Instruction *visitTrunc(TruncInst &CI);
266 Instruction *visitZExt(ZExtInst &CI);
267 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000268 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000269 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000270 Instruction *visitFPToUI(FPToUIInst &FI);
271 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000272 Instruction *visitUIToFP(CastInst &CI);
273 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000274 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000275 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000276 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000277 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
278 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000279 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000280 Instruction *visitSelectInst(SelectInst &SI);
281 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000282 Instruction *visitCallInst(CallInst &CI);
283 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000284 Instruction *visitPHINode(PHINode &PN);
285 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000286 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000287 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000288 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000289 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000290 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000291 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000292 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000293 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000294 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000295 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000296
297 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000298 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000299
Chris Lattner9fe38862003-06-19 17:00:31 +0000300 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000301 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000302 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000303 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000304 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
305 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000306 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000307 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
308
Chris Lattner9fe38862003-06-19 17:00:31 +0000309
Chris Lattner28977af2004-04-05 01:30:19 +0000310 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000311 // InsertNewInstBefore - insert an instruction New before instruction Old
312 // in the program. Add the new instruction to the worklist.
313 //
Chris Lattner955f3312004-09-28 21:48:02 +0000314 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000315 assert(New && New->getParent() == 0 &&
316 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000317 BasicBlock *BB = Old.getParent();
318 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000319 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000320 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000321 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000322
Chris Lattner8b170942002-08-09 23:47:40 +0000323 // ReplaceInstUsesWith - This method is to be used when an instruction is
324 // found to be dead, replacable with another preexisting expression. Here
325 // we add all uses of I to the worklist, replace all uses of I with the new
326 // value, then return I, so that the inst combiner will know that I was
327 // modified.
328 //
329 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000330 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000331
332 // If we are replacing the instruction with itself, this must be in a
333 // segment of unreachable code, so just clobber the instruction.
334 if (&I == V)
335 V = UndefValue::get(I.getType());
336
337 I.replaceAllUsesWith(V);
338 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340
341 // EraseInstFromFunction - When dealing with an instruction that has side
342 // effects or produces a void value, we can't rely on DCE to delete the
343 // instruction. Instead, visit methods should return the value returned by
344 // this function.
345 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000346 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000347
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000348 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000349 // Make sure that we reprocess all operands now that we reduced their
350 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000351 if (I.getNumOperands() < 8) {
352 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
353 if (Instruction *Op = dyn_cast<Instruction>(*i))
354 Worklist.Add(Op);
355 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000356 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000357 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000358 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000359 return 0; // Don't do anything with FI
360 }
Chris Lattner173234a2008-06-02 01:18:21 +0000361
362 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
363 APInt &KnownOne, unsigned Depth = 0) const {
364 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
365 }
366
367 bool MaskedValueIsZero(Value *V, const APInt &Mask,
368 unsigned Depth = 0) const {
369 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
370 }
371 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
372 return llvm::ComputeNumSignBits(Op, TD, Depth);
373 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000374
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000375 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000376
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 /// SimplifyCommutative - This performs a few simplifications for
378 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000379 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000380
Reid Spencere4d87aa2006-12-23 06:05:41 +0000381 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
382 /// most-complex to least-complex order.
383 bool SimplifyCompare(CmpInst &I);
384
Chris Lattner886ab6c2009-01-31 08:15:18 +0000385 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
386 /// based on the demanded bits.
387 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
388 APInt& KnownZero, APInt& KnownOne,
389 unsigned Depth);
390 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000391 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000392 unsigned Depth=0);
393
394 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
395 /// SimplifyDemandedBits knows about. See if the instruction has any
396 /// properties that allow us to simplify its operands.
397 bool SimplifyDemandedInstructionBits(Instruction &Inst);
398
Evan Cheng388df622009-02-03 10:05:09 +0000399 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
400 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000401
Chris Lattner5d1704d2009-09-27 19:57:57 +0000402 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
403 // which has a PHI node as operand #0, see if we can fold the instruction
404 // into the PHI (which is only possible if all operands to the PHI are
405 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000406 //
407 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
408 // that would normally be unprofitable because they strongly encourage jump
409 // threading.
410 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000411
Chris Lattnerbac32862004-11-14 19:13:23 +0000412 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
413 // operator and they all are only used by the PHI, PHI together their
414 // inputs, and do the operation once, to the result of the PHI.
415 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000416 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000417 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
418
Chris Lattner7da52b22006-11-01 04:51:18 +0000419
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000420 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
421 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000422
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000423 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000424 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000425 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000426 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000427 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000428 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000429 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000430 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000431 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000432
Chris Lattnerafe91a52006-06-15 19:07:26 +0000433
Reid Spencerc55b2432006-12-13 18:21:21 +0000434 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000435
Dan Gohman6de29f82009-06-15 22:12:54 +0000436 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000437 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000438 unsigned GetOrEnforceKnownAlignment(Value *V,
439 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000440
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000441 };
Chris Lattner873ff012009-08-30 05:55:36 +0000442} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000443
Dan Gohman844731a2008-05-13 00:00:25 +0000444char InstCombiner::ID = 0;
445static RegisterPass<InstCombiner>
446X("instcombine", "Combine redundant instructions");
447
Chris Lattner4f98c562003-03-10 21:43:22 +0000448// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000449// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000450static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000451 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000452 if (BinaryOperator::isNeg(V) ||
453 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000454 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000455 return 3;
456 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000457 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000458 if (isa<Argument>(V)) return 3;
459 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000460}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000461
Chris Lattnerc8802d22003-03-11 00:12:48 +0000462// isOnlyUse - Return true if this instruction will be deleted if we stop using
463// it.
464static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000465 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000466}
467
Chris Lattner4cb170c2004-02-23 06:38:22 +0000468// getPromotedType - Return the specified type promoted as it would be to pass
469// though a va_arg area...
470static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000471 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
472 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000473 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000474 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000475 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000476}
477
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000478/// getBitCastOperand - If the specified operand is a CastInst, a constant
479/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
480/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000481static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000482 if (Operator *O = dyn_cast<Operator>(V)) {
483 if (O->getOpcode() == Instruction::BitCast)
484 return O->getOperand(0);
485 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
486 if (GEP->hasAllZeroIndices())
487 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000488 }
Chris Lattnereed48272005-09-13 00:40:14 +0000489 return 0;
490}
491
Reid Spencer3da59db2006-11-27 01:05:10 +0000492/// This function is a wrapper around CastInst::isEliminableCastPair. It
493/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000494static Instruction::CastOps
495isEliminableCastPair(
496 const CastInst *CI, ///< The first cast instruction
497 unsigned opcode, ///< The opcode of the second cast instruction
498 const Type *DstTy, ///< The target type for the second cast instruction
499 TargetData *TD ///< The target data for pointer size
500) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000501
Reid Spencer3da59db2006-11-27 01:05:10 +0000502 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
503 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000504
Reid Spencer3da59db2006-11-27 01:05:10 +0000505 // Get the opcodes of the two Cast instructions
506 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
507 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000508
Chris Lattnera0e69692009-03-24 18:35:40 +0000509 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000510 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000511 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000512
513 // We don't want to form an inttoptr or ptrtoint that converts to an integer
514 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000515 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000516 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000517 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000518 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000519 Res = 0;
520
521 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000522}
523
524/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
525/// in any code being generated. It does not require codegen if V is simple
526/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000527static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
528 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000529 if (V->getType() == Ty || isa<Constant>(V)) return false;
530
Chris Lattner01575b72006-05-25 23:24:33 +0000531 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000532 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000533 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000534 return false;
535 return true;
536}
537
Chris Lattner4f98c562003-03-10 21:43:22 +0000538// SimplifyCommutative - This performs a few simplifications for commutative
539// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000540//
Chris Lattner4f98c562003-03-10 21:43:22 +0000541// 1. Order operands such that they are listed from right (least complex) to
542// left (most complex). This puts constants before unary operators before
543// binary operators.
544//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000545// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
546// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000547//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000549 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000550 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000552
Chris Lattner4f98c562003-03-10 21:43:22 +0000553 if (!I.isAssociative()) return Changed;
554 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000555 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
556 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
557 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000558 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000559 cast<Constant>(I.getOperand(1)),
560 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000561 I.setOperand(0, Op->getOperand(0));
562 I.setOperand(1, Folded);
563 return true;
564 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
565 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
566 isOnlyUse(Op) && isOnlyUse(Op1)) {
567 Constant *C1 = cast<Constant>(Op->getOperand(1));
568 Constant *C2 = cast<Constant>(Op1->getOperand(1));
569
570 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000571 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000572 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000573 Op1->getOperand(0),
574 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000575 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000576 I.setOperand(0, New);
577 I.setOperand(1, Folded);
578 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000579 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000580 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000581 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000582}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000583
Reid Spencere4d87aa2006-12-23 06:05:41 +0000584/// SimplifyCompare - For a CmpInst this function just orders the operands
585/// so that theyare listed from right (least complex) to left (most complex).
586/// This puts constants before unary operators before binary operators.
587bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000588 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000589 return false;
590 I.swapOperands();
591 // Compare instructions are not associative so there's nothing else we can do.
592 return true;
593}
594
Chris Lattner8d969642003-03-10 23:06:50 +0000595// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
596// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000597//
Dan Gohman186a6362009-08-12 16:04:34 +0000598static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000599 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000600 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000601
Chris Lattner0ce85802004-12-14 20:08:06 +0000602 // Constants can be considered to be negated values if they can be folded.
603 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000605
606 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
607 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000608 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000609
Chris Lattner8d969642003-03-10 23:06:50 +0000610 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000611}
612
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000613// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
614// instruction if the LHS is a constant negative zero (which is the 'negate'
615// form).
616//
Dan Gohman186a6362009-08-12 16:04:34 +0000617static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000618 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000619 return BinaryOperator::getFNegArgument(V);
620
621 // Constants can be considered to be negated values if they can be folded.
622 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000623 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000624
625 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000627 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000628
629 return 0;
630}
631
Dan Gohman186a6362009-08-12 16:04:34 +0000632static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000633 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000634 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000635
636 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000637 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000638 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000639 return 0;
640}
641
Chris Lattnerc8802d22003-03-11 00:12:48 +0000642// dyn_castFoldableMul - If this value is a multiply that can be folded into
643// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000644// non-constant operand of the multiply, and set CST to point to the multiplier.
645// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000646//
Dan Gohman186a6362009-08-12 16:04:34 +0000647static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000648 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000649 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000650 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000651 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000652 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000653 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000654 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000655 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000656 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000657 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000658 CST = ConstantInt::get(V->getType()->getContext(),
659 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000660 return I->getOperand(0);
661 }
662 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000663 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000664}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000665
Reid Spencer7177c3a2007-03-25 05:33:51 +0000666/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000667static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000668 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000669 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000670}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000671/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000672static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000673 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000674 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000675}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000676/// MultiplyOverflows - True if the multiply can not be expressed in an int
677/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000678static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000679 uint32_t W = C1->getBitWidth();
680 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
681 if (sign) {
682 LHSExt.sext(W * 2);
683 RHSExt.sext(W * 2);
684 } else {
685 LHSExt.zext(W * 2);
686 RHSExt.zext(W * 2);
687 }
688
689 APInt MulExt = LHSExt * RHSExt;
690
691 if (sign) {
692 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
693 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
694 return MulExt.slt(Min) || MulExt.sgt(Max);
695 } else
696 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
697}
Chris Lattner955f3312004-09-28 21:48:02 +0000698
Reid Spencere7816b52007-03-08 01:52:58 +0000699
Chris Lattner255d8912006-02-11 09:31:47 +0000700/// ShrinkDemandedConstant - Check to see if the specified operand of the
701/// specified instruction is a constant integer. If so, check to see if there
702/// are any bits set in the constant that are not demanded. If so, shrink the
703/// constant and return true.
704static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000705 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000706 assert(I && "No instruction?");
707 assert(OpNo < I->getNumOperands() && "Operand index too large");
708
709 // If the operand is not a constant integer, nothing to do.
710 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
711 if (!OpC) return false;
712
713 // If there are no bits set that aren't demanded, nothing to do.
714 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
715 if ((~Demanded & OpC->getValue()) == 0)
716 return false;
717
718 // This instruction is producing bits that are not demanded. Shrink the RHS.
719 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000720 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000721 return true;
722}
723
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000724// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
725// set of known zero and one bits, compute the maximum and minimum values that
726// could have the specified known zero and known one bits, returning them in
727// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000728static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000729 const APInt& KnownOne,
730 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
734 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000735 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
738 // bit if it is unknown.
739 Min = KnownOne;
740 Max = KnownOne|UnknownBits;
741
Dan Gohman1c8491e2009-04-25 17:12:48 +0000742 if (UnknownBits.isNegative()) { // Sign bit is unknown
743 Min.set(Min.getBitWidth()-1);
744 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000745 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000746}
747
748// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
749// a set of known zero and one bits, compute the maximum and minimum values that
750// could have the specified known zero and known one bits, returning them in
751// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000752static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000753 const APInt &KnownOne,
754 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000755 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
756 KnownZero.getBitWidth() == Min.getBitWidth() &&
757 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000758 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000759 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000760
761 // The minimum value is when the unknown bits are all zeros.
762 Min = KnownOne;
763 // The maximum value is when the unknown bits are all ones.
764 Max = KnownOne|UnknownBits;
765}
Chris Lattner255d8912006-02-11 09:31:47 +0000766
Chris Lattner886ab6c2009-01-31 08:15:18 +0000767/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
768/// SimplifyDemandedBits knows about. See if the instruction has any
769/// properties that allow us to simplify its operands.
770bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000771 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000772 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
773 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
774
775 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
776 KnownZero, KnownOne, 0);
777 if (V == 0) return false;
778 if (V == &Inst) return true;
779 ReplaceInstUsesWith(Inst, V);
780 return true;
781}
782
783/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
784/// specified instruction operand if possible, updating it in place. It returns
785/// true if it made any change and false otherwise.
786bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
787 APInt &KnownZero, APInt &KnownOne,
788 unsigned Depth) {
789 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
790 KnownZero, KnownOne, Depth);
791 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000792 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000793 return true;
794}
795
796
797/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
798/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000799/// that only the bits set in DemandedMask of the result of V are ever used
800/// downstream. Consequently, depending on the mask and V, it may be possible
801/// to replace V with a constant or one of its operands. In such cases, this
802/// function does the replacement and returns true. In all other cases, it
803/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000804/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000805/// to be zero in the expression. These are provided to potentially allow the
806/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
807/// the expression. KnownOne and KnownZero always follow the invariant that
808/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
809/// the bits in KnownOne and KnownZero may only be accurate for those bits set
810/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
811/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000812///
813/// This returns null if it did not change anything and it permits no
814/// simplification. This returns V itself if it did some simplification of V's
815/// operands based on the information about what bits are demanded. This returns
816/// some other non-null value if it found out that V is equal to another value
817/// in the context where the specified bits are demanded, but not for all users.
818Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
819 APInt &KnownZero, APInt &KnownOne,
820 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000821 assert(V != 0 && "Null pointer of Value???");
822 assert(Depth <= 6 && "Limit Search Depth");
823 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000824 const Type *VTy = V->getType();
825 assert((TD || !isa<PointerType>(VTy)) &&
826 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000827 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
828 (!VTy->isIntOrIntVector() ||
829 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000830 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000831 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000832 "Value *V, DemandedMask, KnownZero and KnownOne "
833 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000834 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
835 // We know all of the bits for a constant!
836 KnownOne = CI->getValue() & DemandedMask;
837 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000838 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000839 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000840 if (isa<ConstantPointerNull>(V)) {
841 // We know all of the bits for a constant!
842 KnownOne.clear();
843 KnownZero = DemandedMask;
844 return 0;
845 }
846
Chris Lattner08d2cc72009-01-31 07:26:06 +0000847 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000848 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000849 if (DemandedMask == 0) { // Not demanding any bits from V.
850 if (isa<UndefValue>(V))
851 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000852 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000853 }
854
Chris Lattner4598c942009-01-31 08:24:16 +0000855 if (Depth == 6) // Limit search depth.
856 return 0;
857
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000858 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
859 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
860
Dan Gohman1c8491e2009-04-25 17:12:48 +0000861 Instruction *I = dyn_cast<Instruction>(V);
862 if (!I) {
863 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
864 return 0; // Only analyze instructions.
865 }
866
Chris Lattner4598c942009-01-31 08:24:16 +0000867 // If there are multiple uses of this value and we aren't at the root, then
868 // we can't do any simplifications of the operands, because DemandedMask
869 // only reflects the bits demanded by *one* of the users.
870 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000871 // Despite the fact that we can't simplify this instruction in all User's
872 // context, we can at least compute the knownzero/knownone bits, and we can
873 // do simplifications that apply to *just* the one user if we know that
874 // this instruction has a simpler value in that context.
875 if (I->getOpcode() == Instruction::And) {
876 // If either the LHS or the RHS are Zero, the result is zero.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
880 LHSKnownZero, LHSKnownOne, Depth+1);
881
882 // If all of the demanded bits are known 1 on one side, return the other.
883 // These bits cannot contribute to the result of the 'and' in this
884 // context.
885 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
886 (DemandedMask & ~LHSKnownZero))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
889 (DemandedMask & ~RHSKnownZero))
890 return I->getOperand(1);
891
892 // If all of the demanded bits in the inputs are known zeros, return zero.
893 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000894 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000895
896 } else if (I->getOpcode() == Instruction::Or) {
897 // We can simplify (X|Y) -> X or Y in the user's context if we know that
898 // only bits from X or Y are demanded.
899
900 // If either the LHS or the RHS are One, the result is One.
901 ComputeMaskedBits(I->getOperand(1), DemandedMask,
902 RHSKnownZero, RHSKnownOne, Depth+1);
903 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
904 LHSKnownZero, LHSKnownOne, Depth+1);
905
906 // If all of the demanded bits are known zero on one side, return the
907 // other. These bits cannot contribute to the result of the 'or' in this
908 // context.
909 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
910 (DemandedMask & ~LHSKnownOne))
911 return I->getOperand(0);
912 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
913 (DemandedMask & ~RHSKnownOne))
914 return I->getOperand(1);
915
916 // If all of the potentially set bits on one side are known to be set on
917 // the other side, just use the 'other' side.
918 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
919 (DemandedMask & (~RHSKnownZero)))
920 return I->getOperand(0);
921 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
922 (DemandedMask & (~LHSKnownZero)))
923 return I->getOperand(1);
924 }
925
Chris Lattner4598c942009-01-31 08:24:16 +0000926 // Compute the KnownZero/KnownOne bits to simplify things downstream.
927 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
928 return 0;
929 }
930
931 // If this is the root being simplified, allow it to have multiple uses,
932 // just set the DemandedMask to all bits so that we can try to simplify the
933 // operands. This allows visitTruncInst (for example) to simplify the
934 // operand of a trunc without duplicating all the logic below.
935 if (Depth == 0 && !V->hasOneUse())
936 DemandedMask = APInt::getAllOnesValue(BitWidth);
937
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000939 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000941 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 case Instruction::And:
943 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
945 RHSKnownZero, RHSKnownOne, Depth+1) ||
946 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000947 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 return I;
949 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
950 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000951
952 // If all of the demanded bits are known 1 on one side, return the other.
953 // These bits cannot contribute to the result of the 'and'.
954 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
955 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000957 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
958 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000959 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000960
961 // If all of the demanded bits in the inputs are known zeros, return zero.
962 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000963 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000966 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000967 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000968
969 // Output known-1 bits are only known if set in both the LHS & RHS.
970 RHSKnownOne &= LHSKnownOne;
971 // Output known-0 are known to be clear if zero in either the LHS | RHS.
972 RHSKnownZero |= LHSKnownZero;
973 break;
974 case Instruction::Or:
975 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977 RHSKnownZero, RHSKnownOne, Depth+1) ||
978 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
981 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
982 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000983
984 // If all of the demanded bits are known zero on one side, return the other.
985 // These bits cannot contribute to the result of the 'or'.
986 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
987 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
990 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000991 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // If all of the potentially set bits on one side are known to be set on
994 // the other side, just use the 'other' side.
995 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
996 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
999 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001001
1002 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001003 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001005
1006 // Output known-0 bits are only known if clear in both the LHS & RHS.
1007 RHSKnownZero &= LHSKnownZero;
1008 // Output known-1 are known to be set if set in either the LHS | RHS.
1009 RHSKnownOne |= LHSKnownOne;
1010 break;
1011 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1) ||
1014 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001015 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I;
1017 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1018 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001019
1020 // If all of the demanded bits are known zero on one side, return the other.
1021 // These bits cannot contribute to the result of the 'xor'.
1022 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001023 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001025 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026
1027 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1028 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1029 (RHSKnownOne & LHSKnownOne);
1030 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1031 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1032 (RHSKnownOne & LHSKnownZero);
1033
1034 // If all of the demanded bits are known to be zero on one side or the
1035 // other, turn this into an *inclusive* or.
1036 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001037 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1038 Instruction *Or =
1039 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1040 I->getName());
1041 return InsertNewInstBefore(Or, *I);
1042 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001043
1044 // If all of the demanded bits on one side are known, and all of the set
1045 // bits on that side are also known to be set on the other side, turn this
1046 // into an AND, as we know the bits will be cleared.
1047 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1048 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1049 // all known
1050 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001051 Constant *AndC = Constant::getIntegerValue(VTy,
1052 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001054 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001056 }
1057 }
1058
1059 // If the RHS is a constant, see if we can simplify it.
1060 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001061 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
Chris Lattnerd0883142009-10-11 22:22:13 +00001064 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1065 // are flipping are known to be set, then the xor is just resetting those
1066 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1067 // simplifying both of them.
1068 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1069 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1070 isa<ConstantInt>(I->getOperand(1)) &&
1071 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1072 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1073 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1074 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1075 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1076
1077 Constant *AndC =
1078 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1079 Instruction *NewAnd =
1080 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1081 InsertNewInstBefore(NewAnd, *I);
1082
1083 Constant *XorC =
1084 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1085 Instruction *NewXor =
1086 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1087 return InsertNewInstBefore(NewXor, *I);
1088 }
1089
1090
Reid Spencer8cb68342007-03-12 17:25:59 +00001091 RHSKnownZero = KnownZeroOut;
1092 RHSKnownOne = KnownOneOut;
1093 break;
1094 }
1095 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1097 RHSKnownZero, RHSKnownOne, Depth+1) ||
1098 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001099 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 return I;
1101 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1102 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001103
1104 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001105 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1106 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001108
1109 // Only known if known in both the LHS and RHS.
1110 RHSKnownOne &= LHSKnownOne;
1111 RHSKnownZero &= LHSKnownZero;
1112 break;
1113 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001114 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001115 DemandedMask.zext(truncBf);
1116 RHSKnownZero.zext(truncBf);
1117 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001118 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001119 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 DemandedMask.trunc(BitWidth);
1122 RHSKnownZero.trunc(BitWidth);
1123 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 break;
1126 }
1127 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001128 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001130
1131 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1132 if (const VectorType *SrcVTy =
1133 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1134 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1135 // Don't touch a bitcast between vectors of different element counts.
1136 return false;
1137 } else
1138 // Don't touch a scalar-to-vector bitcast.
1139 return false;
1140 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1141 // Don't touch a vector-to-scalar bitcast.
1142 return false;
1143
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 return I;
1147 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 break;
1149 case Instruction::ZExt: {
1150 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001151 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001152
Zhou Shengd48653a2007-03-29 04:45:55 +00001153 DemandedMask.trunc(SrcBitWidth);
1154 RHSKnownZero.trunc(SrcBitWidth);
1155 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001157 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001159 DemandedMask.zext(BitWidth);
1160 RHSKnownZero.zext(BitWidth);
1161 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001164 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 break;
1166 }
1167 case Instruction::SExt: {
1168 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001169 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
Reid Spencer8cb68342007-03-12 17:25:59 +00001171 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001172 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001173
Zhou Sheng01542f32007-03-29 02:26:30 +00001174 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 // If any of the sign extended bits are demanded, we know that the sign
1176 // bit is demanded.
1177 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001178 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001179
Zhou Shengd48653a2007-03-29 04:45:55 +00001180 InputDemandedBits.trunc(SrcBitWidth);
1181 RHSKnownZero.trunc(SrcBitWidth);
1182 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001183 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001184 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001186 InputDemandedBits.zext(BitWidth);
1187 RHSKnownZero.zext(BitWidth);
1188 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001189 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001190
1191 // If the sign bit of the input is known set or clear, then we know the
1192 // top bits of the result.
1193
1194 // If the input sign bit is known zero, or if the NewBits are not demanded
1195 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001196 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001197 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001198 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1199 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001200 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 }
1203 break;
1204 }
1205 case Instruction::Add: {
1206 // Figure out what the input bits are. If the top bits of the and result
1207 // are not demanded, then the add doesn't demand them from its input
1208 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001209 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001210
1211 // If there is a constant on the RHS, there are a variety of xformations
1212 // we can do.
1213 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1214 // If null, this should be simplified elsewhere. Some of the xforms here
1215 // won't work if the RHS is zero.
1216 if (RHS->isZero())
1217 break;
1218
1219 // If the top bit of the output is demanded, demand everything from the
1220 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001221 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001222
1223 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001224 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001227
1228 // If the RHS of the add has bits set that can't affect the input, reduce
1229 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001230 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001231 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001232
1233 // Avoid excess work.
1234 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1235 break;
1236
1237 // Turn it into OR if input bits are zero.
1238 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1239 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001240 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 }
1244
1245 // We can say something about the output known-zero and known-one bits,
1246 // depending on potential carries from the input constant and the
1247 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1248 // bits set and the RHS constant is 0x01001, then we know we have a known
1249 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1250
1251 // To compute this, we first compute the potential carry bits. These are
1252 // the bits which may be modified. I'm not aware of a better way to do
1253 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001255 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001256
1257 // Now that we know which bits have carries, compute the known-1/0 sets.
1258
1259 // Bits are known one if they are known zero in one operand and one in the
1260 // other, and there is no input carry.
1261 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1262 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1263
1264 // Bits are known zero if they are known zero in both operands and there
1265 // is no input carry.
1266 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1267 } else {
1268 // If the high-bits of this ADD are not demanded, then it does not demand
1269 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001270 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 // Right fill the mask of bits for this ADD to demand the most
1272 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001273 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001274 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1275 LHSKnownZero, LHSKnownOne, Depth+1) ||
1276 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001277 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001278 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 }
1280 }
1281 break;
1282 }
1283 case Instruction::Sub:
1284 // If the high-bits of this SUB are not demanded, then it does not demand
1285 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001286 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 // Right fill the mask of bits for this SUB to demand the most
1288 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001289 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001290 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1292 LHSKnownZero, LHSKnownOne, Depth+1) ||
1293 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001295 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001296 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001297 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1298 // the known zeros and ones.
1299 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 break;
1301 case Instruction::Shl:
1302 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001303 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001304 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 return I;
1308 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 RHSKnownZero <<= ShiftAmt;
1310 RHSKnownOne <<= ShiftAmt;
1311 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001312 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001313 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 }
1315 break;
1316 case Instruction::LShr:
1317 // For a logical shift right
1318 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001319 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001320
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001322 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 return I;
1326 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1328 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001329 if (ShiftAmt) {
1330 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001331 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001332 RHSKnownZero |= HighBits; // high bits known zero.
1333 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001334 }
1335 break;
1336 case Instruction::AShr:
1337 // If this is an arithmetic shift right and only the low-bit is set, we can
1338 // always convert this into a logical shr, even if the shift amount is
1339 // variable. The low bit of the shift cannot be an input sign bit unless
1340 // the shift amount is >= the size of the datatype, which is undefined.
1341 if (DemandedMask == 1) {
1342 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001343 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001346 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001347
1348 // If the sign bit is the only bit demanded by this ashr, then there is no
1349 // need to do it, the shift doesn't change the high bit.
1350 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001352
1353 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001354 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001355
Reid Spencer8cb68342007-03-12 17:25:59 +00001356 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001357 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001358 // If any of the "high bits" are demanded, we should set the sign bit as
1359 // demanded.
1360 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1361 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001363 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 return I;
1365 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001366 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001367 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1369 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1370
1371 // Handle the sign bits.
1372 APInt SignBit(APInt::getSignBit(BitWidth));
1373 // Adjust to where it is now in the mask.
1374 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1375
1376 // If the input sign bit is known to be zero, or if none of the top bits
1377 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001378 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 (HighBits & ~DemandedMask) == HighBits) {
1380 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001381 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001382 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001383 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1385 RHSKnownOne |= HighBits;
1386 }
1387 }
1388 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001389 case Instruction::SRem:
1390 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001391 APInt RA = Rem->getValue().abs();
1392 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001393 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001394 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001395
Nick Lewycky8e394322008-11-02 02:41:50 +00001396 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001397 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001398 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001399 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001400 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001401
1402 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1403 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001404
1405 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001406
Chris Lattner886ab6c2009-01-31 08:15:18 +00001407 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001408 }
1409 }
1410 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001411 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001412 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1413 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001414 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1415 KnownZero2, KnownOne2, Depth+1) ||
1416 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001417 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001418 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001419
Chris Lattner455e9ab2009-01-21 18:09:24 +00001420 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001421 Leaders = std::max(Leaders,
1422 KnownZero2.countLeadingOnes());
1423 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001424 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001426 case Instruction::Call:
1427 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1428 switch (II->getIntrinsicID()) {
1429 default: break;
1430 case Intrinsic::bswap: {
1431 // If the only bits demanded come from one byte of the bswap result,
1432 // just shift the input byte into position to eliminate the bswap.
1433 unsigned NLZ = DemandedMask.countLeadingZeros();
1434 unsigned NTZ = DemandedMask.countTrailingZeros();
1435
1436 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1437 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1438 // have 14 leading zeros, round to 8.
1439 NLZ &= ~7;
1440 NTZ &= ~7;
1441 // If we need exactly one byte, we can do this transformation.
1442 if (BitWidth-NLZ-NTZ == 8) {
1443 unsigned ResultBit = NTZ;
1444 unsigned InputBit = BitWidth-NTZ-8;
1445
1446 // Replace this with either a left or right shift to get the byte into
1447 // the right place.
1448 Instruction *NewVal;
1449 if (InputBit > ResultBit)
1450 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001451 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001452 else
1453 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001454 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001455 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001456 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001457 }
1458
1459 // TODO: Could compute known zero/one bits based on the input.
1460 break;
1461 }
1462 }
1463 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001464 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001465 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001466 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001467
1468 // If the client is only demanding bits that we know, return the known
1469 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001470 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1471 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001472 return false;
1473}
1474
Chris Lattner867b99f2006-10-05 06:55:50 +00001475
Mon P Wangaeb06d22008-11-10 04:46:22 +00001476/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001477/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001478/// actually used by the caller. This method analyzes which elements of the
1479/// operand are undef and returns that information in UndefElts.
1480///
1481/// If the information about demanded elements can be used to simplify the
1482/// operation, the operation is simplified, then the resultant value is
1483/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001484Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1485 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001487 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001488 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001489 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001490
1491 if (isa<UndefValue>(V)) {
1492 // If the entire vector is undefined, just return this info.
1493 UndefElts = EltMask;
1494 return 0;
1495 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1496 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001497 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001498 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001499
Chris Lattner867b99f2006-10-05 06:55:50 +00001500 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001501 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1502 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001503 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001504
1505 std::vector<Constant*> Elts;
1506 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001507 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001508 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001509 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1511 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001512 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001513 } else { // Otherwise, defined.
1514 Elts.push_back(CP->getOperand(i));
1515 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001516
Chris Lattner867b99f2006-10-05 06:55:50 +00001517 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001518 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001519 return NewCP != CP ? NewCP : 0;
1520 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001521 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001523
1524 // Check if this is identity. If so, return 0 since we are not simplifying
1525 // anything.
1526 if (DemandedElts == ((1ULL << VWidth) -1))
1527 return 0;
1528
Reid Spencer9d6565a2007-02-15 02:26:10 +00001529 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001530 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001531 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001532 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001533 for (unsigned i = 0; i != VWidth; ++i) {
1534 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1535 Elts.push_back(Elt);
1536 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001537 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001538 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001539 }
1540
Dan Gohman488fbfc2008-09-09 18:11:14 +00001541 // Limit search depth.
1542 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001543 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001544
1545 // If multiple users are using the root value, procede with
1546 // simplification conservatively assuming that all elements
1547 // are needed.
1548 if (!V->hasOneUse()) {
1549 // Quit if we find multiple users of a non-root value though.
1550 // They'll be handled when it's their turn to be visited by
1551 // the main instcombine process.
1552 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001553 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001554 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001555
1556 // Conservatively assume that all elements are needed.
1557 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001558 }
1559
1560 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001561 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001562
1563 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001564 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001565 Value *TmpV;
1566 switch (I->getOpcode()) {
1567 default: break;
1568
1569 case Instruction::InsertElement: {
1570 // If this is a variable index, we don't know which element it overwrites.
1571 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001572 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001573 if (Idx == 0) {
1574 // Note that we can't propagate undef elt info, because we don't know
1575 // which elt is getting updated.
1576 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1577 UndefElts2, Depth+1);
1578 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1579 break;
1580 }
1581
1582 // If this is inserting an element that isn't demanded, remove this
1583 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001584 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001585 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1586 Worklist.Add(I);
1587 return I->getOperand(0);
1588 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001589
1590 // Otherwise, the element inserted overwrites whatever was there, so the
1591 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001592 APInt DemandedElts2 = DemandedElts;
1593 DemandedElts2.clear(IdxNo);
1594 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001595 UndefElts, Depth+1);
1596 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1597
1598 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001599 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 break;
1601 }
1602 case Instruction::ShuffleVector: {
1603 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001604 uint64_t LHSVWidth =
1605 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001606 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001607 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001608 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001609 unsigned MaskVal = Shuffle->getMaskValue(i);
1610 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001611 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001612 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001613 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001614 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001615 else
Evan Cheng388df622009-02-03 10:05:09 +00001616 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001617 }
1618 }
1619 }
1620
Nate Begeman7b254672009-02-11 22:36:25 +00001621 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001622 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001623 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001624 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1625
Nate Begeman7b254672009-02-11 22:36:25 +00001626 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001627 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1628 UndefElts3, Depth+1);
1629 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1630
1631 bool NewUndefElts = false;
1632 for (unsigned i = 0; i < VWidth; i++) {
1633 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001634 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001635 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001636 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001637 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001638 NewUndefElts = true;
1639 UndefElts.set(i);
1640 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001641 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001642 if (UndefElts3[MaskVal - LHSVWidth]) {
1643 NewUndefElts = true;
1644 UndefElts.set(i);
1645 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001646 }
1647 }
1648
1649 if (NewUndefElts) {
1650 // Add additional discovered undefs.
1651 std::vector<Constant*> Elts;
1652 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001653 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001654 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001655 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001656 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001657 Shuffle->getMaskValue(i)));
1658 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001659 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001660 MadeChange = true;
1661 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001662 break;
1663 }
Chris Lattner69878332007-04-14 22:29:23 +00001664 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001665 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001666 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1667 if (!VTy) break;
1668 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001669 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001670 unsigned Ratio;
1671
1672 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001673 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001674 // elements as are demanded of us.
1675 Ratio = 1;
1676 InputDemandedElts = DemandedElts;
1677 } else if (VWidth > InVWidth) {
1678 // Untested so far.
1679 break;
1680
1681 // If there are more elements in the result than there are in the source,
1682 // then an input element is live if any of the corresponding output
1683 // elements are live.
1684 Ratio = VWidth/InVWidth;
1685 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001686 if (DemandedElts[OutIdx])
1687 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001688 }
1689 } else {
1690 // Untested so far.
1691 break;
1692
1693 // If there are more elements in the source than there are in the result,
1694 // then an input element is live if the corresponding output element is
1695 // live.
1696 Ratio = InVWidth/VWidth;
1697 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001698 if (DemandedElts[InIdx/Ratio])
1699 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001700 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001701
Chris Lattner69878332007-04-14 22:29:23 +00001702 // div/rem demand all inputs, because they don't want divide by zero.
1703 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1704 UndefElts2, Depth+1);
1705 if (TmpV) {
1706 I->setOperand(0, TmpV);
1707 MadeChange = true;
1708 }
1709
1710 UndefElts = UndefElts2;
1711 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001712 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001713 // If there are more elements in the result than there are in the source,
1714 // then an output element is undef if the corresponding input element is
1715 // undef.
1716 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001717 if (UndefElts2[OutIdx/Ratio])
1718 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001719 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001720 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001721 // If there are more elements in the source than there are in the result,
1722 // then a result element is undef if all of the corresponding input
1723 // elements are undef.
1724 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1725 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001726 if (!UndefElts2[InIdx]) // Not undef?
1727 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001728 }
1729 break;
1730 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001731 case Instruction::And:
1732 case Instruction::Or:
1733 case Instruction::Xor:
1734 case Instruction::Add:
1735 case Instruction::Sub:
1736 case Instruction::Mul:
1737 // div/rem demand all inputs, because they don't want divide by zero.
1738 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1739 UndefElts, Depth+1);
1740 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1741 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1742 UndefElts2, Depth+1);
1743 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1744
1745 // Output elements are undefined if both are undefined. Consider things
1746 // like undef&0. The result is known zero, not undef.
1747 UndefElts &= UndefElts2;
1748 break;
1749
1750 case Instruction::Call: {
1751 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1752 if (!II) break;
1753 switch (II->getIntrinsicID()) {
1754 default: break;
1755
1756 // Binary vector operations that work column-wise. A dest element is a
1757 // function of the corresponding input elements from the two inputs.
1758 case Intrinsic::x86_sse_sub_ss:
1759 case Intrinsic::x86_sse_mul_ss:
1760 case Intrinsic::x86_sse_min_ss:
1761 case Intrinsic::x86_sse_max_ss:
1762 case Intrinsic::x86_sse2_sub_sd:
1763 case Intrinsic::x86_sse2_mul_sd:
1764 case Intrinsic::x86_sse2_min_sd:
1765 case Intrinsic::x86_sse2_max_sd:
1766 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1767 UndefElts, Depth+1);
1768 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1769 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1770 UndefElts2, Depth+1);
1771 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1772
1773 // If only the low elt is demanded and this is a scalarizable intrinsic,
1774 // scalarize it now.
1775 if (DemandedElts == 1) {
1776 switch (II->getIntrinsicID()) {
1777 default: break;
1778 case Intrinsic::x86_sse_sub_ss:
1779 case Intrinsic::x86_sse_mul_ss:
1780 case Intrinsic::x86_sse2_sub_sd:
1781 case Intrinsic::x86_sse2_mul_sd:
1782 // TODO: Lower MIN/MAX/ABS/etc
1783 Value *LHS = II->getOperand(1);
1784 Value *RHS = II->getOperand(2);
1785 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001786 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001787 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001788 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001789 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001790
1791 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001792 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001793 case Intrinsic::x86_sse_sub_ss:
1794 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001795 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001796 II->getName()), *II);
1797 break;
1798 case Intrinsic::x86_sse_mul_ss:
1799 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001800 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001801 II->getName()), *II);
1802 break;
1803 }
1804
1805 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001806 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001807 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001808 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001809 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001810 return New;
1811 }
1812 }
1813
1814 // Output elements are undefined if both are undefined. Consider things
1815 // like undef&0. The result is known zero, not undef.
1816 UndefElts &= UndefElts2;
1817 break;
1818 }
1819 break;
1820 }
1821 }
1822 return MadeChange ? I : 0;
1823}
1824
Dan Gohman45b4e482008-05-19 22:14:15 +00001825
Chris Lattner564a7272003-08-13 19:01:45 +00001826/// AssociativeOpt - Perform an optimization on an associative operator. This
1827/// function is designed to check a chain of associative operators for a
1828/// potential to apply a certain optimization. Since the optimization may be
1829/// applicable if the expression was reassociated, this checks the chain, then
1830/// reassociates the expression as necessary to expose the optimization
1831/// opportunity. This makes use of a special Functor, which must define
1832/// 'shouldApply' and 'apply' methods.
1833///
1834template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001835static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001836 unsigned Opcode = Root.getOpcode();
1837 Value *LHS = Root.getOperand(0);
1838
1839 // Quick check, see if the immediate LHS matches...
1840 if (F.shouldApply(LHS))
1841 return F.apply(Root);
1842
1843 // Otherwise, if the LHS is not of the same opcode as the root, return.
1844 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001845 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001846 // Should we apply this transform to the RHS?
1847 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1848
1849 // If not to the RHS, check to see if we should apply to the LHS...
1850 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1851 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1852 ShouldApply = true;
1853 }
1854
1855 // If the functor wants to apply the optimization to the RHS of LHSI,
1856 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1857 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001858 // Now all of the instructions are in the current basic block, go ahead
1859 // and perform the reassociation.
1860 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1861
1862 // First move the selected RHS to the LHS of the root...
1863 Root.setOperand(0, LHSI->getOperand(1));
1864
1865 // Make what used to be the LHS of the root be the user of the root...
1866 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001867 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001868 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001869 return 0;
1870 }
Chris Lattner65725312004-04-16 18:08:07 +00001871 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001872 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001873 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001874 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001875 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001876
1877 // Now propagate the ExtraOperand down the chain of instructions until we
1878 // get to LHSI.
1879 while (TmpLHSI != LHSI) {
1880 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001881 // Move the instruction to immediately before the chain we are
1882 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001883 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001884 ARI = NextLHSI;
1885
Chris Lattner564a7272003-08-13 19:01:45 +00001886 Value *NextOp = NextLHSI->getOperand(1);
1887 NextLHSI->setOperand(1, ExtraOperand);
1888 TmpLHSI = NextLHSI;
1889 ExtraOperand = NextOp;
1890 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001891
Chris Lattner564a7272003-08-13 19:01:45 +00001892 // Now that the instructions are reassociated, have the functor perform
1893 // the transformation...
1894 return F.apply(Root);
1895 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001896
Chris Lattner564a7272003-08-13 19:01:45 +00001897 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1898 }
1899 return 0;
1900}
1901
Dan Gohman844731a2008-05-13 00:00:25 +00001902namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001903
Nick Lewycky02d639f2008-05-23 04:34:58 +00001904// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001905struct AddRHS {
1906 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001907 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001908 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1909 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001910 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001911 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001912 }
1913};
1914
1915// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1916// iff C1&C2 == 0
1917struct AddMaskingAnd {
1918 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001919 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001920 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001921 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001922 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001923 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001924 }
1925 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001926 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001927 }
1928};
1929
Dan Gohman844731a2008-05-13 00:00:25 +00001930}
1931
Chris Lattner6e7ba452005-01-01 16:22:27 +00001932static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001933 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001934 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001935 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001936
Chris Lattner2eefe512004-04-09 19:05:30 +00001937 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001938 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1939 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001940
Chris Lattner2eefe512004-04-09 19:05:30 +00001941 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1942 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001943 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1944 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001945 }
1946
1947 Value *Op0 = SO, *Op1 = ConstOperand;
1948 if (!ConstIsRHS)
1949 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001950
Chris Lattner6e7ba452005-01-01 16:22:27 +00001951 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001952 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1953 SO->getName()+".op");
1954 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1955 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1956 SO->getName()+".cmp");
1957 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1958 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1959 SO->getName()+".cmp");
1960 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001961}
1962
1963// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1964// constant as the other operand, try to fold the binary operator into the
1965// select arguments. This also works for Cast instructions, which obviously do
1966// not have a second operand.
1967static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1968 InstCombiner *IC) {
1969 // Don't modify shared select instructions
1970 if (!SI->hasOneUse()) return 0;
1971 Value *TV = SI->getOperand(1);
1972 Value *FV = SI->getOperand(2);
1973
1974 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001975 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001976 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001977
Chris Lattner6e7ba452005-01-01 16:22:27 +00001978 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1979 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1980
Gabor Greif051a9502008-04-06 20:25:17 +00001981 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1982 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001983 }
1984 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001985}
1986
Chris Lattner4e998b22004-09-29 05:07:12 +00001987
Chris Lattner5d1704d2009-09-27 19:57:57 +00001988/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1989/// has a PHI node as operand #0, see if we can fold the instruction into the
1990/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00001991///
1992/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1993/// that would normally be unprofitable because they strongly encourage jump
1994/// threading.
1995Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1996 bool AllowAggressive) {
1997 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00001998 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001999 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002000 if (NumPHIValues == 0 ||
2001 // We normally only transform phis with a single use, unless we're trying
2002 // hard to make jump threading happen.
2003 (!PN->hasOneUse() && !AllowAggressive))
2004 return 0;
2005
2006
Chris Lattner5d1704d2009-09-27 19:57:57 +00002007 // Check to see if all of the operands of the PHI are simple constants
2008 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002009 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2010 // bail out. We don't do arbitrary constant expressions here because moving
2011 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002012 BasicBlock *NonConstBB = 0;
2013 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002014 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2015 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002016 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002017 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002018 NonConstBB = PN->getIncomingBlock(i);
2019
2020 // If the incoming non-constant value is in I's block, we have an infinite
2021 // loop.
2022 if (NonConstBB == I.getParent())
2023 return 0;
2024 }
2025
2026 // If there is exactly one non-constant value, we can insert a copy of the
2027 // operation in that block. However, if this is a critical edge, we would be
2028 // inserting the computation one some other paths (e.g. inside a loop). Only
2029 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002030 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002031 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2032 if (!BI || !BI->isUnconditional()) return 0;
2033 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002034
2035 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002036 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002037 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002038 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002039 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002040
2041 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002042 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2043 // We only currently try to fold the condition of a select when it is a phi,
2044 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002045 Value *TrueV = SI->getTrueValue();
2046 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002047 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002048 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002049 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002050 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2051 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002052 Value *InV = 0;
2053 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002054 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002055 } else {
2056 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002057 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2058 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002059 "phitmp", NonConstBB->getTerminator());
2060 Worklist.Add(cast<Instruction>(InV));
2061 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002062 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002063 }
2064 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002065 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002066 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002067 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002068 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002069 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002070 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002071 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002072 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002073 } else {
2074 assert(PN->getIncomingBlock(i) == NonConstBB);
2075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002076 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002077 PN->getIncomingValue(i), C, "phitmp",
2078 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002079 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002080 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002081 CI->getPredicate(),
2082 PN->getIncomingValue(i), C, "phitmp",
2083 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002084 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002085 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002086
Chris Lattner7a1e9242009-08-30 06:13:40 +00002087 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002088 }
2089 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002090 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002091 } else {
2092 CastInst *CI = cast<CastInst>(&I);
2093 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002094 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002095 Value *InV;
2096 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002097 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002098 } else {
2099 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002100 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002101 I.getType(), "phitmp",
2102 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002103 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002104 }
2105 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002106 }
2107 }
2108 return ReplaceInstUsesWith(I, NewPN);
2109}
2110
Chris Lattner2454a2e2008-01-29 06:52:45 +00002111
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002112/// WillNotOverflowSignedAdd - Return true if we can prove that:
2113/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2114/// This basically requires proving that the add in the original type would not
2115/// overflow to change the sign bit or have a carry out.
2116bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2117 // There are different heuristics we can use for this. Here are some simple
2118 // ones.
2119
2120 // Add has the property that adding any two 2's complement numbers can only
2121 // have one carry bit which can change a sign. As such, if LHS and RHS each
2122 // have at least two sign bits, we know that the addition of the two values will
2123 // sign extend fine.
2124 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2125 return true;
2126
2127
2128 // If one of the operands only has one non-zero bit, and if the other operand
2129 // has a known-zero bit in a more significant place than it (not including the
2130 // sign bit) the ripple may go up to and fill the zero, but won't change the
2131 // sign. For example, (X & ~4) + 1.
2132
2133 // TODO: Implement.
2134
2135 return false;
2136}
2137
Chris Lattner2454a2e2008-01-29 06:52:45 +00002138
Chris Lattner7e708292002-06-25 16:13:24 +00002139Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002140 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002141 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002142
Chris Lattner66331a42004-04-10 22:01:55 +00002143 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002144 // X + undef -> undef
2145 if (isa<UndefValue>(RHS))
2146 return ReplaceInstUsesWith(I, RHS);
2147
Chris Lattner66331a42004-04-10 22:01:55 +00002148 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002149 if (RHSC->isNullValue())
2150 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002151
Chris Lattner66331a42004-04-10 22:01:55 +00002152 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002153 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002154 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002155 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002156 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002157 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002158
2159 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2160 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002161 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002162 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002163
Eli Friedman709b33d2009-07-13 22:27:52 +00002164 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002165 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002166 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002167 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002168 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002169
2170 if (isa<PHINode>(LHS))
2171 if (Instruction *NV = FoldOpIntoPhi(I))
2172 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002173
Chris Lattner4f637d42006-01-06 17:59:59 +00002174 ConstantInt *XorRHS = 0;
2175 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002176 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002177 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002178 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002179 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002180
Zhou Sheng4351c642007-04-02 08:20:41 +00002181 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002182 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2183 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002184 do {
2185 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002186 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2187 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002188 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2189 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002190 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002191 if (!MaskedValueIsZero(XorLHS,
2192 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002193 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002194 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002195 }
2196 }
2197 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002198 C0080Val = APIntOps::lshr(C0080Val, Size);
2199 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2200 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002201
Reid Spencer35c38852007-03-28 01:36:16 +00002202 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002203 // with funny bit widths then this switch statement should be removed. It
2204 // is just here to get the size of the "middle" type back up to something
2205 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002206 const Type *MiddleType = 0;
2207 switch (Size) {
2208 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002209 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2210 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2211 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002212 }
2213 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002214 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002215 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002216 }
2217 }
Chris Lattner66331a42004-04-10 22:01:55 +00002218 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002219
Owen Anderson1d0be152009-08-13 21:58:54 +00002220 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002221 return BinaryOperator::CreateXor(LHS, RHS);
2222
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002223 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002224 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002225 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002226 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002227
2228 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2229 if (RHSI->getOpcode() == Instruction::Sub)
2230 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2231 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2232 }
2233 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2234 if (LHSI->getOpcode() == Instruction::Sub)
2235 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2236 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2237 }
Robert Bocchino71698282004-07-27 21:02:21 +00002238 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002239
Chris Lattner5c4afb92002-05-08 22:46:53 +00002240 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002241 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002242 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002243 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002244 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002245 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002246 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002247 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002248 }
2249
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002250 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002251 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002252
2253 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002254 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002255 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002256 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002257
Misha Brukmanfd939082005-04-21 23:48:37 +00002258
Chris Lattner50af16a2004-11-13 19:50:12 +00002259 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002260 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002261 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002262 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002263
2264 // X*C1 + X*C2 --> X * (C1+C2)
2265 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002266 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002267 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002268 }
2269
2270 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002271 if (dyn_castFoldableMul(RHS, C2) == LHS)
2272 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002273
Chris Lattnere617c9e2007-01-05 02:17:46 +00002274 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002275 if (dyn_castNotVal(LHS) == RHS ||
2276 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002277 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002278
Chris Lattnerad3448c2003-02-18 19:57:07 +00002279
Chris Lattner564a7272003-08-13 19:01:45 +00002280 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002281 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2282 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002283 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002284
2285 // A+B --> A|B iff A and B have no bits set in common.
2286 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2287 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2288 APInt LHSKnownOne(IT->getBitWidth(), 0);
2289 APInt LHSKnownZero(IT->getBitWidth(), 0);
2290 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2291 if (LHSKnownZero != 0) {
2292 APInt RHSKnownOne(IT->getBitWidth(), 0);
2293 APInt RHSKnownZero(IT->getBitWidth(), 0);
2294 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2295
2296 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002297 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002298 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002299 }
2300 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002301
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002302 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002303 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002304 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002305 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2306 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002307 if (W != Y) {
2308 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002309 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002310 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002311 std::swap(W, X);
2312 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002313 std::swap(Y, Z);
2314 std::swap(W, X);
2315 }
2316 }
2317
2318 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002319 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002320 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002321 }
2322 }
2323 }
2324
Chris Lattner6b032052003-10-02 15:11:26 +00002325 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002326 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002327 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002328 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002329
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002330 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002331 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002332 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002333 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002334 if (Anded == CRHS) {
2335 // See if all bits from the first bit set in the Add RHS up are included
2336 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002337 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002338
2339 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002340 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002341
2342 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002343 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002344
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002345 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2346 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002347 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002348 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002349 }
2350 }
2351 }
2352
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002353 // Try to fold constant add into select arguments.
2354 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002355 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002356 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002357 }
2358
Chris Lattner42790482007-12-20 01:56:58 +00002359 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002360 {
2361 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002362 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002363 if (!SI) {
2364 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002365 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002366 }
Chris Lattner42790482007-12-20 01:56:58 +00002367 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002368 Value *TV = SI->getTrueValue();
2369 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002370 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002371
2372 // Can we fold the add into the argument of the select?
2373 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002374 if (match(FV, m_Zero()) &&
2375 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002376 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002377 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002378 if (match(TV, m_Zero()) &&
2379 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002380 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002381 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002382 }
2383 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002384
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002385 // Check for (add (sext x), y), see if we can merge this into an
2386 // integer add followed by a sext.
2387 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2388 // (add (sext x), cst) --> (sext (add x, cst'))
2389 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2390 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002391 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002392 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002393 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002394 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2395 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002396 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2397 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002398 return new SExtInst(NewAdd, I.getType());
2399 }
2400 }
2401
2402 // (add (sext x), (sext y)) --> (sext (add int x, y))
2403 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2404 // Only do this if x/y have the same type, if at last one of them has a
2405 // single use (so we don't increase the number of sexts), and if the
2406 // integer add will not overflow.
2407 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2408 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2409 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2410 RHSConv->getOperand(0))) {
2411 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002412 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2413 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002414 return new SExtInst(NewAdd, I.getType());
2415 }
2416 }
2417 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002418
2419 return Changed ? &I : 0;
2420}
2421
2422Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2423 bool Changed = SimplifyCommutative(I);
2424 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2425
2426 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2427 // X + 0 --> X
2428 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002429 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002430 (I.getType())->getValueAPF()))
2431 return ReplaceInstUsesWith(I, LHS);
2432 }
2433
2434 if (isa<PHINode>(LHS))
2435 if (Instruction *NV = FoldOpIntoPhi(I))
2436 return NV;
2437 }
2438
2439 // -A + B --> B - A
2440 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002441 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002442 return BinaryOperator::CreateFSub(RHS, LHSV);
2443
2444 // A + -B --> A - B
2445 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002446 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002447 return BinaryOperator::CreateFSub(LHS, V);
2448
2449 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2450 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2451 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2452 return ReplaceInstUsesWith(I, LHS);
2453
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002454 // Check for (add double (sitofp x), y), see if we can merge this into an
2455 // integer add followed by a promotion.
2456 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2457 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2458 // ... if the constant fits in the integer value. This is useful for things
2459 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2460 // requires a constant pool load, and generally allows the add to be better
2461 // instcombined.
2462 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2463 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002464 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002465 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002466 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002467 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2468 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002469 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2470 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002471 return new SIToFPInst(NewAdd, I.getType());
2472 }
2473 }
2474
2475 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2476 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2477 // Only do this if x/y have the same type, if at last one of them has a
2478 // single use (so we don't increase the number of int->fp conversions),
2479 // and if the integer add will not overflow.
2480 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2481 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2482 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2483 RHSConv->getOperand(0))) {
2484 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002485 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2486 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002487 return new SIToFPInst(NewAdd, I.getType());
2488 }
2489 }
2490 }
2491
Chris Lattner7e708292002-06-25 16:13:24 +00002492 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002493}
2494
Chris Lattner7e708292002-06-25 16:13:24 +00002495Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002496 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002497
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002498 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002500
Chris Lattner233f7dc2002-08-12 21:17:25 +00002501 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002502 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002504
Chris Lattnere87597f2004-10-16 18:11:37 +00002505 if (isa<UndefValue>(Op0))
2506 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2507 if (isa<UndefValue>(Op1))
2508 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2509
Chris Lattnerd65460f2003-11-05 01:06:05 +00002510 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2511 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002512 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002513 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002514
Chris Lattnerd65460f2003-11-05 01:06:05 +00002515 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002516 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002517 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002518 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002519
Chris Lattner76b7a062007-01-15 07:02:54 +00002520 // -(X >>u 31) -> (X >>s 31)
2521 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002522 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002523 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002524 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002525 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002526 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002527 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002528 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002529 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002530 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002531 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002532 }
2533 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002534 }
2535 else if (SI->getOpcode() == Instruction::AShr) {
2536 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2537 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002538 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002539 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002540 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002541 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002542 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002543 }
2544 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002545 }
2546 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002547 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002548
2549 // Try to fold constant sub into select arguments.
2550 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002551 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002552 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002553
2554 // C - zext(bool) -> bool ? C - 1 : C
2555 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002556 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002557 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002558 }
2559
Owen Anderson1d0be152009-08-13 21:58:54 +00002560 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002561 return BinaryOperator::CreateXor(Op0, Op1);
2562
Chris Lattner43d84d62005-04-07 16:15:25 +00002563 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002564 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002565 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002566 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002567 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002568 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002569 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002570 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002571 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2572 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2573 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002574 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002575 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002576 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002577 }
2578
Chris Lattnerfd059242003-10-15 16:48:29 +00002579 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002580 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2581 // is not used by anyone else...
2582 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002583 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002584 // Swap the two operands of the subexpr...
2585 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2586 Op1I->setOperand(0, IIOp1);
2587 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002588
Chris Lattnera2881962003-02-18 19:28:33 +00002589 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002590 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002591 }
2592
2593 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2594 //
2595 if (Op1I->getOpcode() == Instruction::And &&
2596 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2597 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2598
Chris Lattner74381062009-08-30 07:44:24 +00002599 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002600 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002601 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002602
Reid Spencerac5209e2006-10-16 23:08:08 +00002603 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002604 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002605 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002606 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002607 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002608 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002609 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002610
Chris Lattnerad3448c2003-02-18 19:57:07 +00002611 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002612 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002613 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002614 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002615 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002616 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002617 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002618 }
Chris Lattner40371712002-05-09 01:29:19 +00002619 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002620 }
Chris Lattnera2881962003-02-18 19:28:33 +00002621
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002622 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2623 if (Op0I->getOpcode() == Instruction::Add) {
2624 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2625 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2626 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2627 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2628 } else if (Op0I->getOpcode() == Instruction::Sub) {
2629 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002630 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002631 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002632 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002633 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002634
Chris Lattner50af16a2004-11-13 19:50:12 +00002635 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002636 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002637 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002638 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002639
Chris Lattner50af16a2004-11-13 19:50:12 +00002640 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002641 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002642 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002643 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002644 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002645}
2646
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002647Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002651 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002652 return BinaryOperator::CreateFAdd(Op0, V);
2653
2654 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2655 if (Op1I->getOpcode() == Instruction::FAdd) {
2656 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002657 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002658 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002659 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002660 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002661 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002662 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002663 }
2664
2665 return 0;
2666}
2667
Chris Lattnera0141b92007-07-15 20:42:37 +00002668/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2669/// comparison only checks the sign bit. If it only checks the sign bit, set
2670/// TrueIfSigned if the result of the comparison is true when the input value is
2671/// signed.
2672static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2673 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002674 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002675 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2676 TrueIfSigned = true;
2677 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002678 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2679 TrueIfSigned = true;
2680 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002681 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2682 TrueIfSigned = false;
2683 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002684 case ICmpInst::ICMP_UGT:
2685 // True if LHS u> RHS and RHS == high-bit-mask - 1
2686 TrueIfSigned = true;
2687 return RHS->getValue() ==
2688 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2689 case ICmpInst::ICMP_UGE:
2690 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2691 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002692 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002693 default:
2694 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002695 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002696}
2697
Chris Lattner7e708292002-06-25 16:13:24 +00002698Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002699 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002700 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002701
Chris Lattnera2498472009-10-11 21:36:10 +00002702 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002703 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002704
Chris Lattner8af304a2009-10-11 07:53:15 +00002705 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002706 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2707 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002708
2709 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002710 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002711 if (SI->getOpcode() == Instruction::Shl)
2712 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002713 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002714 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002715
Zhou Sheng843f07672007-04-19 05:39:12 +00002716 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002717 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002718 if (CI->equalsInt(1)) // X * 1 == X
2719 return ReplaceInstUsesWith(I, Op0);
2720 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002721 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002722
Zhou Sheng97b52c22007-03-29 01:57:21 +00002723 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002724 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002725 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002726 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002727 }
Chris Lattnera2498472009-10-11 21:36:10 +00002728 } else if (isa<VectorType>(Op1C->getType())) {
2729 if (Op1C->isNullValue())
2730 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002731
Chris Lattnera2498472009-10-11 21:36:10 +00002732 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002733 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002734 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002735
2736 // As above, vector X*splat(1.0) -> X in all defined cases.
2737 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002738 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2739 if (CI->equalsInt(1))
2740 return ReplaceInstUsesWith(I, Op0);
2741 }
2742 }
Chris Lattnera2881962003-02-18 19:28:33 +00002743 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002744
2745 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2746 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002747 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002748 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002749 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2750 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002751 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002752
2753 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002754
2755 // Try to fold constant mul into select arguments.
2756 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002757 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002758 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002759
2760 if (isa<PHINode>(Op0))
2761 if (Instruction *NV = FoldOpIntoPhi(I))
2762 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002763 }
2764
Dan Gohman186a6362009-08-12 16:04:34 +00002765 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002766 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002768
Nick Lewycky0c730792008-11-21 07:33:58 +00002769 // (X / Y) * Y = X - (X % Y)
2770 // (X / Y) * -Y = (X % Y) - X
2771 {
Chris Lattnera2498472009-10-11 21:36:10 +00002772 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002773 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2774 if (!BO ||
2775 (BO->getOpcode() != Instruction::UDiv &&
2776 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002777 Op1C = Op0;
2778 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002779 }
Chris Lattnera2498472009-10-11 21:36:10 +00002780 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002781 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002782 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002783 (BO->getOpcode() == Instruction::UDiv ||
2784 BO->getOpcode() == Instruction::SDiv)) {
2785 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2786
Dan Gohmanfa94b942009-08-12 16:33:09 +00002787 // If the division is exact, X % Y is zero.
2788 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2789 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002790 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002791 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002792 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002793 }
2794
Chris Lattner74381062009-08-30 07:44:24 +00002795 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002796 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002797 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002798 else
Chris Lattner74381062009-08-30 07:44:24 +00002799 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002800 Rem->takeName(BO);
2801
Chris Lattnera2498472009-10-11 21:36:10 +00002802 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002803 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002804 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002805 }
2806 }
2807
Chris Lattner8af304a2009-10-11 07:53:15 +00002808 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002809 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002810 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002811
Chris Lattner8af304a2009-10-11 07:53:15 +00002812 // X*(1 << Y) --> X << Y
2813 // (1 << Y)*X --> X << Y
2814 {
2815 Value *Y;
2816 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002817 return BinaryOperator::CreateShl(Op1, Y);
2818 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002819 return BinaryOperator::CreateShl(Op0, Y);
2820 }
2821
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002822 // If one of the operands of the multiply is a cast from a boolean value, then
2823 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002824 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2825 if (!isa<VectorType>(I.getType())) {
2826 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00002827 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002828
Chris Lattnerd2c58362009-10-11 21:29:45 +00002829 Value *BoolCast = 0, *OtherOp = 0;
2830 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002831 BoolCast = Op0, OtherOp = Op1;
2832 else if (MaskedValueIsZero(Op1, Negative2))
2833 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002834
Chris Lattner0036e3a2009-10-11 21:22:21 +00002835 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002836 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2837 BoolCast, "tmp");
2838 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002839 }
2840 }
2841
Chris Lattner7e708292002-06-25 16:13:24 +00002842 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002843}
2844
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002845Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2846 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002847 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002848
2849 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002850 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2851 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002852 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2853 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2854 if (Op1F->isExactlyValue(1.0))
2855 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002856 } else if (isa<VectorType>(Op1C->getType())) {
2857 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002858 // As above, vector X*splat(1.0) -> X in all defined cases.
2859 if (Constant *Splat = Op1V->getSplatValue()) {
2860 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2861 if (F->isExactlyValue(1.0))
2862 return ReplaceInstUsesWith(I, Op0);
2863 }
2864 }
2865 }
2866
2867 // Try to fold constant mul into select arguments.
2868 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2869 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2870 return R;
2871
2872 if (isa<PHINode>(Op0))
2873 if (Instruction *NV = FoldOpIntoPhi(I))
2874 return NV;
2875 }
2876
Dan Gohman186a6362009-08-12 16:04:34 +00002877 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002878 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002879 return BinaryOperator::CreateFMul(Op0v, Op1v);
2880
2881 return Changed ? &I : 0;
2882}
2883
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002884/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2885/// instruction.
2886bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2887 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2888
2889 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2890 int NonNullOperand = -1;
2891 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2892 if (ST->isNullValue())
2893 NonNullOperand = 2;
2894 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2895 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2896 if (ST->isNullValue())
2897 NonNullOperand = 1;
2898
2899 if (NonNullOperand == -1)
2900 return false;
2901
2902 Value *SelectCond = SI->getOperand(0);
2903
2904 // Change the div/rem to use 'Y' instead of the select.
2905 I.setOperand(1, SI->getOperand(NonNullOperand));
2906
2907 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2908 // problem. However, the select, or the condition of the select may have
2909 // multiple uses. Based on our knowledge that the operand must be non-zero,
2910 // propagate the known value for the select into other uses of it, and
2911 // propagate a known value of the condition into its other users.
2912
2913 // If the select and condition only have a single use, don't bother with this,
2914 // early exit.
2915 if (SI->use_empty() && SelectCond->hasOneUse())
2916 return true;
2917
2918 // Scan the current block backward, looking for other uses of SI.
2919 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2920
2921 while (BBI != BBFront) {
2922 --BBI;
2923 // If we found a call to a function, we can't assume it will return, so
2924 // information from below it cannot be propagated above it.
2925 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2926 break;
2927
2928 // Replace uses of the select or its condition with the known values.
2929 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2930 I != E; ++I) {
2931 if (*I == SI) {
2932 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002933 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002934 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002935 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2936 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002937 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002938 }
2939 }
2940
2941 // If we past the instruction, quit looking for it.
2942 if (&*BBI == SI)
2943 SI = 0;
2944 if (&*BBI == SelectCond)
2945 SelectCond = 0;
2946
2947 // If we ran out of things to eliminate, break out of the loop.
2948 if (SelectCond == 0 && SI == 0)
2949 break;
2950
2951 }
2952 return true;
2953}
2954
2955
Reid Spencer1628cec2006-10-26 06:15:43 +00002956/// This function implements the transforms on div instructions that work
2957/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2958/// used by the visitors to those instructions.
2959/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002960Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002961 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002962
Chris Lattner50b2ca42008-02-19 06:12:18 +00002963 // undef / X -> 0 for integer.
2964 // undef / X -> undef for FP (the undef could be a snan).
2965 if (isa<UndefValue>(Op0)) {
2966 if (Op0->getType()->isFPOrFPVector())
2967 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002969 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002970
2971 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002972 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002973 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002974
Reid Spencer1628cec2006-10-26 06:15:43 +00002975 return 0;
2976}
Misha Brukmanfd939082005-04-21 23:48:37 +00002977
Reid Spencer1628cec2006-10-26 06:15:43 +00002978/// This function implements the transforms common to both integer division
2979/// instructions (udiv and sdiv). It is called by the visitors to those integer
2980/// division instructions.
2981/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002982Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2984
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002985 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002986 if (Op0 == Op1) {
2987 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002988 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002989 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002990 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002991 }
2992
Owen Andersoneed707b2009-07-24 23:12:02 +00002993 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002994 return ReplaceInstUsesWith(I, CI);
2995 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002996
Reid Spencer1628cec2006-10-26 06:15:43 +00002997 if (Instruction *Common = commonDivTransforms(I))
2998 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002999
3000 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3001 // This does not apply for fdiv.
3002 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3003 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003004
3005 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3006 // div X, 1 == X
3007 if (RHS->equalsInt(1))
3008 return ReplaceInstUsesWith(I, Op0);
3009
3010 // (X / C1) / C2 -> X / (C1*C2)
3011 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3012 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3013 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003014 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003015 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003017 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003018 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003019 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003020 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003021
Reid Spencerbca0e382007-03-23 20:05:17 +00003022 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003023 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3025 return R;
3026 if (isa<PHINode>(Op0))
3027 if (Instruction *NV = FoldOpIntoPhi(I))
3028 return NV;
3029 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003030 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003031
Chris Lattnera2881962003-02-18 19:28:33 +00003032 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003033 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003034 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003035 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003036
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003037 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003038 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003039 return ReplaceInstUsesWith(I, Op0);
3040
Nick Lewycky895f0852008-11-27 20:21:08 +00003041 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3042 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3043 // div X, 1 == X
3044 if (X->isOne())
3045 return ReplaceInstUsesWith(I, Op0);
3046 }
3047
Reid Spencer1628cec2006-10-26 06:15:43 +00003048 return 0;
3049}
3050
3051Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053
3054 // Handle the integer div common cases
3055 if (Instruction *Common = commonIDivTransforms(I))
3056 return Common;
3057
Reid Spencer1628cec2006-10-26 06:15:43 +00003058 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003059 // X udiv C^2 -> X >> C
3060 // Check to see if this is an unsigned division with an exact power of 2,
3061 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003062 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003063 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003064 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003065
3066 // X udiv C, where C >= signbit
3067 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003068 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003069 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003070 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003071 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003072 }
3073
3074 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003075 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 if (RHSI->getOpcode() == Instruction::Shl &&
3077 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003078 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003079 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003080 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003081 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003082 if (uint32_t C2 = C1.logBase2())
3083 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003084 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003085 }
3086 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003087 }
3088
Reid Spencer1628cec2006-10-26 06:15:43 +00003089 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3090 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003091 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003092 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003093 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003094 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003095 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003096 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003097 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003098 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003099 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003100 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003101
3102 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003103 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003104 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003105
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003106 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003107 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003108 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003109 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110 return 0;
3111}
3112
Reid Spencer1628cec2006-10-26 06:15:43 +00003113Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3115
3116 // Handle the integer div common cases
3117 if (Instruction *Common = commonIDivTransforms(I))
3118 return Common;
3119
3120 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3121 // sdiv X, -1 == -X
3122 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003123 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003124
Dan Gohmanfa94b942009-08-12 16:33:09 +00003125 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003126 if (cast<SDivOperator>(&I)->isExact() &&
3127 RHS->getValue().isNonNegative() &&
3128 RHS->getValue().isPowerOf2()) {
3129 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3130 RHS->getValue().exactLogBase2());
3131 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3132 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003133
3134 // -X/C --> X/-C provided the negation doesn't overflow.
3135 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3136 if (isa<Constant>(Sub->getOperand(0)) &&
3137 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003138 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003139 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3140 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003141 }
3142
3143 // If the sign bits of both operands are zero (i.e. we can prove they are
3144 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003145 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003146 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003147 if (MaskedValueIsZero(Op0, Mask)) {
3148 if (MaskedValueIsZero(Op1, Mask)) {
3149 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3150 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3151 }
3152 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003153 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003154 ShiftedInt->getValue().isPowerOf2()) {
3155 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3156 // Safe because the only negative value (1 << Y) can take on is
3157 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3158 // the sign bit set.
3159 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3160 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003161 }
Eli Friedman8be17392009-07-18 09:53:21 +00003162 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003163
3164 return 0;
3165}
3166
3167Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3168 return commonDivTransforms(I);
3169}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003170
Reid Spencer0a783f72006-11-02 01:53:59 +00003171/// This function implements the transforms on rem instructions that work
3172/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3173/// is used by the visitors to those instructions.
3174/// @brief Transforms common to all three rem instructions
3175Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003176 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003177
Chris Lattner50b2ca42008-02-19 06:12:18 +00003178 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3179 if (I.getType()->isFPOrFPVector())
3180 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003182 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003183 if (isa<UndefValue>(Op1))
3184 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003185
3186 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003187 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3188 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003189
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 return 0;
3191}
3192
3193/// This function implements the transforms common to both integer remainder
3194/// instructions (urem and srem). It is called by the visitors to those integer
3195/// remainder instructions.
3196/// @brief Common integer remainder transforms
3197Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3198 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3199
3200 if (Instruction *common = commonRemTransforms(I))
3201 return common;
3202
Dale Johannesened6af242009-01-21 00:35:19 +00003203 // 0 % X == 0 for integer, we don't need to preserve faults!
3204 if (Constant *LHS = dyn_cast<Constant>(Op0))
3205 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003206 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003207
Chris Lattner857e8cd2004-12-12 21:48:58 +00003208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003209 // X % 0 == undef, we don't need to preserve faults!
3210 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003211 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003212
Chris Lattnera2881962003-02-18 19:28:33 +00003213 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003214 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003215
Chris Lattner97943922006-02-28 05:49:21 +00003216 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3217 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3218 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3219 return R;
3220 } else if (isa<PHINode>(Op0I)) {
3221 if (Instruction *NV = FoldOpIntoPhi(I))
3222 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003223 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003224
3225 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003226 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003227 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003228 }
Chris Lattnera2881962003-02-18 19:28:33 +00003229 }
3230
Reid Spencer0a783f72006-11-02 01:53:59 +00003231 return 0;
3232}
3233
3234Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3236
3237 if (Instruction *common = commonIRemTransforms(I))
3238 return common;
3239
3240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3241 // X urem C^2 -> X and C
3242 // Check to see if this is an unsigned remainder with an exact power of 2,
3243 // if so, convert to a bitwise and.
3244 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003245 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003246 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003247 }
3248
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003249 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003250 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3251 if (RHSI->getOpcode() == Instruction::Shl &&
3252 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003253 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003254 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003255 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003256 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003257 }
3258 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003259 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003260
Reid Spencer0a783f72006-11-02 01:53:59 +00003261 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3262 // where C1&C2 are powers of two.
3263 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3264 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3265 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3266 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003267 if ((STO->getValue().isPowerOf2()) &&
3268 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003269 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3270 SI->getName()+".t");
3271 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3272 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003273 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 }
3275 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003276 }
3277
Chris Lattner3f5b8772002-05-06 16:14:14 +00003278 return 0;
3279}
3280
Reid Spencer0a783f72006-11-02 01:53:59 +00003281Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3283
Dan Gohmancff55092007-11-05 23:16:33 +00003284 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003285 if (Instruction *Common = commonIRemTransforms(I))
3286 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003287
Dan Gohman186a6362009-08-12 16:04:34 +00003288 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003289 if (!isa<Constant>(RHSNeg) ||
3290 (isa<ConstantInt>(RHSNeg) &&
3291 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003292 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003293 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003294 I.setOperand(1, RHSNeg);
3295 return &I;
3296 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003297
Dan Gohmancff55092007-11-05 23:16:33 +00003298 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003299 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003300 if (I.getType()->isInteger()) {
3301 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3302 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3303 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003304 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003305 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003306 }
3307
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003308 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003309 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3310 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003311
Nick Lewycky9dce8732008-12-20 16:48:00 +00003312 bool hasNegative = false;
3313 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3314 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3315 if (RHS->getValue().isNegative())
3316 hasNegative = true;
3317
3318 if (hasNegative) {
3319 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003320 for (unsigned i = 0; i != VWidth; ++i) {
3321 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3322 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003323 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003324 else
3325 Elts[i] = RHS;
3326 }
3327 }
3328
Owen Andersonaf7ec972009-07-28 21:19:26 +00003329 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003330 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003331 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003332 I.setOperand(1, NewRHSV);
3333 return &I;
3334 }
3335 }
3336 }
3337
Reid Spencer0a783f72006-11-02 01:53:59 +00003338 return 0;
3339}
3340
3341Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003342 return commonRemTransforms(I);
3343}
3344
Chris Lattner457dd822004-06-09 07:59:58 +00003345// isOneBitSet - Return true if there is exactly one bit set in the specified
3346// constant.
3347static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003348 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003349}
3350
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003351// isHighOnes - Return true if the constant is of the form 1+0+.
3352// This is the same as lowones(~X).
3353static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003354 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003355}
3356
Reid Spencere4d87aa2006-12-23 06:05:41 +00003357/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003358/// are carefully arranged to allow folding of expressions such as:
3359///
3360/// (A < B) | (A > B) --> (A != B)
3361///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003362/// Note that this is only valid if the first and second predicates have the
3363/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003364///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003365/// Three bits are used to represent the condition, as follows:
3366/// 0 A > B
3367/// 1 A == B
3368/// 2 A < B
3369///
3370/// <=> Value Definition
3371/// 000 0 Always false
3372/// 001 1 A > B
3373/// 010 2 A == B
3374/// 011 3 A >= B
3375/// 100 4 A < B
3376/// 101 5 A != B
3377/// 110 6 A <= B
3378/// 111 7 Always true
3379///
3380static unsigned getICmpCode(const ICmpInst *ICI) {
3381 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003382 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383 case ICmpInst::ICMP_UGT: return 1; // 001
3384 case ICmpInst::ICMP_SGT: return 1; // 001
3385 case ICmpInst::ICMP_EQ: return 2; // 010
3386 case ICmpInst::ICMP_UGE: return 3; // 011
3387 case ICmpInst::ICMP_SGE: return 3; // 011
3388 case ICmpInst::ICMP_ULT: return 4; // 100
3389 case ICmpInst::ICMP_SLT: return 4; // 100
3390 case ICmpInst::ICMP_NE: return 5; // 101
3391 case ICmpInst::ICMP_ULE: return 6; // 110
3392 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003393 // True -> 7
3394 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003395 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003396 return 0;
3397 }
3398}
3399
Evan Cheng8db90722008-10-14 17:15:11 +00003400/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3401/// predicate into a three bit mask. It also returns whether it is an ordered
3402/// predicate by reference.
3403static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3404 isOrdered = false;
3405 switch (CC) {
3406 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3407 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003408 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3409 case FCmpInst::FCMP_UGT: return 1; // 001
3410 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3411 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003412 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3413 case FCmpInst::FCMP_UGE: return 3; // 011
3414 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3415 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003416 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3417 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003418 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3419 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003420 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003421 default:
3422 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003423 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003424 return 0;
3425 }
3426}
3427
Reid Spencere4d87aa2006-12-23 06:05:41 +00003428/// getICmpValue - This is the complement of getICmpCode, which turns an
3429/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003430/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003431/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003432static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003433 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003434 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003435 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003436 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003437 case 1:
3438 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003439 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003440 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003441 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3442 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003443 case 3:
3444 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003445 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003446 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003447 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003448 case 4:
3449 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003450 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003452 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3453 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003454 case 6:
3455 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003456 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003458 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003459 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003460 }
3461}
3462
Evan Cheng8db90722008-10-14 17:15:11 +00003463/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3464/// opcode and two operands into either a FCmp instruction. isordered is passed
3465/// in to determine which kind of predicate to use in the new fcmp instruction.
3466static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003467 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003468 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003469 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003470 case 0:
3471 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003472 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003473 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003474 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003475 case 1:
3476 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003477 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003478 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003479 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003480 case 2:
3481 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003482 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003483 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003484 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003485 case 3:
3486 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003487 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003488 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003489 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003490 case 4:
3491 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003492 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003493 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003494 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003495 case 5:
3496 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003497 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003498 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003499 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003500 case 6:
3501 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003502 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003503 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003504 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003505 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003506 }
3507}
3508
Chris Lattnerb9553d62008-11-16 04:55:20 +00003509/// PredicatesFoldable - Return true if both predicates match sign or if at
3510/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003511static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3512 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003513 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3514 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003515}
3516
3517namespace {
3518// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3519struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003520 InstCombiner &IC;
3521 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003522 ICmpInst::Predicate pred;
3523 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3524 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3525 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003526 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003527 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3528 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003529 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3530 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003531 return false;
3532 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003533 Instruction *apply(Instruction &Log) const {
3534 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3535 if (ICI->getOperand(0) != LHS) {
3536 assert(ICI->getOperand(1) == LHS);
3537 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003538 }
3539
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003540 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003541 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003542 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003543 unsigned Code;
3544 switch (Log.getOpcode()) {
3545 case Instruction::And: Code = LHSCode & RHSCode; break;
3546 case Instruction::Or: Code = LHSCode | RHSCode; break;
3547 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003548 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003549 }
3550
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003551 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3552 ICmpInst::isSignedPredicate(ICI->getPredicate());
3553
Owen Andersond672ecb2009-07-03 00:17:18 +00003554 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003555 if (Instruction *I = dyn_cast<Instruction>(RV))
3556 return I;
3557 // Otherwise, it's a constant boolean value...
3558 return IC.ReplaceInstUsesWith(Log, RV);
3559 }
3560};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003561} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003562
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3564// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003565// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003567 ConstantInt *OpRHS,
3568 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569 BinaryOperator &TheAnd) {
3570 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003571 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003572 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003573 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003574
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003575 switch (Op->getOpcode()) {
3576 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003577 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003578 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003579 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003580 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003581 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003582 }
3583 break;
3584 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003585 if (Together == AndRHS) // (X | C) & C --> C
3586 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003587
Chris Lattner6e7ba452005-01-01 16:22:27 +00003588 if (Op->hasOneUse() && Together != OpRHS) {
3589 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003590 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003591 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003592 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003593 }
3594 break;
3595 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003596 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003597 // Adding a one to a single bit bit-field should be turned into an XOR
3598 // of the bit. First thing to check is to see if this AND is with a
3599 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003600 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003601
3602 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003603 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003604 // Ok, at this point, we know that we are masking the result of the
3605 // ADD down to exactly one bit. If the constant we are adding has
3606 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003607 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003608
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003609 // Check to see if any bits below the one bit set in AndRHSV are set.
3610 if ((AddRHS & (AndRHSV-1)) == 0) {
3611 // If not, the only thing that can effect the output of the AND is
3612 // the bit specified by AndRHSV. If that bit is set, the effect of
3613 // the XOR is to toggle the bit. If it is clear, then the ADD has
3614 // no effect.
3615 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3616 TheAnd.setOperand(0, X);
3617 return &TheAnd;
3618 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003619 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003620 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003621 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003622 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003623 }
3624 }
3625 }
3626 }
3627 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003628
3629 case Instruction::Shl: {
3630 // We know that the AND will not produce any of the bits shifted in, so if
3631 // the anded constant includes them, clear them now!
3632 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003633 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003634 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003635 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003636 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003637
Zhou Sheng290bec52007-03-29 08:15:12 +00003638 if (CI->getValue() == ShlMask) {
3639 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003640 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3641 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003642 TheAnd.setOperand(1, CI);
3643 return &TheAnd;
3644 }
3645 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003646 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003647 case Instruction::LShr:
3648 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003649 // We know that the AND will not produce any of the bits shifted in, so if
3650 // the anded constant includes them, clear them now! This only applies to
3651 // unsigned shifts, because a signed shr may bring in set bits!
3652 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003653 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003654 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003655 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003656 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003657
Zhou Sheng290bec52007-03-29 08:15:12 +00003658 if (CI->getValue() == ShrMask) {
3659 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003660 return ReplaceInstUsesWith(TheAnd, Op);
3661 } else if (CI != AndRHS) {
3662 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3663 return &TheAnd;
3664 }
3665 break;
3666 }
3667 case Instruction::AShr:
3668 // Signed shr.
3669 // See if this is shifting in some sign extension, then masking it out
3670 // with an and.
3671 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003672 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003673 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003674 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003675 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003676 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003677 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003678 // Make the argument unsigned.
3679 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003680 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003681 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003682 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003683 }
3684 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003685 }
3686 return 0;
3687}
3688
Chris Lattner8b170942002-08-09 23:47:40 +00003689
Chris Lattnera96879a2004-09-29 17:40:11 +00003690/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3691/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3693/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003694/// insert new instructions.
3695Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003696 bool isSigned, bool Inside,
3697 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003698 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003699 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003700 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701
Chris Lattnera96879a2004-09-29 17:40:11 +00003702 if (Inside) {
3703 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003704 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003705
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003707 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003708 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003710 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003711 }
3712
3713 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003714 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003715 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003716 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003717 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003718 }
3719
3720 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003721 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003722
Reid Spencere4e40032007-03-21 23:19:50 +00003723 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003724 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003725 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003726 ICmpInst::Predicate pred = (isSigned ?
3727 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003728 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003730
Reid Spencere4e40032007-03-21 23:19:50 +00003731 // Emit V-Lo >u Hi-1-Lo
3732 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003733 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003734 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003735 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003736 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003737}
3738
Chris Lattner7203e152005-09-18 07:22:02 +00003739// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3740// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3741// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3742// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003743static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003744 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003745 uint32_t BitWidth = Val->getType()->getBitWidth();
3746 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003747
3748 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003749 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003750 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003751 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003752 return true;
3753}
3754
Chris Lattner7203e152005-09-18 07:22:02 +00003755/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3756/// where isSub determines whether the operator is a sub. If we can fold one of
3757/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003758///
3759/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3760/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3761/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3762///
3763/// return (A +/- B).
3764///
3765Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003766 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003767 Instruction &I) {
3768 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3769 if (!LHSI || LHSI->getNumOperands() != 2 ||
3770 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3771
3772 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3773
3774 switch (LHSI->getOpcode()) {
3775 default: return 0;
3776 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003777 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003778 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003779 if ((Mask->getValue().countLeadingZeros() +
3780 Mask->getValue().countPopulation()) ==
3781 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003782 break;
3783
3784 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3785 // part, we don't need any explicit masks to take them out of A. If that
3786 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003787 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003788 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003789 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003790 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003791 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003792 break;
3793 }
3794 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003795 return 0;
3796 case Instruction::Or:
3797 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003798 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003799 if ((Mask->getValue().countLeadingZeros() +
3800 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003801 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003802 break;
3803 return 0;
3804 }
3805
Chris Lattnerc8e77562005-09-18 04:24:45 +00003806 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003807 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3808 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003809}
3810
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003811/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3812Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3813 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003814 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003815 ConstantInt *LHSCst, *RHSCst;
3816 ICmpInst::Predicate LHSCC, RHSCC;
3817
Chris Lattnerea065fb2008-11-16 05:10:52 +00003818 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003819 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003820 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003821 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003822 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003824
3825 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3826 // where C is a power of 2
3827 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3828 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003829 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003830 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003831 }
3832
3833 // From here on, we only handle:
3834 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3835 if (Val != Val2) return 0;
3836
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3838 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3839 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3840 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3841 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3842 return 0;
3843
3844 // We can't fold (ugt x, C) & (sgt x, C2).
3845 if (!PredicatesFoldable(LHSCC, RHSCC))
3846 return 0;
3847
3848 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003849 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003850 if (ICmpInst::isSignedPredicate(LHSCC) ||
3851 (ICmpInst::isEquality(LHSCC) &&
3852 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003853 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003854 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003855 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3856
3857 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 std::swap(LHS, RHS);
3859 std::swap(LHSCst, RHSCst);
3860 std::swap(LHSCC, RHSCC);
3861 }
3862
3863 // At this point, we know we have have two icmp instructions
3864 // comparing a value against two constants and and'ing the result
3865 // together. Because of the above check, we know that we only have
3866 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3867 // (from the FoldICmpLogical check above), that the two constants
3868 // are not equal and that the larger constant is on the RHS
3869 assert(LHSCst != RHSCst && "Compares not folded above?");
3870
3871 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003872 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003873 case ICmpInst::ICMP_EQ:
3874 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003875 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003876 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3877 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3878 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003879 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3881 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3882 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3883 return ReplaceInstUsesWith(I, LHS);
3884 }
3885 case ICmpInst::ICMP_NE:
3886 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003887 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003888 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003889 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003890 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003891 break; // (X != 13 & X u< 15) -> no change
3892 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003893 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003894 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003895 break; // (X != 13 & X s< 15) -> no change
3896 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3897 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3898 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3899 return ReplaceInstUsesWith(I, RHS);
3900 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003901 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003902 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003903 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003904 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003905 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003906 }
3907 break; // (X != 13 & X != 15) -> no change
3908 }
3909 break;
3910 case ICmpInst::ICMP_ULT:
3911 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003912 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3914 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003915 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3919 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3920 return ReplaceInstUsesWith(I, LHS);
3921 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3922 break;
3923 }
3924 break;
3925 case ICmpInst::ICMP_SLT:
3926 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003927 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003928 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3929 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003930 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3932 break;
3933 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3934 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3935 return ReplaceInstUsesWith(I, LHS);
3936 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3937 break;
3938 }
3939 break;
3940 case ICmpInst::ICMP_UGT:
3941 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003942 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003943 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3944 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3945 return ReplaceInstUsesWith(I, RHS);
3946 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3947 break;
3948 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003949 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003950 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003951 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003952 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003953 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003954 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003955 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3956 break;
3957 }
3958 break;
3959 case ICmpInst::ICMP_SGT:
3960 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003961 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003962 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3963 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3964 return ReplaceInstUsesWith(I, RHS);
3965 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3966 break;
3967 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003968 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003969 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003970 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003971 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003972 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003973 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003974 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3975 break;
3976 }
3977 break;
3978 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003979
3980 return 0;
3981}
3982
Chris Lattner42d1be02009-07-23 05:14:02 +00003983Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3984 FCmpInst *RHS) {
3985
3986 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3987 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3988 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3989 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3990 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3991 // If either of the constants are nans, then the whole thing returns
3992 // false.
3993 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003995 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003996 LHS->getOperand(0), RHS->getOperand(0));
3997 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003998
3999 // Handle vector zeros. This occurs because the canonical form of
4000 // "fcmp ord x,x" is "fcmp ord x, 0".
4001 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4002 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004003 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004004 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004005 return 0;
4006 }
4007
4008 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4009 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4010 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4011
4012
4013 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4014 // Swap RHS operands to match LHS.
4015 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4016 std::swap(Op1LHS, Op1RHS);
4017 }
4018
4019 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4020 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4021 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004022 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004023
4024 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004025 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004026 if (Op0CC == FCmpInst::FCMP_TRUE)
4027 return ReplaceInstUsesWith(I, RHS);
4028 if (Op1CC == FCmpInst::FCMP_TRUE)
4029 return ReplaceInstUsesWith(I, LHS);
4030
4031 bool Op0Ordered;
4032 bool Op1Ordered;
4033 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4034 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4035 if (Op1Pred == 0) {
4036 std::swap(LHS, RHS);
4037 std::swap(Op0Pred, Op1Pred);
4038 std::swap(Op0Ordered, Op1Ordered);
4039 }
4040 if (Op0Pred == 0) {
4041 // uno && ueq -> uno && (uno || eq) -> ueq
4042 // ord && olt -> ord && (ord && lt) -> olt
4043 if (Op0Ordered == Op1Ordered)
4044 return ReplaceInstUsesWith(I, RHS);
4045
4046 // uno && oeq -> uno && (ord && eq) -> false
4047 // uno && ord -> false
4048 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004049 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004050 // ord && ueq -> ord && (uno || eq) -> oeq
4051 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4052 Op0LHS, Op0RHS, Context));
4053 }
4054 }
4055
4056 return 0;
4057}
4058
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004059
Chris Lattner7e708292002-06-25 16:13:24 +00004060Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004061 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004063
Chris Lattnere87597f2004-10-16 18:11:37 +00004064 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004065 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004066
Chris Lattner6e7ba452005-01-01 16:22:27 +00004067 // and X, X = X
4068 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004069 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004070
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004071 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004072 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004073 if (SimplifyDemandedInstructionBits(I))
4074 return &I;
4075 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004076 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004077 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004078 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004079 } else if (isa<ConstantAggregateZero>(Op1)) {
4080 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004081 }
4082 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004083
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004084 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004085 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004086 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004087
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004088 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004089 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004090 Value *Op0LHS = Op0I->getOperand(0);
4091 Value *Op0RHS = Op0I->getOperand(1);
4092 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004093 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004094 case Instruction::Xor:
4095 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004096 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004097 if (!Op0I->hasOneUse()) break;
4098
4099 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4100 // Not masking anything out for the LHS, move to RHS.
4101 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4102 Op0RHS->getName()+".masked");
4103 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4104 }
4105 if (!isa<Constant>(Op0RHS) &&
4106 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4107 // Not masking anything out for the RHS, move to LHS.
4108 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4109 Op0LHS->getName()+".masked");
4110 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004111 }
4112
Chris Lattner6e7ba452005-01-01 16:22:27 +00004113 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004114 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004115 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4116 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4117 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004119 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004120 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004121 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004122 break;
4123
4124 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004125 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4126 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4127 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004129 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004130
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004131 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4132 // has 1's for all bits that the subtraction with A might affect.
4133 if (Op0I->hasOneUse()) {
4134 uint32_t BitWidth = AndRHSMask.getBitWidth();
4135 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4136 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4137
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004138 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004139 if (!(A && A->isZero()) && // avoid infinite recursion.
4140 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004141 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004142 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4143 }
4144 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004145 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004146
4147 case Instruction::Shl:
4148 case Instruction::LShr:
4149 // (1 << x) & 1 --> zext(x == 0)
4150 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004151 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004152 Value *NewICmp =
4153 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004154 return new ZExtInst(NewICmp, I.getType());
4155 }
4156 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004157 }
4158
Chris Lattner58403262003-07-23 19:25:52 +00004159 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004160 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004161 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004162 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004163 // If this is an integer truncation or change from signed-to-unsigned, and
4164 // if the source is an and/or with immediate, transform it. This
4165 // frequently occurs for bitfield accesses.
4166 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004167 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004168 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004169 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004170 if (CastOp->getOpcode() == Instruction::And) {
4171 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004172 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4173 // This will fold the two constants together, which may allow
4174 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004175 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004176 CastOp->getOperand(0), I.getType(),
4177 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004178 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004179 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004180 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004181 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004182 } else if (CastOp->getOpcode() == Instruction::Or) {
4183 // Change: and (cast (or X, C1) to T), C2
4184 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004185 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004186 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004187 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004188 return ReplaceInstUsesWith(I, AndRHS);
4189 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004190 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004191 }
Chris Lattner06782f82003-07-23 19:36:21 +00004192 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004193
4194 // Try to fold constant and into select arguments.
4195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004197 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004198 if (isa<PHINode>(Op0))
4199 if (Instruction *NV = FoldOpIntoPhi(I))
4200 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004201 }
4202
Dan Gohman186a6362009-08-12 16:04:34 +00004203 Value *Op0NotVal = dyn_castNotVal(Op0);
4204 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004205
Chris Lattner5b62aa72004-06-18 06:07:51 +00004206 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004207 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004208
Misha Brukmancb6267b2004-07-30 12:50:08 +00004209 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004210 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004211 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4212 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004213 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004214 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004215
4216 {
Chris Lattner003b6202007-06-15 05:58:24 +00004217 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004218 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004219 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4220 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004221
4222 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004223 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004224 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004225 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004226 }
4227 }
4228
Dan Gohman4ae51262009-08-12 16:23:25 +00004229 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004230 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4231 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004232
4233 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004234 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004235 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004236 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004237 }
4238 }
Chris Lattner64daab52006-04-01 08:03:55 +00004239
4240 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004241 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004242 if (A == Op1) { // (A^B)&A -> A&(A^B)
4243 I.swapOperands(); // Simplify below
4244 std::swap(Op0, Op1);
4245 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4246 cast<BinaryOperator>(Op0)->swapOperands();
4247 I.swapOperands(); // Simplify below
4248 std::swap(Op0, Op1);
4249 }
4250 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004251
Chris Lattner64daab52006-04-01 08:03:55 +00004252 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004253 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004254 if (B == Op0) { // B&(A^B) -> B&(B^A)
4255 cast<BinaryOperator>(Op1)->swapOperands();
4256 std::swap(A, B);
4257 }
Chris Lattner74381062009-08-30 07:44:24 +00004258 if (A == Op0) // A&(A^B) -> A & ~B
4259 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004260 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004261
4262 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004263 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4264 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004265 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004266 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4267 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004268 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004269 }
4270
Reid Spencere4d87aa2006-12-23 06:05:41 +00004271 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4272 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004273 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004274 return R;
4275
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004276 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4277 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4278 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004279 }
4280
Chris Lattner6fc205f2006-05-05 06:39:07 +00004281 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004282 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4283 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4284 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4285 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004286 if (SrcTy == Op1C->getOperand(0)->getType() &&
4287 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004288 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004289 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4290 I.getType(), TD) &&
4291 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4292 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004293 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4294 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004295 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004296 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004297 }
Chris Lattnere511b742006-11-14 07:46:50 +00004298
4299 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004300 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4301 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4302 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004303 SI0->getOperand(1) == SI1->getOperand(1) &&
4304 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004305 Value *NewOp =
4306 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4307 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004308 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004309 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004310 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004311 }
4312
Evan Cheng8db90722008-10-14 17:15:11 +00004313 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004314 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004315 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4316 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4317 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004318 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004319
Chris Lattner7e708292002-06-25 16:13:24 +00004320 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004321}
4322
Chris Lattner8c34cd22008-10-05 02:13:19 +00004323/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4324/// capable of providing pieces of a bswap. The subexpression provides pieces
4325/// of a bswap if it is proven that each of the non-zero bytes in the output of
4326/// the expression came from the corresponding "byte swapped" byte in some other
4327/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4328/// we know that the expression deposits the low byte of %X into the high byte
4329/// of the bswap result and that all other bytes are zero. This expression is
4330/// accepted, the high byte of ByteValues is set to X to indicate a correct
4331/// match.
4332///
4333/// This function returns true if the match was unsuccessful and false if so.
4334/// On entry to the function the "OverallLeftShift" is a signed integer value
4335/// indicating the number of bytes that the subexpression is later shifted. For
4336/// example, if the expression is later right shifted by 16 bits, the
4337/// OverallLeftShift value would be -2 on entry. This is used to specify which
4338/// byte of ByteValues is actually being set.
4339///
4340/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4341/// byte is masked to zero by a user. For example, in (X & 255), X will be
4342/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4343/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4344/// always in the local (OverallLeftShift) coordinate space.
4345///
4346static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4347 SmallVector<Value*, 8> &ByteValues) {
4348 if (Instruction *I = dyn_cast<Instruction>(V)) {
4349 // If this is an or instruction, it may be an inner node of the bswap.
4350 if (I->getOpcode() == Instruction::Or) {
4351 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4352 ByteValues) ||
4353 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4354 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004355 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004356
4357 // If this is a logical shift by a constant multiple of 8, recurse with
4358 // OverallLeftShift and ByteMask adjusted.
4359 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4360 unsigned ShAmt =
4361 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4362 // Ensure the shift amount is defined and of a byte value.
4363 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4364 return true;
4365
4366 unsigned ByteShift = ShAmt >> 3;
4367 if (I->getOpcode() == Instruction::Shl) {
4368 // X << 2 -> collect(X, +2)
4369 OverallLeftShift += ByteShift;
4370 ByteMask >>= ByteShift;
4371 } else {
4372 // X >>u 2 -> collect(X, -2)
4373 OverallLeftShift -= ByteShift;
4374 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004375 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004376 }
4377
4378 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4379 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4380
4381 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4382 ByteValues);
4383 }
4384
4385 // If this is a logical 'and' with a mask that clears bytes, clear the
4386 // corresponding bytes in ByteMask.
4387 if (I->getOpcode() == Instruction::And &&
4388 isa<ConstantInt>(I->getOperand(1))) {
4389 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4390 unsigned NumBytes = ByteValues.size();
4391 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4392 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4393
4394 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4395 // If this byte is masked out by a later operation, we don't care what
4396 // the and mask is.
4397 if ((ByteMask & (1 << i)) == 0)
4398 continue;
4399
4400 // If the AndMask is all zeros for this byte, clear the bit.
4401 APInt MaskB = AndMask & Byte;
4402 if (MaskB == 0) {
4403 ByteMask &= ~(1U << i);
4404 continue;
4405 }
4406
4407 // If the AndMask is not all ones for this byte, it's not a bytezap.
4408 if (MaskB != Byte)
4409 return true;
4410
4411 // Otherwise, this byte is kept.
4412 }
4413
4414 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4415 ByteValues);
4416 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417 }
4418
Chris Lattner8c34cd22008-10-05 02:13:19 +00004419 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4420 // the input value to the bswap. Some observations: 1) if more than one byte
4421 // is demanded from this input, then it could not be successfully assembled
4422 // into a byteswap. At least one of the two bytes would not be aligned with
4423 // their ultimate destination.
4424 if (!isPowerOf2_32(ByteMask)) return true;
4425 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004426
Chris Lattner8c34cd22008-10-05 02:13:19 +00004427 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4428 // is demanded, it needs to go into byte 0 of the result. This means that the
4429 // byte needs to be shifted until it lands in the right byte bucket. The
4430 // shift amount depends on the position: if the byte is coming from the high
4431 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4432 // low part, it must be shifted left.
4433 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4434 if (InputByteNo < ByteValues.size()/2) {
4435 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4436 return true;
4437 } else {
4438 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4439 return true;
4440 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441
4442 // If the destination byte value is already defined, the values are or'd
4443 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004444 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004445 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004446 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004447 return false;
4448}
4449
4450/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4451/// If so, insert the new bswap intrinsic and return it.
4452Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004453 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004454 if (!ITy || ITy->getBitWidth() % 16 ||
4455 // ByteMask only allows up to 32-byte values.
4456 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004457 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004458
4459 /// ByteValues - For each byte of the result, we keep track of which value
4460 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004461 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004462 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004463
4464 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004465 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4466 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004467 return 0;
4468
4469 // Check to see if all of the bytes come from the same value.
4470 Value *V = ByteValues[0];
4471 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4472
4473 // Check to make sure that all of the bytes come from the same value.
4474 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4475 if (ByteValues[i] != V)
4476 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004477 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004478 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004479 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004480 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004481}
4482
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004483/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4484/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4485/// we can simplify this expression to "cond ? C : D or B".
4486static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004487 Value *C, Value *D,
4488 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004489 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004490 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004491 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004492 return 0;
4493
Chris Lattnera6a474d2008-11-16 04:26:55 +00004494 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004495 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004496 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004497 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004498 return SelectInst::Create(Cond, C, B);
4499 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004500 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004501 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004502 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004503 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004504 return 0;
4505}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004506
Chris Lattner69d4ced2008-11-16 05:20:07 +00004507/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4508Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4509 ICmpInst *LHS, ICmpInst *RHS) {
4510 Value *Val, *Val2;
4511 ConstantInt *LHSCst, *RHSCst;
4512 ICmpInst::Predicate LHSCC, RHSCC;
4513
4514 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004515 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004516 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004517 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004518 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004519 return 0;
4520
4521 // From here on, we only handle:
4522 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4523 if (Val != Val2) return 0;
4524
4525 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4526 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4527 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4528 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4529 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4530 return 0;
4531
4532 // We can't fold (ugt x, C) | (sgt x, C2).
4533 if (!PredicatesFoldable(LHSCC, RHSCC))
4534 return 0;
4535
4536 // Ensure that the larger constant is on the RHS.
4537 bool ShouldSwap;
4538 if (ICmpInst::isSignedPredicate(LHSCC) ||
4539 (ICmpInst::isEquality(LHSCC) &&
4540 ICmpInst::isSignedPredicate(RHSCC)))
4541 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4542 else
4543 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4544
4545 if (ShouldSwap) {
4546 std::swap(LHS, RHS);
4547 std::swap(LHSCst, RHSCst);
4548 std::swap(LHSCC, RHSCC);
4549 }
4550
4551 // At this point, we know we have have two icmp instructions
4552 // comparing a value against two constants and or'ing the result
4553 // together. Because of the above check, we know that we only have
4554 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4555 // FoldICmpLogical check above), that the two constants are not
4556 // equal.
4557 assert(LHSCst != RHSCst && "Compares not folded above?");
4558
4559 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004560 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004561 case ICmpInst::ICMP_EQ:
4562 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004563 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004564 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004565 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004566 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004567 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004568 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004569 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004570 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 }
4572 break; // (X == 13 | X == 15) -> no change
4573 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4574 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4575 break;
4576 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4578 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4579 return ReplaceInstUsesWith(I, RHS);
4580 }
4581 break;
4582 case ICmpInst::ICMP_NE:
4583 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004584 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004585 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4586 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4587 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4588 return ReplaceInstUsesWith(I, LHS);
4589 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4590 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4591 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004592 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004593 }
4594 break;
4595 case ICmpInst::ICMP_ULT:
4596 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004597 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004598 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4599 break;
4600 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4601 // If RHSCst is [us]MAXINT, it is always false. Not handling
4602 // this can cause overflow.
4603 if (RHSCst->isMaxValue(false))
4604 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004605 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004606 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004607 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4608 break;
4609 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4610 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4611 return ReplaceInstUsesWith(I, RHS);
4612 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4613 break;
4614 }
4615 break;
4616 case ICmpInst::ICMP_SLT:
4617 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004618 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004619 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4620 break;
4621 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4622 // If RHSCst is [us]MAXINT, it is always false. Not handling
4623 // this can cause overflow.
4624 if (RHSCst->isMaxValue(true))
4625 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004626 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004627 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004628 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4629 break;
4630 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4631 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4632 return ReplaceInstUsesWith(I, RHS);
4633 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4634 break;
4635 }
4636 break;
4637 case ICmpInst::ICMP_UGT:
4638 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004639 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004640 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4641 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4642 return ReplaceInstUsesWith(I, LHS);
4643 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4644 break;
4645 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4646 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004647 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004648 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4649 break;
4650 }
4651 break;
4652 case ICmpInst::ICMP_SGT:
4653 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004654 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004655 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4656 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4657 return ReplaceInstUsesWith(I, LHS);
4658 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4659 break;
4660 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4661 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004663 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4664 break;
4665 }
4666 break;
4667 }
4668 return 0;
4669}
4670
Chris Lattner5414cc52009-07-23 05:46:22 +00004671Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4672 FCmpInst *RHS) {
4673 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4674 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4675 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4676 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4677 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4678 // If either of the constants are nans, then the whole thing returns
4679 // true.
4680 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004681 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004682
4683 // Otherwise, no need to compare the two constants, compare the
4684 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004685 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004686 LHS->getOperand(0), RHS->getOperand(0));
4687 }
4688
4689 // Handle vector zeros. This occurs because the canonical form of
4690 // "fcmp uno x,x" is "fcmp uno x, 0".
4691 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4692 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004693 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004694 LHS->getOperand(0), RHS->getOperand(0));
4695
4696 return 0;
4697 }
4698
4699 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4700 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4701 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4702
4703 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4704 // Swap RHS operands to match LHS.
4705 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4706 std::swap(Op1LHS, Op1RHS);
4707 }
4708 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4709 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4710 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004711 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004712 Op0LHS, Op0RHS);
4713 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004714 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004715 if (Op0CC == FCmpInst::FCMP_FALSE)
4716 return ReplaceInstUsesWith(I, RHS);
4717 if (Op1CC == FCmpInst::FCMP_FALSE)
4718 return ReplaceInstUsesWith(I, LHS);
4719 bool Op0Ordered;
4720 bool Op1Ordered;
4721 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4722 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4723 if (Op0Ordered == Op1Ordered) {
4724 // If both are ordered or unordered, return a new fcmp with
4725 // or'ed predicates.
4726 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4727 Op0LHS, Op0RHS, Context);
4728 if (Instruction *I = dyn_cast<Instruction>(RV))
4729 return I;
4730 // Otherwise, it's a constant boolean value...
4731 return ReplaceInstUsesWith(I, RV);
4732 }
4733 }
4734 return 0;
4735}
4736
Bill Wendlinga698a472008-12-01 08:23:25 +00004737/// FoldOrWithConstants - This helper function folds:
4738///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004739/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004740///
4741/// into:
4742///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004743/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004744///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004745/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004746Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004747 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004748 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4749 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004750
Bill Wendling286a0542008-12-02 06:24:20 +00004751 Value *V1 = 0;
4752 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004753 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004754
Bill Wendling29976b92008-12-02 06:18:11 +00004755 APInt Xor = CI1->getValue() ^ CI2->getValue();
4756 if (!Xor.isAllOnesValue()) return 0;
4757
Bill Wendling286a0542008-12-02 06:24:20 +00004758 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004759 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004760 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004761 }
4762
4763 return 0;
4764}
4765
Chris Lattner7e708292002-06-25 16:13:24 +00004766Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004767 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004768 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004769
Chris Lattner42593e62007-03-24 23:56:43 +00004770 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004771 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004772
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004773 // or X, X = X
4774 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004775 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004776
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004777 // See if we can simplify any instructions used by the instruction whose sole
4778 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004779 if (SimplifyDemandedInstructionBits(I))
4780 return &I;
4781 if (isa<VectorType>(I.getType())) {
4782 if (isa<ConstantAggregateZero>(Op1)) {
4783 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4784 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4785 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4786 return ReplaceInstUsesWith(I, I.getOperand(1));
4787 }
Chris Lattner42593e62007-03-24 23:56:43 +00004788 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004789
Chris Lattner3f5b8772002-05-06 16:14:14 +00004790 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004791 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004792 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004793 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004794 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004795 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004796 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004797 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004798 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004799 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004800 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004801
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004802 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004803 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004805 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004806 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004807 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004808 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004809 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004810
4811 // Try to fold constant and into select arguments.
4812 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004813 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004814 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004815 if (isa<PHINode>(Op0))
4816 if (Instruction *NV = FoldOpIntoPhi(I))
4817 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004818 }
4819
Chris Lattner4f637d42006-01-06 17:59:59 +00004820 Value *A = 0, *B = 0;
4821 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004822
Dan Gohman4ae51262009-08-12 16:23:25 +00004823 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004824 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4825 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004826 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004827 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4828 return ReplaceInstUsesWith(I, Op0);
4829
Chris Lattner6423d4c2006-07-10 20:25:24 +00004830 // (A | B) | C and A | (B | C) -> bswap if possible.
4831 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004832 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4833 match(Op1, m_Or(m_Value(), m_Value())) ||
4834 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4835 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004836 if (Instruction *BSwap = MatchBSwap(I))
4837 return BSwap;
4838 }
4839
Chris Lattner6e4c6492005-05-09 04:58:36 +00004840 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004841 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004842 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004843 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004844 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004845 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004846 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004847 }
4848
4849 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004850 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004851 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004852 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004853 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004854 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004855 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004856 }
4857
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004858 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004859 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004860 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4861 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004862 Value *V1 = 0, *V2 = 0, *V3 = 0;
4863 C1 = dyn_cast<ConstantInt>(C);
4864 C2 = dyn_cast<ConstantInt>(D);
4865 if (C1 && C2) { // (A & C1)|(B & C2)
4866 // If we have: ((V + N) & C1) | (V & C2)
4867 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4868 // replace with V+N.
4869 if (C1->getValue() == ~C2->getValue()) {
4870 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004871 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004872 // Add commutes, try both ways.
4873 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4874 return ReplaceInstUsesWith(I, A);
4875 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4876 return ReplaceInstUsesWith(I, A);
4877 }
4878 // Or commutes, try both ways.
4879 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004880 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004881 // Add commutes, try both ways.
4882 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4883 return ReplaceInstUsesWith(I, B);
4884 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4885 return ReplaceInstUsesWith(I, B);
4886 }
4887 }
Chris Lattner044e5332007-04-08 08:01:49 +00004888 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004889 }
4890
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004891 // Check to see if we have any common things being and'ed. If so, find the
4892 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004893 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4894 if (A == B) // (A & C)|(A & D) == A & (C|D)
4895 V1 = A, V2 = C, V3 = D;
4896 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4897 V1 = A, V2 = B, V3 = C;
4898 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4899 V1 = C, V2 = A, V3 = D;
4900 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4901 V1 = C, V2 = A, V3 = B;
4902
4903 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004904 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004905 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004906 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004907 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004908
Dan Gohman1975d032008-10-30 20:40:10 +00004909 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004910 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004911 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004912 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004913 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004914 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004915 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004916 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004917 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004918
Bill Wendlingb01865c2008-11-30 13:52:49 +00004919 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004920 if ((match(C, m_Not(m_Specific(D))) &&
4921 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004922 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004923 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004924 if ((match(A, m_Not(m_Specific(D))) &&
4925 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004926 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004927 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004928 if ((match(C, m_Not(m_Specific(B))) &&
4929 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004930 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004931 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004932 if ((match(A, m_Not(m_Specific(B))) &&
4933 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004934 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004935 }
Chris Lattnere511b742006-11-14 07:46:50 +00004936
4937 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004938 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4939 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4940 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004941 SI0->getOperand(1) == SI1->getOperand(1) &&
4942 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004943 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4944 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004945 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004946 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004947 }
4948 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004949
Bill Wendlingb3833d12008-12-01 01:07:11 +00004950 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004951 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4952 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004953 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004954 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004955 }
4956 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004957 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4958 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004959 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004960 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004961 }
4962
Dan Gohman4ae51262009-08-12 16:23:25 +00004963 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004964 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004965 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004966 } else {
4967 A = 0;
4968 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004969 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004970 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004971 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004972 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004973
Misha Brukmancb6267b2004-07-30 12:50:08 +00004974 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004975 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004976 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004977 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004978 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004979 }
Chris Lattnera2881962003-02-18 19:28:33 +00004980
Reid Spencere4d87aa2006-12-23 06:05:41 +00004981 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4982 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004983 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004984 return R;
4985
Chris Lattner69d4ced2008-11-16 05:20:07 +00004986 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4987 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4988 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004989 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004990
4991 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004992 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004993 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004994 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004995 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4996 !isa<ICmpInst>(Op1C->getOperand(0))) {
4997 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004998 if (SrcTy == Op1C->getOperand(0)->getType() &&
4999 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005000 // Only do this if the casts both really cause code to be
5001 // generated.
5002 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5003 I.getType(), TD) &&
5004 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5005 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005006 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5007 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005008 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005009 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005010 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005011 }
Chris Lattner99c65742007-10-24 05:38:08 +00005012 }
5013
5014
5015 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5016 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005017 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5018 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5019 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005020 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005021
Chris Lattner7e708292002-06-25 16:13:24 +00005022 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005023}
5024
Dan Gohman844731a2008-05-13 00:00:25 +00005025namespace {
5026
Chris Lattnerc317d392004-02-16 01:20:27 +00005027// XorSelf - Implements: X ^ X --> 0
5028struct XorSelf {
5029 Value *RHS;
5030 XorSelf(Value *rhs) : RHS(rhs) {}
5031 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5032 Instruction *apply(BinaryOperator &Xor) const {
5033 return &Xor;
5034 }
5035};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005036
Dan Gohman844731a2008-05-13 00:00:25 +00005037}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005038
Chris Lattner7e708292002-06-25 16:13:24 +00005039Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005040 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005042
Evan Chengd34af782008-03-25 20:07:13 +00005043 if (isa<UndefValue>(Op1)) {
5044 if (isa<UndefValue>(Op0))
5045 // Handle undef ^ undef -> 0 special case. This is a common
5046 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005048 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005049 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005050
Chris Lattnerc317d392004-02-16 01:20:27 +00005051 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005052 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005053 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005054 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005055 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005056
5057 // See if we can simplify any instructions used by the instruction whose sole
5058 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005059 if (SimplifyDemandedInstructionBits(I))
5060 return &I;
5061 if (isa<VectorType>(I.getType()))
5062 if (isa<ConstantAggregateZero>(Op1))
5063 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005064
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005065 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005066 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005067 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5068 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5069 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5070 if (Op0I->getOpcode() == Instruction::And ||
5071 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005072 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5073 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005074 Value *NotY =
5075 Builder->CreateNot(Op0I->getOperand(1),
5076 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005077 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005078 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005079 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005080 }
5081 }
5082 }
5083 }
5084
5085
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005086 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005087 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005088 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005089 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005090 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005091 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005092
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005093 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005094 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005095 FCI->getOperand(0), FCI->getOperand(1));
5096 }
5097
Nick Lewycky517e1f52008-05-31 19:01:33 +00005098 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5099 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5100 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5101 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5102 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005103 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5104 (RHS == ConstantExpr::getCast(Opcode,
5105 ConstantInt::getTrue(*Context),
5106 Op0C->getDestTy()))) {
5107 CI->setPredicate(CI->getInversePredicate());
5108 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005109 }
5110 }
5111 }
5112 }
5113
Reid Spencere4d87aa2006-12-23 06:05:41 +00005114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005115 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005116 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5117 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005118 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5119 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005120 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005121 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005122 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005123
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005124 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005125 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005126 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005127 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005128 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005129 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005130 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005131 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005132 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005133 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005134 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005135 Constant *C = ConstantInt::get(*Context,
5136 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005137 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005138
Chris Lattner7c4049c2004-01-12 19:35:11 +00005139 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005140 } else if (Op0I->getOpcode() == Instruction::Or) {
5141 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005142 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005143 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005144 // Anything in both C1 and C2 is known to be zero, remove it from
5145 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005146 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5147 NewRHS = ConstantExpr::getAnd(NewRHS,
5148 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005149 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005150 I.setOperand(0, Op0I->getOperand(0));
5151 I.setOperand(1, NewRHS);
5152 return &I;
5153 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005154 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005155 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005156 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005157
5158 // Try to fold constant and into select arguments.
5159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005161 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005162 if (isa<PHINode>(Op0))
5163 if (Instruction *NV = FoldOpIntoPhi(I))
5164 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005165 }
5166
Dan Gohman186a6362009-08-12 16:04:34 +00005167 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005168 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005169 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005170
Dan Gohman186a6362009-08-12 16:04:34 +00005171 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005172 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005173 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005174
Chris Lattner318bf792007-03-18 22:51:34 +00005175
5176 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5177 if (Op1I) {
5178 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005179 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005180 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005181 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005182 I.swapOperands();
5183 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005184 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005185 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005186 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005187 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005188 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005189 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005190 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005191 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005192 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005193 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005194 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005195 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005196 std::swap(A, B);
5197 }
Chris Lattner318bf792007-03-18 22:51:34 +00005198 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005199 I.swapOperands(); // Simplified below.
5200 std::swap(Op0, Op1);
5201 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005202 }
Chris Lattner318bf792007-03-18 22:51:34 +00005203 }
5204
5205 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5206 if (Op0I) {
5207 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005208 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005209 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005210 if (A == Op1) // (B|A)^B == (A|B)^B
5211 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005212 if (B == Op1) // (A|B)^B == A & ~B
5213 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005214 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005215 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005216 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005217 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005218 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005219 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005220 if (A == Op1) // (A&B)^A -> (B&A)^A
5221 std::swap(A, B);
5222 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005223 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005224 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005225 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005226 }
Chris Lattner318bf792007-03-18 22:51:34 +00005227 }
5228
5229 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5230 if (Op0I && Op1I && Op0I->isShift() &&
5231 Op0I->getOpcode() == Op1I->getOpcode() &&
5232 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005234 Value *NewOp =
5235 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5236 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005237 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005238 Op1I->getOperand(1));
5239 }
5240
5241 if (Op0I && Op1I) {
5242 Value *A, *B, *C, *D;
5243 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005244 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5245 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005246 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005247 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005248 }
5249 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005250 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5251 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005252 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005253 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005254 }
5255
5256 // (A & B)^(C & D)
5257 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005258 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5259 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005260 // (X & Y)^(X & Y) -> (Y^Z) & X
5261 Value *X = 0, *Y = 0, *Z = 0;
5262 if (A == C)
5263 X = A, Y = B, Z = D;
5264 else if (A == D)
5265 X = A, Y = B, Z = C;
5266 else if (B == C)
5267 X = B, Y = A, Z = D;
5268 else if (B == D)
5269 X = B, Y = A, Z = C;
5270
5271 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005272 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005273 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005274 }
5275 }
5276 }
5277
Reid Spencere4d87aa2006-12-23 06:05:41 +00005278 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005280 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005281 return R;
5282
Chris Lattner6fc205f2006-05-05 06:39:07 +00005283 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005284 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005285 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005286 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005288 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005289 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5291 I.getType(), TD) &&
5292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5293 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005294 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5295 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005296 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005297 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005298 }
Chris Lattner99c65742007-10-24 05:38:08 +00005299 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005300
Chris Lattner7e708292002-06-25 16:13:24 +00005301 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005302}
5303
Owen Andersond672ecb2009-07-03 00:17:18 +00005304static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005305 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005306 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005307}
Chris Lattnera96879a2004-09-29 17:40:11 +00005308
Dan Gohman6de29f82009-06-15 22:12:54 +00005309static bool HasAddOverflow(ConstantInt *Result,
5310 ConstantInt *In1, ConstantInt *In2,
5311 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005312 if (IsSigned)
5313 if (In2->getValue().isNegative())
5314 return Result->getValue().sgt(In1->getValue());
5315 else
5316 return Result->getValue().slt(In1->getValue());
5317 else
5318 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005319}
5320
Dan Gohman6de29f82009-06-15 22:12:54 +00005321/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005322/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005323static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005324 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005325 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005326 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005327
Dan Gohman6de29f82009-06-15 22:12:54 +00005328 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5329 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005330 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005331 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5332 ExtractElement(In1, Idx, Context),
5333 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005334 IsSigned))
5335 return true;
5336 }
5337 return false;
5338 }
5339
5340 return HasAddOverflow(cast<ConstantInt>(Result),
5341 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5342 IsSigned);
5343}
5344
5345static bool HasSubOverflow(ConstantInt *Result,
5346 ConstantInt *In1, ConstantInt *In2,
5347 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005348 if (IsSigned)
5349 if (In2->getValue().isNegative())
5350 return Result->getValue().slt(In1->getValue());
5351 else
5352 return Result->getValue().sgt(In1->getValue());
5353 else
5354 return Result->getValue().ugt(In1->getValue());
5355}
5356
Dan Gohman6de29f82009-06-15 22:12:54 +00005357/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5358/// overflowed for this type.
5359static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005360 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005361 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005362 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005363
5364 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5365 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005366 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005367 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5368 ExtractElement(In1, Idx, Context),
5369 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005370 IsSigned))
5371 return true;
5372 }
5373 return false;
5374 }
5375
5376 return HasSubOverflow(cast<ConstantInt>(Result),
5377 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5378 IsSigned);
5379}
5380
Chris Lattner574da9b2005-01-13 20:14:25 +00005381/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5382/// code necessary to compute the offset from the base pointer (without adding
5383/// in the base pointer). Return the result as a signed integer of intptr size.
5384static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005385 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005386 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005387 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005388 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005389
5390 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005391 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005392 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005393
Gabor Greif177dd3f2008-06-12 21:37:33 +00005394 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5395 ++i, ++GTI) {
5396 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005397 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005398 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5399 if (OpC->isZero()) continue;
5400
5401 // Handle a struct index, which adds its field offset to the pointer.
5402 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5403 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5404
Chris Lattner74381062009-08-30 07:44:24 +00005405 Result = IC.Builder->CreateAdd(Result,
5406 ConstantInt::get(IntPtrTy, Size),
5407 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005409 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005410
Owen Andersoneed707b2009-07-24 23:12:02 +00005411 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005412 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005413 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5414 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005415 // Emit an add instruction.
5416 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005417 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005418 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005420 if (Op->getType() != IntPtrTy)
5421 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005422 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005423 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005424 // We'll let instcombine(mul) convert this to a shl if possible.
5425 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005426 }
5427
5428 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005429 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005430 }
5431 return Result;
5432}
5433
Chris Lattner10c0d912008-04-22 02:53:33 +00005434
Dan Gohman8f080f02009-07-17 22:16:21 +00005435/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5436/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5437/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5438/// be complex, and scales are involved. The above expression would also be
5439/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5440/// This later form is less amenable to optimization though, and we are allowed
5441/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005442///
5443/// If we can't emit an optimized form for this expression, this returns null.
5444///
5445static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5446 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005447 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005448 gep_type_iterator GTI = gep_type_begin(GEP);
5449
5450 // Check to see if this gep only has a single variable index. If so, and if
5451 // any constant indices are a multiple of its scale, then we can compute this
5452 // in terms of the scale of the variable index. For example, if the GEP
5453 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5454 // because the expression will cross zero at the same point.
5455 unsigned i, e = GEP->getNumOperands();
5456 int64_t Offset = 0;
5457 for (i = 1; i != e; ++i, ++GTI) {
5458 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5459 // Compute the aggregate offset of constant indices.
5460 if (CI->isZero()) continue;
5461
5462 // Handle a struct index, which adds its field offset to the pointer.
5463 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5464 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5465 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005466 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005467 Offset += Size*CI->getSExtValue();
5468 }
5469 } else {
5470 // Found our variable index.
5471 break;
5472 }
5473 }
5474
5475 // If there are no variable indices, we must have a constant offset, just
5476 // evaluate it the general way.
5477 if (i == e) return 0;
5478
5479 Value *VariableIdx = GEP->getOperand(i);
5480 // Determine the scale factor of the variable element. For example, this is
5481 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005482 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005483
5484 // Verify that there are no other variable indices. If so, emit the hard way.
5485 for (++i, ++GTI; i != e; ++i, ++GTI) {
5486 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5487 if (!CI) return 0;
5488
5489 // Compute the aggregate offset of constant indices.
5490 if (CI->isZero()) continue;
5491
5492 // Handle a struct index, which adds its field offset to the pointer.
5493 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5494 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5495 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005496 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005497 Offset += Size*CI->getSExtValue();
5498 }
5499 }
5500
5501 // Okay, we know we have a single variable index, which must be a
5502 // pointer/array/vector index. If there is no offset, life is simple, return
5503 // the index.
5504 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5505 if (Offset == 0) {
5506 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5507 // we don't need to bother extending: the extension won't affect where the
5508 // computation crosses zero.
5509 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005510 VariableIdx = new TruncInst(VariableIdx,
5511 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005512 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005513 return VariableIdx;
5514 }
5515
5516 // Otherwise, there is an index. The computation we will do will be modulo
5517 // the pointer size, so get it.
5518 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5519
5520 Offset &= PtrSizeMask;
5521 VariableScale &= PtrSizeMask;
5522
5523 // To do this transformation, any constant index must be a multiple of the
5524 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5525 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5526 // multiple of the variable scale.
5527 int64_t NewOffs = Offset / (int64_t)VariableScale;
5528 if (Offset != NewOffs*(int64_t)VariableScale)
5529 return 0;
5530
5531 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005532 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005533 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005534 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005535 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005536 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005537 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005538 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005539}
5540
5541
Reid Spencere4d87aa2006-12-23 06:05:41 +00005542/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005543/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005544Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005545 ICmpInst::Predicate Cond,
5546 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005547 // Look through bitcasts.
5548 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5549 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005550
Chris Lattner574da9b2005-01-13 20:14:25 +00005551 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005552 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005553 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005554 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005555 // know pointers can't overflow since the gep is inbounds. See if we can
5556 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005557 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5558
5559 // If not, synthesize the offset the hard way.
5560 if (Offset == 0)
5561 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005562 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005563 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005564 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005565 // If the base pointers are different, but the indices are the same, just
5566 // compare the base pointer.
5567 if (PtrBase != GEPRHS->getOperand(0)) {
5568 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005569 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005570 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005571 if (IndicesTheSame)
5572 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5573 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5574 IndicesTheSame = false;
5575 break;
5576 }
5577
5578 // If all indices are the same, just compare the base pointers.
5579 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005580 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005581 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005582
5583 // Otherwise, the base pointers are different and the indices are
5584 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005585 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005586 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005587
Chris Lattnere9d782b2005-01-13 22:25:21 +00005588 // If one of the GEPs has all zero indices, recurse.
5589 bool AllZeros = true;
5590 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5592 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5593 AllZeros = false;
5594 break;
5595 }
5596 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005597 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5598 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005599
5600 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005601 AllZeros = true;
5602 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5603 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5604 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5605 AllZeros = false;
5606 break;
5607 }
5608 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005609 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005610
Chris Lattner4401c9c2005-01-14 00:20:05 +00005611 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5612 // If the GEPs only differ by one index, compare it.
5613 unsigned NumDifferences = 0; // Keep track of # differences.
5614 unsigned DiffOperand = 0; // The operand that differs.
5615 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5616 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005617 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5618 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005619 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005620 NumDifferences = 2;
5621 break;
5622 } else {
5623 if (NumDifferences++) break;
5624 DiffOperand = i;
5625 }
5626 }
5627
5628 if (NumDifferences == 0) // SAME GEP?
5629 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005630 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005631 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005632
Chris Lattner4401c9c2005-01-14 00:20:05 +00005633 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005634 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5635 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005637 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005638 }
5639 }
5640
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005642 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005643 if (TD &&
5644 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005645 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5646 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5647 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5648 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005649 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005650 }
5651 }
5652 return 0;
5653}
5654
Chris Lattnera5406232008-05-19 20:18:56 +00005655/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5656///
5657Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5658 Instruction *LHSI,
5659 Constant *RHSC) {
5660 if (!isa<ConstantFP>(RHSC)) return 0;
5661 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5662
5663 // Get the width of the mantissa. We don't want to hack on conversions that
5664 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005665 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005666 if (MantissaWidth == -1) return 0; // Unknown.
5667
5668 // Check to see that the input is converted from an integer type that is small
5669 // enough that preserves all bits. TODO: check here for "known" sign bits.
5670 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005671 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005672
5673 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005674 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5675 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005676 ++InputSize;
5677
5678 // If the conversion would lose info, don't hack on this.
5679 if ((int)InputSize > MantissaWidth)
5680 return 0;
5681
5682 // Otherwise, we can potentially simplify the comparison. We know that it
5683 // will always come through as an integer value and we know the constant is
5684 // not a NAN (it would have been previously simplified).
5685 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5686
5687 ICmpInst::Predicate Pred;
5688 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005689 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005690 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005691 case FCmpInst::FCMP_OEQ:
5692 Pred = ICmpInst::ICMP_EQ;
5693 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005694 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005695 case FCmpInst::FCMP_OGT:
5696 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5697 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005698 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005699 case FCmpInst::FCMP_OGE:
5700 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5701 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005702 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005703 case FCmpInst::FCMP_OLT:
5704 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5705 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005706 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005707 case FCmpInst::FCMP_OLE:
5708 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5709 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005710 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005711 case FCmpInst::FCMP_ONE:
5712 Pred = ICmpInst::ICMP_NE;
5713 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005714 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005715 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005717 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005718 }
5719
5720 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5721
5722 // Now we know that the APFloat is a normal number, zero or inf.
5723
Chris Lattner85162782008-05-20 03:50:52 +00005724 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005725 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005726 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005727
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005728 if (!LHSUnsigned) {
5729 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5730 // and large values.
5731 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5732 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5733 APFloat::rmNearestTiesToEven);
5734 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5735 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5736 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005737 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5738 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005739 }
5740 } else {
5741 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5742 // +INF and large values.
5743 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5744 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5745 APFloat::rmNearestTiesToEven);
5746 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5747 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5748 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005749 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5750 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005751 }
Chris Lattnera5406232008-05-19 20:18:56 +00005752 }
5753
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005754 if (!LHSUnsigned) {
5755 // See if the RHS value is < SignedMin.
5756 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5757 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5758 APFloat::rmNearestTiesToEven);
5759 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5760 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5761 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005762 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5763 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005764 }
Chris Lattnera5406232008-05-19 20:18:56 +00005765 }
5766
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005767 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5768 // [0, UMAX], but it may still be fractional. See if it is fractional by
5769 // casting the FP value to the integer value and back, checking for equality.
5770 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005771 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005772 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5773 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005774 if (!RHS.isZero()) {
5775 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005776 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5777 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005778 if (!Equal) {
5779 // If we had a comparison against a fractional value, we have to adjust
5780 // the compare predicate and sometimes the value. RHSC is rounded towards
5781 // zero at this point.
5782 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005783 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005784 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005785 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005786 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005787 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005788 case ICmpInst::ICMP_ULE:
5789 // (float)int <= 4.4 --> int <= 4
5790 // (float)int <= -4.4 --> false
5791 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005792 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005793 break;
5794 case ICmpInst::ICMP_SLE:
5795 // (float)int <= 4.4 --> int <= 4
5796 // (float)int <= -4.4 --> int < -4
5797 if (RHS.isNegative())
5798 Pred = ICmpInst::ICMP_SLT;
5799 break;
5800 case ICmpInst::ICMP_ULT:
5801 // (float)int < -4.4 --> false
5802 // (float)int < 4.4 --> int <= 4
5803 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005804 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005805 Pred = ICmpInst::ICMP_ULE;
5806 break;
5807 case ICmpInst::ICMP_SLT:
5808 // (float)int < -4.4 --> int < -4
5809 // (float)int < 4.4 --> int <= 4
5810 if (!RHS.isNegative())
5811 Pred = ICmpInst::ICMP_SLE;
5812 break;
5813 case ICmpInst::ICMP_UGT:
5814 // (float)int > 4.4 --> int > 4
5815 // (float)int > -4.4 --> true
5816 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005817 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005818 break;
5819 case ICmpInst::ICMP_SGT:
5820 // (float)int > 4.4 --> int > 4
5821 // (float)int > -4.4 --> int >= -4
5822 if (RHS.isNegative())
5823 Pred = ICmpInst::ICMP_SGE;
5824 break;
5825 case ICmpInst::ICMP_UGE:
5826 // (float)int >= -4.4 --> true
5827 // (float)int >= 4.4 --> int > 4
5828 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005829 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005830 Pred = ICmpInst::ICMP_UGT;
5831 break;
5832 case ICmpInst::ICMP_SGE:
5833 // (float)int >= -4.4 --> int >= -4
5834 // (float)int >= 4.4 --> int > 4
5835 if (!RHS.isNegative())
5836 Pred = ICmpInst::ICMP_SGT;
5837 break;
5838 }
Chris Lattnera5406232008-05-19 20:18:56 +00005839 }
5840 }
5841
5842 // Lower this FP comparison into an appropriate integer version of the
5843 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005844 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005845}
5846
Reid Spencere4d87aa2006-12-23 06:05:41 +00005847Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5848 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005849 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005850
Chris Lattner58e97462007-01-14 19:42:17 +00005851 // Fold trivial predicates.
5852 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005853 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005854 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005855 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005856
5857 // Simplify 'fcmp pred X, X'
5858 if (Op0 == Op1) {
5859 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005860 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005861 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5862 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5863 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005864 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005865 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5866 case FCmpInst::FCMP_OLT: // True if ordered and less than
5867 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005868 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005869
5870 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5871 case FCmpInst::FCMP_ULT: // True if unordered or less than
5872 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5873 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5874 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5875 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005876 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005877 return &I;
5878
5879 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5880 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5881 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5882 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5883 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5884 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005885 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005886 return &I;
5887 }
5888 }
5889
Reid Spencere4d87aa2006-12-23 06:05:41 +00005890 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005891 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005892
Reid Spencere4d87aa2006-12-23 06:05:41 +00005893 // Handle fcmp with constant RHS
5894 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005895 // If the constant is a nan, see if we can fold the comparison based on it.
5896 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5897 if (CFP->getValueAPF().isNaN()) {
5898 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005899 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005900 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5901 "Comparison must be either ordered or unordered!");
5902 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005903 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005904 }
5905 }
5906
Reid Spencere4d87aa2006-12-23 06:05:41 +00005907 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5908 switch (LHSI->getOpcode()) {
5909 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005910 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5911 // block. If in the same block, we're encouraging jump threading. If
5912 // not, we are just pessimizing the code by making an i1 phi.
5913 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005914 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005915 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005916 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005917 case Instruction::SIToFP:
5918 case Instruction::UIToFP:
5919 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5920 return NV;
5921 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922 case Instruction::Select:
5923 // If either operand of the select is a constant, we can fold the
5924 // comparison into the select arms, which will cause one to be
5925 // constant folded and the select turned into a bitwise or.
5926 Value *Op1 = 0, *Op2 = 0;
5927 if (LHSI->hasOneUse()) {
5928 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5929 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005930 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005932 Op2 = Builder->CreateFCmp(I.getPredicate(),
5933 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5935 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005936 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005938 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5939 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 }
5941 }
5942
5943 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005944 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005945 break;
5946 }
5947 }
5948
5949 return Changed ? &I : 0;
5950}
5951
5952Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5953 bool Changed = SimplifyCompare(I);
5954 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5955 const Type *Ty = Op0->getType();
5956
5957 // icmp X, X
5958 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005959 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005960 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961
5962 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005963 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005964
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005966 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00005967 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005968 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00005969 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005970 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005971 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005972 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005973
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005975 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005977 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005978 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005979 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005980 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005981 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005982 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005983 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005984
Reid Spencere4d87aa2006-12-23 06:05:41 +00005985 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005986 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005987 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005988 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005989 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005990 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005991 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005992 case ICmpInst::ICMP_SGT:
5993 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005994 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005995 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005996 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005997 return BinaryOperator::CreateAnd(Not, Op0);
5998 }
5999 case ICmpInst::ICMP_UGE:
6000 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6001 // FALL THROUGH
6002 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006003 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006004 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006005 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006006 case ICmpInst::ICMP_SGE:
6007 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6008 // FALL THROUGH
6009 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006010 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 return BinaryOperator::CreateOr(Not, Op0);
6012 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006013 }
Chris Lattner8b170942002-08-09 23:47:40 +00006014 }
6015
Dan Gohman1c8491e2009-04-25 17:12:48 +00006016 unsigned BitWidth = 0;
6017 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006018 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6019 else if (Ty->isIntOrIntVector())
6020 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006021
6022 bool isSignBit = false;
6023
Dan Gohman81b28ce2008-09-16 18:46:06 +00006024 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006025 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006026 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006027
Chris Lattnerb6566012008-01-05 01:18:20 +00006028 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6029 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006030 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006031 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006032 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006033 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006034
Dan Gohman81b28ce2008-09-16 18:46:06 +00006035 // If we have an icmp le or icmp ge instruction, turn it into the
6036 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6037 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006038 switch (I.getPredicate()) {
6039 default: break;
6040 case ICmpInst::ICMP_ULE:
6041 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006042 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006043 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006044 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006045 case ICmpInst::ICMP_SLE:
6046 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006047 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006048 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006049 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006050 case ICmpInst::ICMP_UGE:
6051 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006052 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006053 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006054 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006055 case ICmpInst::ICMP_SGE:
6056 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006057 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006058 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006059 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006060 }
6061
Chris Lattner183661e2008-07-11 05:40:05 +00006062 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006063 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006064 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006065 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6066 }
6067
6068 // See if we can fold the comparison based on range information we can get
6069 // by checking whether bits are known to be zero or one in the input.
6070 if (BitWidth != 0) {
6071 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6072 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6073
6074 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006075 isSignBit ? APInt::getSignBit(BitWidth)
6076 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006077 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006078 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006079 if (SimplifyDemandedBits(I.getOperandUse(1),
6080 APInt::getAllOnesValue(BitWidth),
6081 Op1KnownZero, Op1KnownOne, 0))
6082 return &I;
6083
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006084 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006085 // in. Compute the Min, Max and RHS values based on the known bits. For the
6086 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006087 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6088 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6089 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6090 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6091 Op0Min, Op0Max);
6092 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6093 Op1Min, Op1Max);
6094 } else {
6095 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6096 Op0Min, Op0Max);
6097 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6098 Op1Min, Op1Max);
6099 }
6100
Chris Lattner183661e2008-07-11 05:40:05 +00006101 // If Min and Max are known to be the same, then SimplifyDemandedBits
6102 // figured out that the LHS is a constant. Just constant fold this now so
6103 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006105 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006106 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006108 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006109 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110
Chris Lattner183661e2008-07-11 05:40:05 +00006111 // Based on the range information we know about the LHS, see if we can
6112 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006114 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006115 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006117 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006118 break;
6119 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006121 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006122 break;
6123 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006124 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006125 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006127 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006129 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6131 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006132 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006133 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006134
6135 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6136 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006137 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006138 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 }
Chris Lattner84dff672008-07-11 05:08:55 +00006140 break;
6141 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006143 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006144 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006145 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146
6147 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006148 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6150 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006151 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006152 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153
6154 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6155 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006156 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006157 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158 }
Chris Lattner84dff672008-07-11 05:08:55 +00006159 break;
6160 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006162 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006164 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006166 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6168 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006169 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006170 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171 }
Chris Lattner84dff672008-07-11 05:08:55 +00006172 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173 case ICmpInst::ICMP_SGT:
6174 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006175 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006177 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178
6179 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006180 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6182 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006183 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006184 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185 }
6186 break;
6187 case ICmpInst::ICMP_SGE:
6188 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6189 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006190 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006192 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 break;
6194 case ICmpInst::ICMP_SLE:
6195 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6196 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006197 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 break;
6201 case ICmpInst::ICMP_UGE:
6202 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6203 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006204 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006206 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207 break;
6208 case ICmpInst::ICMP_ULE:
6209 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6210 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006211 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006213 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006214 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006215 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216
6217 // Turn a signed comparison into an unsigned one if both operands
6218 // are known to have the same sign.
6219 if (I.isSignedPredicate() &&
6220 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6221 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006222 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006223 }
6224
6225 // Test if the ICmpInst instruction is used exclusively by a select as
6226 // part of a minimum or maximum operation. If so, refrain from doing
6227 // any other folding. This helps out other analyses which understand
6228 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6229 // and CodeGen. And in this case, at least one of the comparison
6230 // operands has at least one user besides the compare (the select),
6231 // which would often largely negate the benefit of folding anyway.
6232 if (I.hasOneUse())
6233 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6234 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6235 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6236 return 0;
6237
6238 // See if we are doing a comparison between a constant and an instruction that
6239 // can be folded into the comparison.
6240 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006241 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006242 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006243 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006244 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006245 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6246 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006247 }
6248
Chris Lattner01deb9d2007-04-03 17:43:25 +00006249 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006250 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6251 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006253 case Instruction::GetElementPtr:
6254 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006255 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006256 bool isAllZeros = true;
6257 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6258 if (!isa<Constant>(LHSI->getOperand(i)) ||
6259 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6260 isAllZeros = false;
6261 break;
6262 }
6263 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006264 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006265 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006266 }
6267 break;
6268
Chris Lattner6970b662005-04-23 15:31:55 +00006269 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006270 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006271 // block. If in the same block, we're encouraging jump threading. If
6272 // not, we are just pessimizing the code by making an i1 phi.
6273 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006274 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006275 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006276 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006277 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006278 // If either operand of the select is a constant, we can fold the
6279 // comparison into the select arms, which will cause one to be
6280 // constant folded and the select turned into a bitwise or.
6281 Value *Op1 = 0, *Op2 = 0;
6282 if (LHSI->hasOneUse()) {
6283 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6284 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006285 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006286 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006287 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6288 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006289 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6290 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006291 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006293 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6294 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006295 }
6296 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006297
Chris Lattner6970b662005-04-23 15:31:55 +00006298 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006299 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006300 break;
6301 }
Chris Lattner4802d902007-04-06 18:57:34 +00006302 case Instruction::Malloc:
6303 // If we have (malloc != null), and if the malloc has a single use, we
6304 // can assume it is successful and remove the malloc.
6305 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006306 Worklist.Add(LHSI);
Victor Hernandez83d63912009-09-18 22:35:49 +00006307 return ReplaceInstUsesWith(I,
6308 ConstantInt::get(Type::getInt1Ty(*Context),
6309 !I.isTrueWhenEqual()));
6310 }
6311 break;
6312 case Instruction::Call:
6313 // If we have (malloc != null), and if the malloc has a single use, we
6314 // can assume it is successful and remove the malloc.
6315 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6316 isa<ConstantPointerNull>(RHSC)) {
6317 Worklist.Add(LHSI);
6318 return ReplaceInstUsesWith(I,
6319 ConstantInt::get(Type::getInt1Ty(*Context),
6320 !I.isTrueWhenEqual()));
6321 }
6322 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006323 }
Chris Lattner6970b662005-04-23 15:31:55 +00006324 }
6325
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006327 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006329 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006330 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6332 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006333 return NI;
6334
Reid Spencere4d87aa2006-12-23 06:05:41 +00006335 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006336 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6337 // now.
6338 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6339 if (isa<PointerType>(Op0->getType()) &&
6340 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006341 // We keep moving the cast from the left operand over to the right
6342 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006343 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006344
Chris Lattner57d86372007-01-06 01:45:59 +00006345 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6346 // so eliminate it as well.
6347 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6348 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006349
Chris Lattnerde90b762003-11-03 04:25:02 +00006350 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006351 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006352 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006353 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006354 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006355 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006356 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006357 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006358 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006359 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006360 }
Chris Lattner57d86372007-01-06 01:45:59 +00006361 }
6362
6363 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006364 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006365 // This comes up when you have code like
6366 // int X = A < B;
6367 // if (X) ...
6368 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006369 // with a constant or another cast from the same type.
6370 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006371 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006372 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006373 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006374
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006375 // See if it's the same type of instruction on the left and right.
6376 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6377 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006378 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006379 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006380 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006381 default: break;
6382 case Instruction::Add:
6383 case Instruction::Sub:
6384 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006385 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006386 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006387 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006388 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6389 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6390 if (CI->getValue().isSignBit()) {
6391 ICmpInst::Predicate Pred = I.isSignedPredicate()
6392 ? I.getUnsignedPredicate()
6393 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006394 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006395 Op1I->getOperand(0));
6396 }
6397
6398 if (CI->getValue().isMaxSignedValue()) {
6399 ICmpInst::Predicate Pred = I.isSignedPredicate()
6400 ? I.getUnsignedPredicate()
6401 : I.getSignedPredicate();
6402 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006403 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006404 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006405 }
6406 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006407 break;
6408 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006409 if (!I.isEquality())
6410 break;
6411
Nick Lewycky5d52c452008-08-21 05:56:10 +00006412 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6413 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6414 // Mask = -1 >> count-trailing-zeros(Cst).
6415 if (!CI->isZero() && !CI->isOne()) {
6416 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006417 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006418 APInt::getLowBitsSet(AP.getBitWidth(),
6419 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006420 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006421 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6422 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006423 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006424 }
6425 }
6426 break;
6427 }
6428 }
6429 }
6430 }
6431
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006432 // ~x < ~y --> y < x
6433 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006434 if (match(Op0, m_Not(m_Value(A))) &&
6435 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006436 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006437 }
6438
Chris Lattner65b72ba2006-09-18 04:22:48 +00006439 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006440 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006441
6442 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006443 if (match(Op0, m_Neg(m_Value(A))) &&
6444 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006445 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006446
Dan Gohman4ae51262009-08-12 16:23:25 +00006447 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006448 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6449 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006450 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006451 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006452 }
6453
Dan Gohman4ae51262009-08-12 16:23:25 +00006454 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006455 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006456 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006457 if (match(B, m_ConstantInt(C1)) &&
6458 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006459 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006460 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006461 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6462 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006463 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006464
6465 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006466 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6467 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6468 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6469 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006470 }
6471 }
6472
Dan Gohman4ae51262009-08-12 16:23:25 +00006473 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006474 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006475 // A == (A^B) -> B == 0
6476 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006477 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006478 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006479 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006480
6481 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006482 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006483 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006484 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006485
6486 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006487 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006488 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006489 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006490
Chris Lattner9c2328e2006-11-14 06:06:06 +00006491 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6492 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006493 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6494 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006495 Value *X = 0, *Y = 0, *Z = 0;
6496
6497 if (A == C) {
6498 X = B; Y = D; Z = A;
6499 } else if (A == D) {
6500 X = B; Y = C; Z = A;
6501 } else if (B == C) {
6502 X = A; Y = D; Z = B;
6503 } else if (B == D) {
6504 X = A; Y = C; Z = B;
6505 }
6506
6507 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006508 Op1 = Builder->CreateXor(X, Y, "tmp");
6509 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006510 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006511 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006512 return &I;
6513 }
6514 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006515 }
Chris Lattner7e708292002-06-25 16:13:24 +00006516 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006517}
6518
Chris Lattner562ef782007-06-20 23:46:26 +00006519
6520/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6521/// and CmpRHS are both known to be integer constants.
6522Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6523 ConstantInt *DivRHS) {
6524 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6525 const APInt &CmpRHSV = CmpRHS->getValue();
6526
6527 // FIXME: If the operand types don't match the type of the divide
6528 // then don't attempt this transform. The code below doesn't have the
6529 // logic to deal with a signed divide and an unsigned compare (and
6530 // vice versa). This is because (x /s C1) <s C2 produces different
6531 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6532 // (x /u C1) <u C2. Simply casting the operands and result won't
6533 // work. :( The if statement below tests that condition and bails
6534 // if it finds it.
6535 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6536 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6537 return 0;
6538 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006539 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006540 if (DivIsSigned && DivRHS->isAllOnesValue())
6541 return 0; // The overflow computation also screws up here
6542 if (DivRHS->isOne())
6543 return 0; // Not worth bothering, and eliminates some funny cases
6544 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006545
6546 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6547 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6548 // C2 (CI). By solving for X we can turn this into a range check
6549 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006550 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006551
6552 // Determine if the product overflows by seeing if the product is
6553 // not equal to the divide. Make sure we do the same kind of divide
6554 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006555 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6556 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006557
6558 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006559 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006560
Chris Lattner1dbfd482007-06-21 18:11:19 +00006561 // Figure out the interval that is being checked. For example, a comparison
6562 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6563 // Compute this interval based on the constants involved and the signedness of
6564 // the compare/divide. This computes a half-open interval, keeping track of
6565 // whether either value in the interval overflows. After analysis each
6566 // overflow variable is set to 0 if it's corresponding bound variable is valid
6567 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6568 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006569 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006570
Chris Lattner562ef782007-06-20 23:46:26 +00006571 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006573 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 HiOverflow = LoOverflow = ProdOV;
6575 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006576 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006577 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006578 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006579 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006580 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006581 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006582 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006583 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6584 HiOverflow = LoOverflow = ProdOV;
6585 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006586 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006587 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006588 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006589 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006590 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6591 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006592 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006593 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006594 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006595 true) ? -1 : 0;
6596 }
Chris Lattner562ef782007-06-20 23:46:26 +00006597 }
Dan Gohman76491272008-02-13 22:09:18 +00006598 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006599 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006601 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006602 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6604 HiOverflow = 1; // [INTMIN+1, overflow)
6605 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6606 }
Dan Gohman76491272008-02-13 22:09:18 +00006607 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006608 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006609 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006610 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006611 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006612 LoOverflow = AddWithOverflow(LoBound, HiBound,
6613 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006614 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006615 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6616 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006617 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006618 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006619 }
6620
Chris Lattner1dbfd482007-06-21 18:11:19 +00006621 // Dividing by a negative swaps the condition. LT <-> GT
6622 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006623 }
6624
6625 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006626 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006627 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006628 case ICmpInst::ICMP_EQ:
6629 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006630 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006631 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006632 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006633 ICmpInst::ICMP_UGE, X, LoBound);
6634 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006635 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006636 ICmpInst::ICMP_ULT, X, HiBound);
6637 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006638 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006639 case ICmpInst::ICMP_NE:
6640 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006641 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006642 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006643 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006644 ICmpInst::ICMP_ULT, X, LoBound);
6645 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006646 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006647 ICmpInst::ICMP_UGE, X, HiBound);
6648 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006649 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006650 case ICmpInst::ICMP_ULT:
6651 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006652 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006653 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006654 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006655 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006656 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006657 case ICmpInst::ICMP_UGT:
6658 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006659 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006660 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006661 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006662 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006663 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006664 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006665 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006666 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006667 }
6668}
6669
6670
Chris Lattner01deb9d2007-04-03 17:43:25 +00006671/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6672///
6673Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6674 Instruction *LHSI,
6675 ConstantInt *RHS) {
6676 const APInt &RHSV = RHS->getValue();
6677
6678 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006679 case Instruction::Trunc:
6680 if (ICI.isEquality() && LHSI->hasOneUse()) {
6681 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6682 // of the high bits truncated out of x are known.
6683 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6684 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6685 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6686 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6687 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6688
6689 // If all the high bits are known, we can do this xform.
6690 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6691 // Pull in the high bits from known-ones set.
6692 APInt NewRHS(RHS->getValue());
6693 NewRHS.zext(SrcBits);
6694 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006695 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006696 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006697 }
6698 }
6699 break;
6700
Duncan Sands0091bf22007-04-04 06:42:45 +00006701 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006702 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6703 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6704 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006705 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6706 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006707 Value *CompareVal = LHSI->getOperand(0);
6708
6709 // If the sign bit of the XorCST is not set, there is no change to
6710 // the operation, just stop using the Xor.
6711 if (!XorCST->getValue().isNegative()) {
6712 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006713 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006714 return &ICI;
6715 }
6716
6717 // Was the old condition true if the operand is positive?
6718 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6719
6720 // If so, the new one isn't.
6721 isTrueIfPositive ^= true;
6722
6723 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006724 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006725 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006726 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006727 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006728 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006729 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006730
6731 if (LHSI->hasOneUse()) {
6732 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6733 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6734 const APInt &SignBit = XorCST->getValue();
6735 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6736 ? ICI.getUnsignedPredicate()
6737 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006738 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006739 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006740 }
6741
6742 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006743 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006744 const APInt &NotSignBit = XorCST->getValue();
6745 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6746 ? ICI.getUnsignedPredicate()
6747 : ICI.getSignedPredicate();
6748 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006749 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006750 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006751 }
6752 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006753 }
6754 break;
6755 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6756 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6757 LHSI->getOperand(0)->hasOneUse()) {
6758 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6759
6760 // If the LHS is an AND of a truncating cast, we can widen the
6761 // and/compare to be the input width without changing the value
6762 // produced, eliminating a cast.
6763 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6764 // We can do this transformation if either the AND constant does not
6765 // have its sign bit set or if it is an equality comparison.
6766 // Extending a relational comparison when we're checking the sign
6767 // bit would not work.
6768 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006769 (ICI.isEquality() ||
6770 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006771 uint32_t BitWidth =
6772 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6773 APInt NewCST = AndCST->getValue();
6774 NewCST.zext(BitWidth);
6775 APInt NewCI = RHSV;
6776 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006777 Value *NewAnd =
6778 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006779 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006780 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006781 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 }
6783 }
6784
6785 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6786 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6787 // happens a LOT in code produced by the C front-end, for bitfield
6788 // access.
6789 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6790 if (Shift && !Shift->isShift())
6791 Shift = 0;
6792
6793 ConstantInt *ShAmt;
6794 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6795 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6796 const Type *AndTy = AndCST->getType(); // Type of the and.
6797
6798 // We can fold this as long as we can't shift unknown bits
6799 // into the mask. This can only happen with signed shift
6800 // rights, as they sign-extend.
6801 if (ShAmt) {
6802 bool CanFold = Shift->isLogicalShift();
6803 if (!CanFold) {
6804 // To test for the bad case of the signed shr, see if any
6805 // of the bits shifted in could be tested after the mask.
6806 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6807 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6808
6809 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6810 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6811 AndCST->getValue()) == 0)
6812 CanFold = true;
6813 }
6814
6815 if (CanFold) {
6816 Constant *NewCst;
6817 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006818 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006819 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006820 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006821
6822 // Check to see if we are shifting out any of the bits being
6823 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006824 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006825 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006826 // If we shifted bits out, the fold is not going to work out.
6827 // As a special case, check to see if this means that the
6828 // result is always true or false now.
6829 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006830 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006831 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006832 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006833 } else {
6834 ICI.setOperand(1, NewCst);
6835 Constant *NewAndCST;
6836 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006837 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006838 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006839 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006840 LHSI->setOperand(1, NewAndCST);
6841 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006842 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843 return &ICI;
6844 }
6845 }
6846 }
6847
6848 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6849 // preferable because it allows the C<<Y expression to be hoisted out
6850 // of a loop if Y is invariant and X is not.
6851 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006852 ICI.isEquality() && !Shift->isArithmeticShift() &&
6853 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006854 // Compute C << Y.
6855 Value *NS;
6856 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006857 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 } else {
6859 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006860 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006861 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862
6863 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006864 Value *NewAnd =
6865 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866
6867 ICI.setOperand(0, NewAnd);
6868 return &ICI;
6869 }
6870 }
6871 break;
6872
Chris Lattnera0141b92007-07-15 20:42:37 +00006873 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6874 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6875 if (!ShAmt) break;
6876
6877 uint32_t TypeBits = RHSV.getBitWidth();
6878
6879 // Check that the shift amount is in range. If not, don't perform
6880 // undefined shifts. When the shift is visited it will be
6881 // simplified.
6882 if (ShAmt->uge(TypeBits))
6883 break;
6884
6885 if (ICI.isEquality()) {
6886 // If we are comparing against bits always shifted out, the
6887 // comparison cannot succeed.
6888 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006889 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006890 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006891 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6892 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006893 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006894 return ReplaceInstUsesWith(ICI, Cst);
6895 }
6896
6897 if (LHSI->hasOneUse()) {
6898 // Otherwise strength reduce the shift into an and.
6899 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6900 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006901 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006902 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006903
Chris Lattner74381062009-08-30 07:44:24 +00006904 Value *And =
6905 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006906 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006907 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006908 }
6909 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006910
6911 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6912 bool TrueIfSigned = false;
6913 if (LHSI->hasOneUse() &&
6914 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6915 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006916 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006917 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006918 Value *And =
6919 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006920 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006921 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006922 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006923 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006924 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006925
6926 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006927 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006928 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006929 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006930 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006931
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006932 // Check that the shift amount is in range. If not, don't perform
6933 // undefined shifts. When the shift is visited it will be
6934 // simplified.
6935 uint32_t TypeBits = RHSV.getBitWidth();
6936 if (ShAmt->uge(TypeBits))
6937 break;
6938
6939 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006940
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006941 // If we are comparing against bits always shifted out, the
6942 // comparison cannot succeed.
6943 APInt Comp = RHSV << ShAmtVal;
6944 if (LHSI->getOpcode() == Instruction::LShr)
6945 Comp = Comp.lshr(ShAmtVal);
6946 else
6947 Comp = Comp.ashr(ShAmtVal);
6948
6949 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6950 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006951 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006952 return ReplaceInstUsesWith(ICI, Cst);
6953 }
6954
6955 // Otherwise, check to see if the bits shifted out are known to be zero.
6956 // If so, we can compare against the unshifted value:
6957 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006958 if (LHSI->hasOneUse() &&
6959 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006960 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006961 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006962 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006963 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006964
Evan Chengf30752c2008-04-23 00:38:06 +00006965 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006966 // Otherwise strength reduce the shift into an and.
6967 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006968 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006969
Chris Lattner74381062009-08-30 07:44:24 +00006970 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6971 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006972 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006973 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006974 }
6975 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006976 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977
6978 case Instruction::SDiv:
6979 case Instruction::UDiv:
6980 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6981 // Fold this div into the comparison, producing a range check.
6982 // Determine, based on the divide type, what the range is being
6983 // checked. If there is an overflow on the low or high side, remember
6984 // it, otherwise compute the range [low, hi) bounding the new value.
6985 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006986 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6987 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6988 DivRHS))
6989 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006990 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006991
6992 case Instruction::Add:
6993 // Fold: icmp pred (add, X, C1), C2
6994
6995 if (!ICI.isEquality()) {
6996 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6997 if (!LHSC) break;
6998 const APInt &LHSV = LHSC->getValue();
6999
7000 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7001 .subtract(LHSV);
7002
7003 if (ICI.isSignedPredicate()) {
7004 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007005 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007006 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007007 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007008 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007009 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007010 }
7011 } else {
7012 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007013 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007014 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007015 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007016 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007017 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007018 }
7019 }
7020 }
7021 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007022 }
7023
7024 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7025 if (ICI.isEquality()) {
7026 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7027
7028 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7029 // the second operand is a constant, simplify a bit.
7030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7031 switch (BO->getOpcode()) {
7032 case Instruction::SRem:
7033 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7034 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7035 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7036 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007037 Value *NewRem =
7038 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7039 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007040 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007041 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007042 }
7043 }
7044 break;
7045 case Instruction::Add:
7046 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7047 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7048 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007049 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007050 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007051 } else if (RHSV == 0) {
7052 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7053 // efficiently invertible, or if the add has just this one use.
7054 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7055
Dan Gohman186a6362009-08-12 16:04:34 +00007056 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007057 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007058 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007059 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007060 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007061 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007062 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007063 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007064 }
7065 }
7066 break;
7067 case Instruction::Xor:
7068 // For the xor case, we can xor two constants together, eliminating
7069 // the explicit xor.
7070 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007071 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007072 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007073
7074 // FALLTHROUGH
7075 case Instruction::Sub:
7076 // Replace (([sub|xor] A, B) != 0) with (A != B)
7077 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007078 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007079 BO->getOperand(1));
7080 break;
7081
7082 case Instruction::Or:
7083 // If bits are being or'd in that are not present in the constant we
7084 // are comparing against, then the comparison could never succeed!
7085 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007086 Constant *NotCI = ConstantExpr::getNot(RHS);
7087 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007088 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007089 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007090 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007091 }
7092 break;
7093
7094 case Instruction::And:
7095 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7096 // If bits are being compared against that are and'd out, then the
7097 // comparison can never succeed!
7098 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007099 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007100 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007101 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007102
7103 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7104 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007105 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007106 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007107 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108
7109 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007110 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007112 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007113 ICmpInst::Predicate pred = isICMP_NE ?
7114 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007115 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007116 }
7117
7118 // ((X & ~7) == 0) --> X < 8
7119 if (RHSV == 0 && isHighOnes(BOC)) {
7120 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007121 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007122 ICmpInst::Predicate pred = isICMP_NE ?
7123 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007124 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007125 }
7126 }
7127 default: break;
7128 }
7129 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7130 // Handle icmp {eq|ne} <intrinsic>, intcst.
7131 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007132 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007133 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007134 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007135 return &ICI;
7136 }
7137 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007138 }
7139 return 0;
7140}
7141
7142/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7143/// We only handle extending casts so far.
7144///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007145Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7146 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007147 Value *LHSCIOp = LHSCI->getOperand(0);
7148 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007149 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007150 Value *RHSCIOp;
7151
Chris Lattner8c756c12007-05-05 22:41:33 +00007152 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7153 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007154 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7155 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007156 cast<IntegerType>(DestTy)->getBitWidth()) {
7157 Value *RHSOp = 0;
7158 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007159 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007160 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7161 RHSOp = RHSC->getOperand(0);
7162 // If the pointer types don't match, insert a bitcast.
7163 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007164 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007165 }
7166
7167 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007168 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007169 }
7170
7171 // The code below only handles extension cast instructions, so far.
7172 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007173 if (LHSCI->getOpcode() != Instruction::ZExt &&
7174 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007175 return 0;
7176
Reid Spencere4d87aa2006-12-23 06:05:41 +00007177 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7178 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007179
Reid Spencere4d87aa2006-12-23 06:05:41 +00007180 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007181 // Not an extension from the same type?
7182 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007183 if (RHSCIOp->getType() != LHSCIOp->getType())
7184 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007185
Nick Lewycky4189a532008-01-28 03:48:02 +00007186 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007187 // and the other is a zext), then we can't handle this.
7188 if (CI->getOpcode() != LHSCI->getOpcode())
7189 return 0;
7190
Nick Lewycky4189a532008-01-28 03:48:02 +00007191 // Deal with equality cases early.
7192 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007193 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007194
7195 // A signed comparison of sign extended values simplifies into a
7196 // signed comparison.
7197 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007198 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007199
7200 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007201 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007202 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007203
Reid Spencere4d87aa2006-12-23 06:05:41 +00007204 // If we aren't dealing with a constant on the RHS, exit early
7205 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7206 if (!CI)
7207 return 0;
7208
7209 // Compute the constant that would happen if we truncated to SrcTy then
7210 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007211 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7212 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007213 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007214
7215 // If the re-extended constant didn't change...
7216 if (Res2 == CI) {
7217 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7218 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007219 // %A = sext i16 %X to i32
7220 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007221 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007222 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007223 // because %A may have negative value.
7224 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007225 // However, we allow this when the compare is EQ/NE, because they are
7226 // signless.
7227 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007228 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007229 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007230 }
7231
7232 // The re-extended constant changed so the constant cannot be represented
7233 // in the shorter type. Consequently, we cannot emit a simple comparison.
7234
7235 // First, handle some easy cases. We know the result cannot be equal at this
7236 // point so handle the ICI.isEquality() cases
7237 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007238 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007239 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007240 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007241
7242 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7243 // should have been folded away previously and not enter in here.
7244 Value *Result;
7245 if (isSignedCmp) {
7246 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007247 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007248 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007249 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007250 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007251 } else {
7252 // We're performing an unsigned comparison.
7253 if (isSignedExt) {
7254 // We're performing an unsigned comp with a sign extended value.
7255 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007256 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007257 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007258 } else {
7259 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007260 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261 }
7262 }
7263
7264 // Finally, return the value computed.
7265 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007266 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007268
7269 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7270 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7271 "ICmp should be folded!");
7272 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007273 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007274 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007275}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007276
Reid Spencer832254e2007-02-02 02:16:23 +00007277Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7278 return commonShiftTransforms(I);
7279}
7280
7281Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7282 return commonShiftTransforms(I);
7283}
7284
7285Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007286 if (Instruction *R = commonShiftTransforms(I))
7287 return R;
7288
7289 Value *Op0 = I.getOperand(0);
7290
7291 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7292 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7293 if (CSI->isAllOnesValue())
7294 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007295
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007296 // See if we can turn a signed shr into an unsigned shr.
7297 if (MaskedValueIsZero(Op0,
7298 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7299 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7300
7301 // Arithmetic shifting an all-sign-bit value is a no-op.
7302 unsigned NumSignBits = ComputeNumSignBits(Op0);
7303 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7304 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007305
Chris Lattner348f6652007-12-06 01:59:46 +00007306 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007307}
7308
7309Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7310 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007312
7313 // shl X, 0 == X and shr X, 0 == X
7314 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007315 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7316 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007317 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007318
Reid Spencere4d87aa2006-12-23 06:05:41 +00007319 if (isa<UndefValue>(Op0)) {
7320 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007321 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007322 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007323 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007324 }
7325 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007326 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7327 return ReplaceInstUsesWith(I, Op0);
7328 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007330 }
7331
Dan Gohman9004c8a2009-05-21 02:28:33 +00007332 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007333 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007334 return &I;
7335
Chris Lattner2eefe512004-04-09 19:05:30 +00007336 // Try to fold constant and into select arguments.
7337 if (isa<Constant>(Op0))
7338 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007339 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007340 return R;
7341
Reid Spencerb83eb642006-10-20 07:07:24 +00007342 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007343 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7344 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007345 return 0;
7346}
7347
Reid Spencerb83eb642006-10-20 07:07:24 +00007348Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007349 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007350 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007351
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007352 // See if we can simplify any instructions used by the instruction whose sole
7353 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007354 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007355
Dan Gohmana119de82009-06-14 23:30:43 +00007356 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7357 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007358 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007359 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007360 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007361 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007362 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007363 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007364 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007365 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007366 }
7367
7368 // ((X*C1) << C2) == (X * (C1 << C2))
7369 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7370 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7371 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007372 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007373 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007374
7375 // Try to fold constant and into select arguments.
7376 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7377 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7378 return R;
7379 if (isa<PHINode>(Op0))
7380 if (Instruction *NV = FoldOpIntoPhi(I))
7381 return NV;
7382
Chris Lattner8999dd32007-12-22 09:07:47 +00007383 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7384 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7385 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7386 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7387 // place. Don't try to do this transformation in this case. Also, we
7388 // require that the input operand is a shift-by-constant so that we have
7389 // confidence that the shifts will get folded together. We could do this
7390 // xform in more cases, but it is unlikely to be profitable.
7391 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7392 isa<ConstantInt>(TrOp->getOperand(1))) {
7393 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007394 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007395 // (shift2 (shift1 & 0x00FF), c2)
7396 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007397
7398 // For logical shifts, the truncation has the effect of making the high
7399 // part of the register be zeros. Emulate this by inserting an AND to
7400 // clear the top bits as needed. This 'and' will usually be zapped by
7401 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007402 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7403 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007404 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7405
7406 // The mask we constructed says what the trunc would do if occurring
7407 // between the shifts. We want to know the effect *after* the second
7408 // shift. We know that it is a logical shift by a constant, so adjust the
7409 // mask as appropriate.
7410 if (I.getOpcode() == Instruction::Shl)
7411 MaskV <<= Op1->getZExtValue();
7412 else {
7413 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7414 MaskV = MaskV.lshr(Op1->getZExtValue());
7415 }
7416
Chris Lattner74381062009-08-30 07:44:24 +00007417 // shift1 & 0x00FF
7418 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7419 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007420
7421 // Return the value truncated to the interesting size.
7422 return new TruncInst(And, I.getType());
7423 }
7424 }
7425
Chris Lattner4d5542c2006-01-06 07:12:35 +00007426 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007427 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7428 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7429 Value *V1, *V2;
7430 ConstantInt *CC;
7431 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007432 default: break;
7433 case Instruction::Add:
7434 case Instruction::And:
7435 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007436 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007437 // These operators commute.
7438 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007439 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007440 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007441 m_Specific(Op1)))) {
7442 Value *YS = // (Y << C)
7443 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7444 // (X + (Y << C))
7445 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7446 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007447 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007448 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007449 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007450 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007451
Chris Lattner150f12a2005-09-18 06:30:59 +00007452 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007453 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007454 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007455 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007456 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007457 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007458 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007459 Value *YS = // (Y << C)
7460 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7461 Op0BO->getName());
7462 // X & (CC << C)
7463 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7464 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007465 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007466 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007467 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007468
Reid Spencera07cb7d2007-02-02 14:41:37 +00007469 // FALL THROUGH.
7470 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007471 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007472 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007473 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007474 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007475 Value *YS = // (Y << C)
7476 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7477 // (X + (Y << C))
7478 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7479 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007480 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007481 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007482 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007483 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007484
Chris Lattner13d4ab42006-05-31 21:14:00 +00007485 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007486 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7487 match(Op0BO->getOperand(0),
7488 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007489 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007490 cast<BinaryOperator>(Op0BO->getOperand(0))
7491 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007492 Value *YS = // (Y << C)
7493 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7494 // X & (CC << C)
7495 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7496 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007497
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007498 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007500
Chris Lattner11021cb2005-09-18 05:12:10 +00007501 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007502 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007503 }
7504
7505
7506 // If the operand is an bitwise operator with a constant RHS, and the
7507 // shift is the only use, we can pull it out of the shift.
7508 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7509 bool isValid = true; // Valid only for And, Or, Xor
7510 bool highBitSet = false; // Transform if high bit of constant set?
7511
7512 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007513 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007514 case Instruction::Add:
7515 isValid = isLeftShift;
7516 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007517 case Instruction::Or:
7518 case Instruction::Xor:
7519 highBitSet = false;
7520 break;
7521 case Instruction::And:
7522 highBitSet = true;
7523 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007524 }
7525
7526 // If this is a signed shift right, and the high bit is modified
7527 // by the logical operation, do not perform the transformation.
7528 // The highBitSet boolean indicates the value of the high bit of
7529 // the constant which would cause it to be modified for this
7530 // operation.
7531 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007532 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007533 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007534
7535 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007536 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007537
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007538 Value *NewShift =
7539 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007540 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007541
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007542 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007543 NewRHS);
7544 }
7545 }
7546 }
7547 }
7548
Chris Lattnerad0124c2006-01-06 07:52:12 +00007549 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007550 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7551 if (ShiftOp && !ShiftOp->isShift())
7552 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007553
Reid Spencerb83eb642006-10-20 07:07:24 +00007554 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007555 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007556 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7557 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007558 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7559 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7560 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007561
Zhou Sheng4351c642007-04-02 08:20:41 +00007562 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007563
7564 const IntegerType *Ty = cast<IntegerType>(I.getType());
7565
7566 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007567 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007568 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7569 // saturates.
7570 if (AmtSum >= TypeBits) {
7571 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007572 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007573 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7574 }
7575
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007576 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007577 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007578 }
7579
7580 if (ShiftOp->getOpcode() == Instruction::LShr &&
7581 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007582 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007583 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007584
Chris Lattnerb87056f2007-02-05 00:57:54 +00007585 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007586 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007587 }
7588
7589 if (ShiftOp->getOpcode() == Instruction::AShr &&
7590 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007591 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007592 if (AmtSum >= TypeBits)
7593 AmtSum = TypeBits-1;
7594
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007595 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007596
Zhou Shenge9e03f62007-03-28 15:02:20 +00007597 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007598 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007599 }
7600
Chris Lattnerb87056f2007-02-05 00:57:54 +00007601 // Okay, if we get here, one shift must be left, and the other shift must be
7602 // right. See if the amounts are equal.
7603 if (ShiftAmt1 == ShiftAmt2) {
7604 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7605 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007606 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007607 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007608 }
7609 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7610 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007611 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007612 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613 }
7614 // We can simplify ((X << C) >>s C) into a trunc + sext.
7615 // NOTE: we could do this for any C, but that would make 'unusual' integer
7616 // types. For now, just stick to ones well-supported by the code
7617 // generators.
7618 const Type *SExtType = 0;
7619 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007620 case 1 :
7621 case 8 :
7622 case 16 :
7623 case 32 :
7624 case 64 :
7625 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007626 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007627 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628 default: break;
7629 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007630 if (SExtType)
7631 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632 // Otherwise, we can't handle it yet.
7633 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007634 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007635
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007636 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007637 if (I.getOpcode() == Instruction::Shl) {
7638 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7639 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007640 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007641
Reid Spencer55702aa2007-03-25 21:11:44 +00007642 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007643 return BinaryOperator::CreateAnd(Shift,
7644 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007645 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007646
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007647 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 if (I.getOpcode() == Instruction::LShr) {
7649 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007650 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007651
Reid Spencerd5e30f02007-03-26 17:18:58 +00007652 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007653 return BinaryOperator::CreateAnd(Shift,
7654 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007655 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007656
7657 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7658 } else {
7659 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007660 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007662 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007663 if (I.getOpcode() == Instruction::Shl) {
7664 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7665 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007666 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7667 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007668
Reid Spencer55702aa2007-03-25 21:11:44 +00007669 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007670 return BinaryOperator::CreateAnd(Shift,
7671 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007672 }
7673
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007674 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007675 if (I.getOpcode() == Instruction::LShr) {
7676 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007677 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007678
Reid Spencer68d27cf2007-03-26 23:45:51 +00007679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007680 return BinaryOperator::CreateAnd(Shift,
7681 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007682 }
7683
7684 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007685 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007686 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007687 return 0;
7688}
7689
Chris Lattnera1be5662002-05-02 17:06:02 +00007690
Chris Lattnercfd65102005-10-29 04:36:15 +00007691/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7692/// expression. If so, decompose it, returning some value X, such that Val is
7693/// X*Scale+Offset.
7694///
7695static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007696 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007697 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7698 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007699 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007700 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007701 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007702 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007703 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7704 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7705 if (I->getOpcode() == Instruction::Shl) {
7706 // This is a value scaled by '1 << the shift amt'.
7707 Scale = 1U << RHS->getZExtValue();
7708 Offset = 0;
7709 return I->getOperand(0);
7710 } else if (I->getOpcode() == Instruction::Mul) {
7711 // This value is scaled by 'RHS'.
7712 Scale = RHS->getZExtValue();
7713 Offset = 0;
7714 return I->getOperand(0);
7715 } else if (I->getOpcode() == Instruction::Add) {
7716 // We have X+C. Check to see if we really have (X*C2)+C1,
7717 // where C1 is divisible by C2.
7718 unsigned SubScale;
7719 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007720 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7721 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007722 Offset += RHS->getZExtValue();
7723 Scale = SubScale;
7724 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007725 }
7726 }
7727 }
7728
7729 // Otherwise, we can't look past this.
7730 Scale = 1;
7731 Offset = 0;
7732 return Val;
7733}
7734
7735
Chris Lattnerb3f83972005-10-24 06:03:58 +00007736/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7737/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007738Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007739 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007740 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007741
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007742 BuilderTy AllocaBuilder(*Builder);
7743 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7744
Chris Lattnerb53c2382005-10-24 06:22:12 +00007745 // Remove any uses of AI that are dead.
7746 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007747
Chris Lattnerb53c2382005-10-24 06:22:12 +00007748 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7749 Instruction *User = cast<Instruction>(*UI++);
7750 if (isInstructionTriviallyDead(User)) {
7751 while (UI != E && *UI == User)
7752 ++UI; // If this instruction uses AI more than once, don't break UI.
7753
Chris Lattnerb53c2382005-10-24 06:22:12 +00007754 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007755 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007756 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007757 }
7758 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007759
7760 // This requires TargetData to get the alloca alignment and size information.
7761 if (!TD) return 0;
7762
Chris Lattnerb3f83972005-10-24 06:03:58 +00007763 // Get the type really allocated and the type casted to.
7764 const Type *AllocElTy = AI.getAllocatedType();
7765 const Type *CastElTy = PTy->getElementType();
7766 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007767
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007768 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7769 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007770 if (CastElTyAlign < AllocElTyAlign) return 0;
7771
Chris Lattner39387a52005-10-24 06:35:18 +00007772 // If the allocation has multiple uses, only promote it if we are strictly
7773 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007774 // same, we open the door to infinite loops of various kinds. (A reference
7775 // from a dbg.declare doesn't count as a use for this purpose.)
7776 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7777 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007778
Duncan Sands777d2302009-05-09 07:06:46 +00007779 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7780 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007781 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007782
Chris Lattner455fcc82005-10-29 03:19:53 +00007783 // See if we can satisfy the modulus by pulling a scale out of the array
7784 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007785 unsigned ArraySizeScale;
7786 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007787 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007788 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7789 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007790
Chris Lattner455fcc82005-10-29 03:19:53 +00007791 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7792 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007793 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7794 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007795
Chris Lattner455fcc82005-10-29 03:19:53 +00007796 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7797 Value *Amt = 0;
7798 if (Scale == 1) {
7799 Amt = NumElements;
7800 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007801 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007802 // Insert before the alloca, not before the cast.
7803 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007804 }
7805
Jeff Cohen86796be2007-04-04 16:58:57 +00007806 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007807 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007808 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007809 }
7810
Chris Lattnerb3f83972005-10-24 06:03:58 +00007811 AllocationInst *New;
7812 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007813 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007814 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007815 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7816 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007817 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007818
Dale Johannesena0a66372009-03-05 00:39:02 +00007819 // If the allocation has one real use plus a dbg.declare, just remove the
7820 // declare.
7821 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7822 EraseInstFromFunction(*DI);
7823 }
7824 // If the allocation has multiple real uses, insert a cast and change all
7825 // things that used it to use the new cast. This will also hack on CI, but it
7826 // will die soon.
7827 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007828 // New is the allocation instruction, pointer typed. AI is the original
7829 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007830 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007831 AI.replaceAllUsesWith(NewCast);
7832 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007833 return ReplaceInstUsesWith(CI, New);
7834}
7835
Chris Lattner70074e02006-05-13 02:06:03 +00007836/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007837/// and return it as type Ty without inserting any new casts and without
7838/// changing the computed value. This is used by code that tries to decide
7839/// whether promoting or shrinking integer operations to wider or smaller types
7840/// will allow us to eliminate a truncate or extend.
7841///
7842/// This is a truncation operation if Ty is smaller than V->getType(), or an
7843/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007844///
7845/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7846/// should return true if trunc(V) can be computed by computing V in the smaller
7847/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7848/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7849/// efficiently truncated.
7850///
7851/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7852/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7853/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007854bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007855 unsigned CastOpc,
7856 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007857 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007858 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007859 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007860
7861 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007862 if (!I) return false;
7863
Dan Gohman6de29f82009-06-15 22:12:54 +00007864 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007865
Chris Lattner951626b2007-08-02 06:11:14 +00007866 // If this is an extension or truncate, we can often eliminate it.
7867 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7868 // If this is a cast from the destination type, we can trivially eliminate
7869 // it, and this will remove a cast overall.
7870 if (I->getOperand(0)->getType() == Ty) {
7871 // If the first operand is itself a cast, and is eliminable, do not count
7872 // this as an eliminable cast. We would prefer to eliminate those two
7873 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007874 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007875 ++NumCastsRemoved;
7876 return true;
7877 }
7878 }
7879
7880 // We can't extend or shrink something that has multiple uses: doing so would
7881 // require duplicating the instruction in general, which isn't profitable.
7882 if (!I->hasOneUse()) return false;
7883
Evan Chengf35fd542009-01-15 17:01:23 +00007884 unsigned Opc = I->getOpcode();
7885 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007886 case Instruction::Add:
7887 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007888 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007889 case Instruction::And:
7890 case Instruction::Or:
7891 case Instruction::Xor:
7892 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007893 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007894 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007895 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007896 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007897
Eli Friedman070a9812009-07-13 22:46:01 +00007898 case Instruction::UDiv:
7899 case Instruction::URem: {
7900 // UDiv and URem can be truncated if all the truncated bits are zero.
7901 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7902 uint32_t BitWidth = Ty->getScalarSizeInBits();
7903 if (BitWidth < OrigBitWidth) {
7904 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7905 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7906 MaskedValueIsZero(I->getOperand(1), Mask)) {
7907 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7908 NumCastsRemoved) &&
7909 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7910 NumCastsRemoved);
7911 }
7912 }
7913 break;
7914 }
Chris Lattner46b96052006-11-29 07:18:39 +00007915 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007916 // If we are truncating the result of this SHL, and if it's a shift of a
7917 // constant amount, we can always perform a SHL in a smaller type.
7918 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007919 uint32_t BitWidth = Ty->getScalarSizeInBits();
7920 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007921 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007922 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007923 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007924 }
7925 break;
7926 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007927 // If this is a truncate of a logical shr, we can truncate it to a smaller
7928 // lshr iff we know that the bits we would otherwise be shifting in are
7929 // already zeros.
7930 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007931 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7932 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007933 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007934 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007935 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7936 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007937 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007938 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007939 }
7940 }
Chris Lattner46b96052006-11-29 07:18:39 +00007941 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007942 case Instruction::ZExt:
7943 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007944 case Instruction::Trunc:
7945 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007946 // can safely replace it. Note that replacing it does not reduce the number
7947 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007948 if (Opc == CastOpc)
7949 return true;
7950
7951 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007952 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007953 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007954 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007955 case Instruction::Select: {
7956 SelectInst *SI = cast<SelectInst>(I);
7957 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007958 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007959 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007960 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007961 }
Chris Lattner8114b712008-06-18 04:00:49 +00007962 case Instruction::PHI: {
7963 // We can change a phi if we can change all operands.
7964 PHINode *PN = cast<PHINode>(I);
7965 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7966 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007967 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007968 return false;
7969 return true;
7970 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007971 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007972 // TODO: Can handle more cases here.
7973 break;
7974 }
7975
7976 return false;
7977}
7978
7979/// EvaluateInDifferentType - Given an expression that
7980/// CanEvaluateInDifferentType returns true for, actually insert the code to
7981/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007982Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007983 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007984 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007985 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007986 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007987
7988 // Otherwise, it must be an instruction.
7989 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007990 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007991 unsigned Opc = I->getOpcode();
7992 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007993 case Instruction::Add:
7994 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007995 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007996 case Instruction::And:
7997 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007998 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007999 case Instruction::AShr:
8000 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008001 case Instruction::Shl:
8002 case Instruction::UDiv:
8003 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008004 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008005 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008006 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008007 break;
8008 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008009 case Instruction::Trunc:
8010 case Instruction::ZExt:
8011 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008012 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008013 // just return the source. There's no need to insert it because it is not
8014 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008015 if (I->getOperand(0)->getType() == Ty)
8016 return I->getOperand(0);
8017
Chris Lattner8114b712008-06-18 04:00:49 +00008018 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008019 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008020 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008021 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008022 case Instruction::Select: {
8023 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8024 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8025 Res = SelectInst::Create(I->getOperand(0), True, False);
8026 break;
8027 }
Chris Lattner8114b712008-06-18 04:00:49 +00008028 case Instruction::PHI: {
8029 PHINode *OPN = cast<PHINode>(I);
8030 PHINode *NPN = PHINode::Create(Ty);
8031 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8032 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8033 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8034 }
8035 Res = NPN;
8036 break;
8037 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008038 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008039 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008040 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008041 break;
8042 }
8043
Chris Lattner8114b712008-06-18 04:00:49 +00008044 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008045 return InsertNewInstBefore(Res, *I);
8046}
8047
Reid Spencer3da59db2006-11-27 01:05:10 +00008048/// @brief Implement the transforms common to all CastInst visitors.
8049Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008050 Value *Src = CI.getOperand(0);
8051
Dan Gohman23d9d272007-05-11 21:10:54 +00008052 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008053 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008054 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008055 if (Instruction::CastOps opc =
8056 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8057 // The first cast (CSrc) is eliminable so we need to fix up or replace
8058 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008059 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008060 }
8061 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008062
Reid Spencer3da59db2006-11-27 01:05:10 +00008063 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008064 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8065 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8066 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008067
8068 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008069 if (isa<PHINode>(Src))
8070 if (Instruction *NV = FoldOpIntoPhi(CI))
8071 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008072
Reid Spencer3da59db2006-11-27 01:05:10 +00008073 return 0;
8074}
8075
Chris Lattner46cd5a12009-01-09 05:44:56 +00008076/// FindElementAtOffset - Given a type and a constant offset, determine whether
8077/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008078/// the specified offset. If so, fill them into NewIndices and return the
8079/// resultant element type, otherwise return null.
8080static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8081 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008082 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008083 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008084 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008085 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008086
8087 // Start with the index over the outer type. Note that the type size
8088 // might be zero (even if the offset isn't zero) if the indexed type
8089 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008090 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008091 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008092 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008093 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008094 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008095
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008096 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008097 if (Offset < 0) {
8098 --FirstIdx;
8099 Offset += TySize;
8100 assert(Offset >= 0);
8101 }
8102 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8103 }
8104
Owen Andersoneed707b2009-07-24 23:12:02 +00008105 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008106
8107 // Index into the types. If we fail, set OrigBase to null.
8108 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008109 // Indexing into tail padding between struct/array elements.
8110 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008111 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008112
Chris Lattner46cd5a12009-01-09 05:44:56 +00008113 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8114 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008115 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8116 "Offset must stay within the indexed type");
8117
Chris Lattner46cd5a12009-01-09 05:44:56 +00008118 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008119 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008120
8121 Offset -= SL->getElementOffset(Elt);
8122 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008123 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008124 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008125 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008126 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008127 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008128 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008129 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008130 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008131 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008132 }
8133 }
8134
Chris Lattner3914f722009-01-24 01:00:13 +00008135 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008136}
8137
Chris Lattnerd3e28342007-04-27 17:44:50 +00008138/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8139Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8140 Value *Src = CI.getOperand(0);
8141
Chris Lattnerd3e28342007-04-27 17:44:50 +00008142 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008143 // If casting the result of a getelementptr instruction with no offset, turn
8144 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008145 if (GEP->hasAllZeroIndices()) {
8146 // Changing the cast operand is usually not a good idea but it is safe
8147 // here because the pointer operand is being replaced with another
8148 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008149 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008150 CI.setOperand(0, GEP->getOperand(0));
8151 return &CI;
8152 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008153
8154 // If the GEP has a single use, and the base pointer is a bitcast, and the
8155 // GEP computes a constant offset, see if we can convert these three
8156 // instructions into fewer. This typically happens with unions and other
8157 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008158 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008159 if (GEP->hasAllConstantIndices()) {
8160 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008161 ConstantInt *OffsetV =
8162 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008163 int64_t Offset = OffsetV->getSExtValue();
8164
8165 // Get the base pointer input of the bitcast, and the type it points to.
8166 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8167 const Type *GEPIdxTy =
8168 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008169 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008170 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008171 // If we were able to index down into an element, create the GEP
8172 // and bitcast the result. This eliminates one bitcast, potentially
8173 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008174 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8175 Builder->CreateInBoundsGEP(OrigBase,
8176 NewIndices.begin(), NewIndices.end()) :
8177 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008179
Chris Lattner46cd5a12009-01-09 05:44:56 +00008180 if (isa<BitCastInst>(CI))
8181 return new BitCastInst(NGEP, CI.getType());
8182 assert(isa<PtrToIntInst>(CI));
8183 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008184 }
8185 }
8186 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008187 }
8188
8189 return commonCastTransforms(CI);
8190}
8191
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008192/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8193/// type like i42. We don't want to introduce operations on random non-legal
8194/// integer types where they don't already exist in the code. In the future,
8195/// we should consider making this based off target-data, so that 32-bit targets
8196/// won't get i64 operations etc.
8197static bool isSafeIntegerType(const Type *Ty) {
8198 switch (Ty->getPrimitiveSizeInBits()) {
8199 case 8:
8200 case 16:
8201 case 32:
8202 case 64:
8203 return true;
8204 default:
8205 return false;
8206 }
8207}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008208
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008209/// commonIntCastTransforms - This function implements the common transforms
8210/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008211Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8212 if (Instruction *Result = commonCastTransforms(CI))
8213 return Result;
8214
8215 Value *Src = CI.getOperand(0);
8216 const Type *SrcTy = Src->getType();
8217 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008218 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8219 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008220
Reid Spencer3da59db2006-11-27 01:05:10 +00008221 // See if we can simplify any instructions used by the LHS whose sole
8222 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008223 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008224 return &CI;
8225
8226 // If the source isn't an instruction or has more than one use then we
8227 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008228 Instruction *SrcI = dyn_cast<Instruction>(Src);
8229 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008230 return 0;
8231
Chris Lattnerc739cd62007-03-03 05:27:34 +00008232 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008233 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008234 // Only do this if the dest type is a simple type, don't convert the
8235 // expression tree to something weird like i93 unless the source is also
8236 // strange.
8237 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008238 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8239 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008240 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008241 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008242 // eliminates the cast, so it is always a win. If this is a zero-extension,
8243 // we need to do an AND to maintain the clear top-part of the computation,
8244 // so we require that the input have eliminated at least one cast. If this
8245 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008246 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008247 bool DoXForm = false;
8248 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008249 switch (CI.getOpcode()) {
8250 default:
8251 // All the others use floating point so we shouldn't actually
8252 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008253 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008254 case Instruction::Trunc:
8255 DoXForm = true;
8256 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008257 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008258 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008259 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008260 // If it's unnecessary to issue an AND to clear the high bits, it's
8261 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008262 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008263 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8264 if (MaskedValueIsZero(TryRes, Mask))
8265 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008266
8267 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008268 if (TryI->use_empty())
8269 EraseInstFromFunction(*TryI);
8270 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008271 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008272 }
Evan Chengf35fd542009-01-15 17:01:23 +00008273 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008274 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008275 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008276 // If we do not have to emit the truncate + sext pair, then it's always
8277 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008278 //
8279 // It's not safe to eliminate the trunc + sext pair if one of the
8280 // eliminated cast is a truncate. e.g.
8281 // t2 = trunc i32 t1 to i16
8282 // t3 = sext i16 t2 to i32
8283 // !=
8284 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008285 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008286 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8287 if (NumSignBits > (DestBitSize - SrcBitSize))
8288 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008289
8290 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008291 if (TryI->use_empty())
8292 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008293 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008294 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008295 }
Evan Chengf35fd542009-01-15 17:01:23 +00008296 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008297
8298 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008299 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8300 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008301 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8302 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008303 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008304 // Just replace this cast with the result.
8305 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008306
Reid Spencer3da59db2006-11-27 01:05:10 +00008307 assert(Res->getType() == DestTy);
8308 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008309 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008310 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008311 // Just replace this cast with the result.
8312 return ReplaceInstUsesWith(CI, Res);
8313 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008314 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008315
8316 // If the high bits are already zero, just replace this cast with the
8317 // result.
8318 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8319 if (MaskedValueIsZero(Res, Mask))
8320 return ReplaceInstUsesWith(CI, Res);
8321
8322 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008323 Constant *C = ConstantInt::get(*Context,
8324 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008325 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008326 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008327 case Instruction::SExt: {
8328 // If the high bits are already filled with sign bit, just replace this
8329 // cast with the result.
8330 unsigned NumSignBits = ComputeNumSignBits(Res);
8331 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008332 return ReplaceInstUsesWith(CI, Res);
8333
Reid Spencer3da59db2006-11-27 01:05:10 +00008334 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008335 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008336 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008337 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008338 }
8339 }
8340
8341 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8342 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8343
8344 switch (SrcI->getOpcode()) {
8345 case Instruction::Add:
8346 case Instruction::Mul:
8347 case Instruction::And:
8348 case Instruction::Or:
8349 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008350 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008351 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8352 // Don't insert two casts unless at least one can be eliminated.
8353 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008354 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008355 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8356 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008357 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008358 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008359 }
8360 }
8361
8362 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8363 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8364 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008365 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008366 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008367 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008368 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008369 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008370 }
8371 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008372
Eli Friedman65445c52009-07-13 21:45:57 +00008373 case Instruction::Shl: {
8374 // Canonicalize trunc inside shl, if we can.
8375 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8376 if (CI && DestBitSize < SrcBitSize &&
8377 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008378 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8379 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008380 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 }
8382 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008383 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008384 }
8385 return 0;
8386}
8387
Chris Lattner8a9f5712007-04-11 06:57:46 +00008388Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008389 if (Instruction *Result = commonIntCastTransforms(CI))
8390 return Result;
8391
8392 Value *Src = CI.getOperand(0);
8393 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008394 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8395 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008396
8397 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008398 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008399 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008400 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008401 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008402 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008403 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008404
Chris Lattner4f9797d2009-03-24 18:15:30 +00008405 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8406 ConstantInt *ShAmtV = 0;
8407 Value *ShiftOp = 0;
8408 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008409 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008410 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8411
8412 // Get a mask for the bits shifting in.
8413 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8414 if (MaskedValueIsZero(ShiftOp, Mask)) {
8415 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008416 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008417
8418 // Okay, we can shrink this. Truncate the input, then return a new
8419 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008420 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008421 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008422 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008423 }
8424 }
8425
8426 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008427}
8428
Evan Chengb98a10e2008-03-24 00:21:34 +00008429/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8430/// in order to eliminate the icmp.
8431Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8432 bool DoXform) {
8433 // If we are just checking for a icmp eq of a single bit and zext'ing it
8434 // to an integer, then shift the bit to the appropriate place and then
8435 // cast to integer to avoid the comparison.
8436 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8437 const APInt &Op1CV = Op1C->getValue();
8438
8439 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8440 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8441 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8442 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8443 if (!DoXform) return ICI;
8444
8445 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008446 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008447 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008448 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008449 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008450 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008451
8452 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008453 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008454 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008455 }
8456
8457 return ReplaceInstUsesWith(CI, In);
8458 }
8459
8460
8461
8462 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8463 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8464 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8465 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8466 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8467 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8468 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8469 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8470 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8471 // This only works for EQ and NE
8472 ICI->isEquality()) {
8473 // If Op1C some other power of two, convert:
8474 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8475 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8476 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8477 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8478
8479 APInt KnownZeroMask(~KnownZero);
8480 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8481 if (!DoXform) return ICI;
8482
8483 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8484 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8485 // (X&4) == 2 --> false
8486 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008487 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008488 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008489 return ReplaceInstUsesWith(CI, Res);
8490 }
8491
8492 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8493 Value *In = ICI->getOperand(0);
8494 if (ShiftAmt) {
8495 // Perform a logical shr by shiftamt.
8496 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008497 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8498 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008499 }
8500
8501 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008502 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008503 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008504 }
8505
8506 if (CI.getType() == In->getType())
8507 return ReplaceInstUsesWith(CI, In);
8508 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008509 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008510 }
8511 }
8512 }
8513
8514 return 0;
8515}
8516
Chris Lattner8a9f5712007-04-11 06:57:46 +00008517Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008518 // If one of the common conversion will work ..
8519 if (Instruction *Result = commonIntCastTransforms(CI))
8520 return Result;
8521
8522 Value *Src = CI.getOperand(0);
8523
Chris Lattnera84f47c2009-02-17 20:47:23 +00008524 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8525 // types and if the sizes are just right we can convert this into a logical
8526 // 'and' which will be much cheaper than the pair of casts.
8527 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8528 // Get the sizes of the types involved. We know that the intermediate type
8529 // will be smaller than A or C, but don't know the relation between A and C.
8530 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008531 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8532 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8533 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008534 // If we're actually extending zero bits, then if
8535 // SrcSize < DstSize: zext(a & mask)
8536 // SrcSize == DstSize: a & mask
8537 // SrcSize > DstSize: trunc(a) & mask
8538 if (SrcSize < DstSize) {
8539 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008540 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008541 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008542 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008543 }
8544
8545 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008546 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008547 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008548 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008549 }
8550 if (SrcSize > DstSize) {
8551 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008552 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008553 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008554 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008555 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008556 }
8557 }
8558
Evan Chengb98a10e2008-03-24 00:21:34 +00008559 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8560 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008561
Evan Chengb98a10e2008-03-24 00:21:34 +00008562 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8563 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8564 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8565 // of the (zext icmp) will be transformed.
8566 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8567 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8568 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8569 (transformZExtICmp(LHS, CI, false) ||
8570 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008571 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8572 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008573 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008574 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008575 }
8576
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008577 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008578 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8579 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8580 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8581 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008582 if (TI0->getType() == CI.getType())
8583 return
8584 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008585 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008586 }
8587
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008588 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8589 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8590 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8591 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8592 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8593 And->getOperand(1) == C)
8594 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8595 Value *TI0 = TI->getOperand(0);
8596 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008597 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008598 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008599 return BinaryOperator::CreateXor(NewAnd, ZC);
8600 }
8601 }
8602
Reid Spencer3da59db2006-11-27 01:05:10 +00008603 return 0;
8604}
8605
Chris Lattner8a9f5712007-04-11 06:57:46 +00008606Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008607 if (Instruction *I = commonIntCastTransforms(CI))
8608 return I;
8609
Chris Lattner8a9f5712007-04-11 06:57:46 +00008610 Value *Src = CI.getOperand(0);
8611
Dan Gohman1975d032008-10-30 20:40:10 +00008612 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008613 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008614 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008615 Constant::getAllOnesValue(CI.getType()),
8616 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008617
8618 // See if the value being truncated is already sign extended. If so, just
8619 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008620 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008621 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008622 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8623 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8624 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008625 unsigned NumSignBits = ComputeNumSignBits(Op);
8626
8627 if (OpBits == DestBits) {
8628 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8629 // bits, it is already ready.
8630 if (NumSignBits > DestBits-MidBits)
8631 return ReplaceInstUsesWith(CI, Op);
8632 } else if (OpBits < DestBits) {
8633 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8634 // bits, just sext from i32.
8635 if (NumSignBits > OpBits-MidBits)
8636 return new SExtInst(Op, CI.getType(), "tmp");
8637 } else {
8638 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8639 // bits, just truncate to i32.
8640 if (NumSignBits > OpBits-MidBits)
8641 return new TruncInst(Op, CI.getType(), "tmp");
8642 }
8643 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008644
8645 // If the input is a shl/ashr pair of a same constant, then this is a sign
8646 // extension from a smaller value. If we could trust arbitrary bitwidth
8647 // integers, we could turn this into a truncate to the smaller bit and then
8648 // use a sext for the whole extension. Since we don't, look deeper and check
8649 // for a truncate. If the source and dest are the same type, eliminate the
8650 // trunc and extend and just do shifts. For example, turn:
8651 // %a = trunc i32 %i to i8
8652 // %b = shl i8 %a, 6
8653 // %c = ashr i8 %b, 6
8654 // %d = sext i8 %c to i32
8655 // into:
8656 // %a = shl i32 %i, 30
8657 // %d = ashr i32 %a, 30
8658 Value *A = 0;
8659 ConstantInt *BA = 0, *CA = 0;
8660 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008661 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008662 BA == CA && isa<TruncInst>(A)) {
8663 Value *I = cast<TruncInst>(A)->getOperand(0);
8664 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008665 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8666 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008667 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008668 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008669 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008670 return BinaryOperator::CreateAShr(I, ShAmtV);
8671 }
8672 }
8673
Chris Lattnerba417832007-04-11 06:12:58 +00008674 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008675}
8676
Chris Lattnerb7530652008-01-27 05:29:54 +00008677/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8678/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008679static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008680 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008681 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008682 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008683 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8684 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008685 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008686 return 0;
8687}
8688
8689/// LookThroughFPExtensions - If this is an fp extension instruction, look
8690/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008691static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008692 if (Instruction *I = dyn_cast<Instruction>(V))
8693 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008694 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008695
8696 // If this value is a constant, return the constant in the smallest FP type
8697 // that can accurately represent it. This allows us to turn
8698 // (float)((double)X+2.0) into x+2.0f.
8699 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008700 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008701 return V; // No constant folding of this.
8702 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008703 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008704 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008705 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008706 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008707 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008708 return V;
8709 // Don't try to shrink to various long double types.
8710 }
8711
8712 return V;
8713}
8714
8715Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8716 if (Instruction *I = commonCastTransforms(CI))
8717 return I;
8718
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008719 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008720 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008721 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008722 // many builtins (sqrt, etc).
8723 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8724 if (OpI && OpI->hasOneUse()) {
8725 switch (OpI->getOpcode()) {
8726 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008727 case Instruction::FAdd:
8728 case Instruction::FSub:
8729 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008730 case Instruction::FDiv:
8731 case Instruction::FRem:
8732 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008733 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8734 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008735 if (LHSTrunc->getType() != SrcTy &&
8736 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008737 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008738 // If the source types were both smaller than the destination type of
8739 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008740 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8741 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008742 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8743 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008744 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008745 }
8746 }
8747 break;
8748 }
8749 }
8750 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008751}
8752
8753Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8754 return commonCastTransforms(CI);
8755}
8756
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008757Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008758 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8759 if (OpI == 0)
8760 return commonCastTransforms(FI);
8761
8762 // fptoui(uitofp(X)) --> X
8763 // fptoui(sitofp(X)) --> X
8764 // This is safe if the intermediate type has enough bits in its mantissa to
8765 // accurately represent all values of X. For example, do not do this with
8766 // i64->float->i64. This is also safe for sitofp case, because any negative
8767 // 'X' value would cause an undefined result for the fptoui.
8768 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8769 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008770 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008771 OpI->getType()->getFPMantissaWidth())
8772 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008773
8774 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008775}
8776
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008777Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008778 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8779 if (OpI == 0)
8780 return commonCastTransforms(FI);
8781
8782 // fptosi(sitofp(X)) --> X
8783 // fptosi(uitofp(X)) --> X
8784 // This is safe if the intermediate type has enough bits in its mantissa to
8785 // accurately represent all values of X. For example, do not do this with
8786 // i64->float->i64. This is also safe for sitofp case, because any negative
8787 // 'X' value would cause an undefined result for the fptoui.
8788 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8789 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008790 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008791 OpI->getType()->getFPMantissaWidth())
8792 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008793
8794 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008795}
8796
8797Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8798 return commonCastTransforms(CI);
8799}
8800
8801Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8802 return commonCastTransforms(CI);
8803}
8804
Chris Lattnera0e69692009-03-24 18:35:40 +00008805Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8806 // If the destination integer type is smaller than the intptr_t type for
8807 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8808 // trunc to be exposed to other transforms. Don't do this for extending
8809 // ptrtoint's, because we don't know if the target sign or zero extends its
8810 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008811 if (TD &&
8812 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008813 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8814 TD->getIntPtrType(CI.getContext()),
8815 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008816 return new TruncInst(P, CI.getType());
8817 }
8818
Chris Lattnerd3e28342007-04-27 17:44:50 +00008819 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008820}
8821
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008822Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008823 // If the source integer type is larger than the intptr_t type for
8824 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8825 // allows the trunc to be exposed to other transforms. Don't do this for
8826 // extending inttoptr's, because we don't know if the target sign or zero
8827 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008828 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008829 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008830 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8831 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008832 return new IntToPtrInst(P, CI.getType());
8833 }
8834
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008835 if (Instruction *I = commonCastTransforms(CI))
8836 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008837
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008838 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008839}
8840
Chris Lattnerd3e28342007-04-27 17:44:50 +00008841Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008842 // If the operands are integer typed then apply the integer transforms,
8843 // otherwise just apply the common ones.
8844 Value *Src = CI.getOperand(0);
8845 const Type *SrcTy = Src->getType();
8846 const Type *DestTy = CI.getType();
8847
Eli Friedman7e25d452009-07-13 20:53:00 +00008848 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008849 if (Instruction *I = commonPointerCastTransforms(CI))
8850 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008851 } else {
8852 if (Instruction *Result = commonCastTransforms(CI))
8853 return Result;
8854 }
8855
8856
8857 // Get rid of casts from one type to the same type. These are useless and can
8858 // be replaced by the operand.
8859 if (DestTy == Src->getType())
8860 return ReplaceInstUsesWith(CI, Src);
8861
Reid Spencer3da59db2006-11-27 01:05:10 +00008862 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008863 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8864 const Type *DstElTy = DstPTy->getElementType();
8865 const Type *SrcElTy = SrcPTy->getElementType();
8866
Nate Begeman83ad90a2008-03-31 00:22:16 +00008867 // If the address spaces don't match, don't eliminate the bitcast, which is
8868 // required for changing types.
8869 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8870 return 0;
8871
Victor Hernandez83d63912009-09-18 22:35:49 +00008872 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008873 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008874 // There is no need to modify malloc calls because it is their bitcast that
8875 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008876 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8877 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8878 return V;
8879
Chris Lattnerd717c182007-05-05 22:32:24 +00008880 // If the source and destination are pointers, and this cast is equivalent
8881 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008882 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008883 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008884 unsigned NumZeros = 0;
8885 while (SrcElTy != DstElTy &&
8886 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8887 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8888 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8889 ++NumZeros;
8890 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008891
Chris Lattnerd3e28342007-04-27 17:44:50 +00008892 // If we found a path from the src to dest, create the getelementptr now.
8893 if (SrcElTy == DstElTy) {
8894 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008895 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8896 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008897 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008898 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008899
Eli Friedman2451a642009-07-18 23:06:53 +00008900 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8901 if (DestVTy->getNumElements() == 1) {
8902 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008903 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008904 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008905 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008906 }
8907 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8908 }
8909 }
8910
8911 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8912 if (SrcVTy->getNumElements() == 1) {
8913 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008914 Value *Elem =
8915 Builder->CreateExtractElement(Src,
8916 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008917 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8918 }
8919 }
8920 }
8921
Reid Spencer3da59db2006-11-27 01:05:10 +00008922 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8923 if (SVI->hasOneUse()) {
8924 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8925 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008926 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008927 cast<VectorType>(DestTy)->getNumElements() ==
8928 SVI->getType()->getNumElements() &&
8929 SVI->getType()->getNumElements() ==
8930 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008931 CastInst *Tmp;
8932 // If either of the operands is a cast from CI.getType(), then
8933 // evaluating the shuffle in the casted destination's type will allow
8934 // us to eliminate at least one cast.
8935 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8936 Tmp->getOperand(0)->getType() == DestTy) ||
8937 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8938 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008939 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8940 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008941 // Return a new shuffle vector. Use the same element ID's, as we
8942 // know the vector types match #elts.
8943 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008944 }
8945 }
8946 }
8947 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008948 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008949}
8950
Chris Lattnere576b912004-04-09 23:46:01 +00008951/// GetSelectFoldableOperands - We want to turn code that looks like this:
8952/// %C = or %A, %B
8953/// %D = select %cond, %C, %A
8954/// into:
8955/// %C = select %cond, %B, 0
8956/// %D = or %A, %C
8957///
8958/// Assuming that the specified instruction is an operand to the select, return
8959/// a bitmask indicating which operands of this instruction are foldable if they
8960/// equal the other incoming value of the select.
8961///
8962static unsigned GetSelectFoldableOperands(Instruction *I) {
8963 switch (I->getOpcode()) {
8964 case Instruction::Add:
8965 case Instruction::Mul:
8966 case Instruction::And:
8967 case Instruction::Or:
8968 case Instruction::Xor:
8969 return 3; // Can fold through either operand.
8970 case Instruction::Sub: // Can only fold on the amount subtracted.
8971 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008972 case Instruction::LShr:
8973 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008974 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008975 default:
8976 return 0; // Cannot fold
8977 }
8978}
8979
8980/// GetSelectFoldableConstant - For the same transformation as the previous
8981/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008982static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008983 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008984 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008985 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008986 case Instruction::Add:
8987 case Instruction::Sub:
8988 case Instruction::Or:
8989 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008990 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008991 case Instruction::LShr:
8992 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008993 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008994 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008995 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008996 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008997 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008998 }
8999}
9000
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009001/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9002/// have the same opcode and only one use each. Try to simplify this.
9003Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9004 Instruction *FI) {
9005 if (TI->getNumOperands() == 1) {
9006 // If this is a non-volatile load or a cast from the same type,
9007 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009008 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009009 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9010 return 0;
9011 } else {
9012 return 0; // unknown unary op.
9013 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009014
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009015 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009016 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009017 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009018 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009019 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009020 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009021 }
9022
Reid Spencer832254e2007-02-02 02:16:23 +00009023 // Only handle binary operators here.
9024 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009025 return 0;
9026
9027 // Figure out if the operations have any operands in common.
9028 Value *MatchOp, *OtherOpT, *OtherOpF;
9029 bool MatchIsOpZero;
9030 if (TI->getOperand(0) == FI->getOperand(0)) {
9031 MatchOp = TI->getOperand(0);
9032 OtherOpT = TI->getOperand(1);
9033 OtherOpF = FI->getOperand(1);
9034 MatchIsOpZero = true;
9035 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9036 MatchOp = TI->getOperand(1);
9037 OtherOpT = TI->getOperand(0);
9038 OtherOpF = FI->getOperand(0);
9039 MatchIsOpZero = false;
9040 } else if (!TI->isCommutative()) {
9041 return 0;
9042 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9043 MatchOp = TI->getOperand(0);
9044 OtherOpT = TI->getOperand(1);
9045 OtherOpF = FI->getOperand(0);
9046 MatchIsOpZero = true;
9047 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9048 MatchOp = TI->getOperand(1);
9049 OtherOpT = TI->getOperand(0);
9050 OtherOpF = FI->getOperand(1);
9051 MatchIsOpZero = true;
9052 } else {
9053 return 0;
9054 }
9055
9056 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009057 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9058 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009059 InsertNewInstBefore(NewSI, SI);
9060
9061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9062 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009063 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009064 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009065 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009066 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009067 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009068 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009069}
9070
Evan Chengde621922009-03-31 20:42:45 +00009071static bool isSelect01(Constant *C1, Constant *C2) {
9072 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9073 if (!C1I)
9074 return false;
9075 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9076 if (!C2I)
9077 return false;
9078 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9079}
9080
9081/// FoldSelectIntoOp - Try fold the select into one of the operands to
9082/// facilitate further optimization.
9083Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9084 Value *FalseVal) {
9085 // See the comment above GetSelectFoldableOperands for a description of the
9086 // transformation we are doing here.
9087 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9088 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9089 !isa<Constant>(FalseVal)) {
9090 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9091 unsigned OpToFold = 0;
9092 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9093 OpToFold = 1;
9094 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9095 OpToFold = 2;
9096 }
9097
9098 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009099 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009100 Value *OOp = TVI->getOperand(2-OpToFold);
9101 // Avoid creating select between 2 constants unless it's selecting
9102 // between 0 and 1.
9103 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9104 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9105 InsertNewInstBefore(NewSel, SI);
9106 NewSel->takeName(TVI);
9107 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9108 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009109 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009110 }
9111 }
9112 }
9113 }
9114 }
9115
9116 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9117 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9118 !isa<Constant>(TrueVal)) {
9119 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9120 unsigned OpToFold = 0;
9121 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9122 OpToFold = 1;
9123 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9124 OpToFold = 2;
9125 }
9126
9127 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009128 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009129 Value *OOp = FVI->getOperand(2-OpToFold);
9130 // Avoid creating select between 2 constants unless it's selecting
9131 // between 0 and 1.
9132 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9133 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9134 InsertNewInstBefore(NewSel, SI);
9135 NewSel->takeName(FVI);
9136 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9137 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009138 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009139 }
9140 }
9141 }
9142 }
9143 }
9144
9145 return 0;
9146}
9147
Dan Gohman81b28ce2008-09-16 18:46:06 +00009148/// visitSelectInstWithICmp - Visit a SelectInst that has an
9149/// ICmpInst as its first operand.
9150///
9151Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9152 ICmpInst *ICI) {
9153 bool Changed = false;
9154 ICmpInst::Predicate Pred = ICI->getPredicate();
9155 Value *CmpLHS = ICI->getOperand(0);
9156 Value *CmpRHS = ICI->getOperand(1);
9157 Value *TrueVal = SI.getTrueValue();
9158 Value *FalseVal = SI.getFalseValue();
9159
9160 // Check cases where the comparison is with a constant that
9161 // can be adjusted to fit the min/max idiom. We may edit ICI in
9162 // place here, so make sure the select is the only user.
9163 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009164 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009165 switch (Pred) {
9166 default: break;
9167 case ICmpInst::ICMP_ULT:
9168 case ICmpInst::ICMP_SLT: {
9169 // X < MIN ? T : F --> F
9170 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9171 return ReplaceInstUsesWith(SI, FalseVal);
9172 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009173 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009174 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9175 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9176 Pred = ICmpInst::getSwappedPredicate(Pred);
9177 CmpRHS = AdjustedRHS;
9178 std::swap(FalseVal, TrueVal);
9179 ICI->setPredicate(Pred);
9180 ICI->setOperand(1, CmpRHS);
9181 SI.setOperand(1, TrueVal);
9182 SI.setOperand(2, FalseVal);
9183 Changed = true;
9184 }
9185 break;
9186 }
9187 case ICmpInst::ICMP_UGT:
9188 case ICmpInst::ICMP_SGT: {
9189 // X > MAX ? T : F --> F
9190 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9191 return ReplaceInstUsesWith(SI, FalseVal);
9192 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009193 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009194 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9195 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9196 Pred = ICmpInst::getSwappedPredicate(Pred);
9197 CmpRHS = AdjustedRHS;
9198 std::swap(FalseVal, TrueVal);
9199 ICI->setPredicate(Pred);
9200 ICI->setOperand(1, CmpRHS);
9201 SI.setOperand(1, TrueVal);
9202 SI.setOperand(2, FalseVal);
9203 Changed = true;
9204 }
9205 break;
9206 }
9207 }
9208
Dan Gohman1975d032008-10-30 20:40:10 +00009209 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9210 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009211 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009212 if (match(TrueVal, m_ConstantInt<-1>()) &&
9213 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009214 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009215 else if (match(TrueVal, m_ConstantInt<0>()) &&
9216 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009217 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9218
Dan Gohman1975d032008-10-30 20:40:10 +00009219 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9220 // If we are just checking for a icmp eq of a single bit and zext'ing it
9221 // to an integer, then shift the bit to the appropriate place and then
9222 // cast to integer to avoid the comparison.
9223 const APInt &Op1CV = CI->getValue();
9224
9225 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9226 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9227 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009228 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009229 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009230 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009231 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009232 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009233 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009234 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009235 if (In->getType() != SI.getType())
9236 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009237 true/*SExt*/, "tmp", ICI);
9238
9239 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009240 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009241 In->getName()+".not"), *ICI);
9242
9243 return ReplaceInstUsesWith(SI, In);
9244 }
9245 }
9246 }
9247
Dan Gohman81b28ce2008-09-16 18:46:06 +00009248 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9249 // Transform (X == Y) ? X : Y -> Y
9250 if (Pred == ICmpInst::ICMP_EQ)
9251 return ReplaceInstUsesWith(SI, FalseVal);
9252 // Transform (X != Y) ? X : Y -> X
9253 if (Pred == ICmpInst::ICMP_NE)
9254 return ReplaceInstUsesWith(SI, TrueVal);
9255 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9256
9257 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9258 // Transform (X == Y) ? Y : X -> X
9259 if (Pred == ICmpInst::ICMP_EQ)
9260 return ReplaceInstUsesWith(SI, FalseVal);
9261 // Transform (X != Y) ? Y : X -> Y
9262 if (Pred == ICmpInst::ICMP_NE)
9263 return ReplaceInstUsesWith(SI, TrueVal);
9264 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9265 }
9266
9267 /// NOTE: if we wanted to, this is where to detect integer ABS
9268
9269 return Changed ? &SI : 0;
9270}
9271
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009272/// isDefinedInBB - Return true if the value is an instruction defined in the
9273/// specified basicblock.
9274static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9275 const Instruction *I = dyn_cast<Instruction>(V);
9276 return I != 0 && I->getParent() == BB;
9277}
9278
9279
Chris Lattner3d69f462004-03-12 05:52:32 +00009280Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009281 Value *CondVal = SI.getCondition();
9282 Value *TrueVal = SI.getTrueValue();
9283 Value *FalseVal = SI.getFalseValue();
9284
9285 // select true, X, Y -> X
9286 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009287 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009288 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009289
9290 // select C, X, X -> X
9291 if (TrueVal == FalseVal)
9292 return ReplaceInstUsesWith(SI, TrueVal);
9293
Chris Lattnere87597f2004-10-16 18:11:37 +00009294 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9295 return ReplaceInstUsesWith(SI, FalseVal);
9296 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9299 if (isa<Constant>(TrueVal))
9300 return ReplaceInstUsesWith(SI, TrueVal);
9301 else
9302 return ReplaceInstUsesWith(SI, FalseVal);
9303 }
9304
Owen Anderson1d0be152009-08-13 21:58:54 +00009305 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009306 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009307 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009308 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009309 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009310 } else {
9311 // Change: A = select B, false, C --> A = and !B, C
9312 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009313 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009314 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009315 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009316 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009317 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009318 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009319 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009320 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009321 } else {
9322 // Change: A = select B, C, true --> A = or !B, C
9323 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009324 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009325 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009326 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009327 }
9328 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009329
9330 // select a, b, a -> a&b
9331 // select a, a, b -> a|b
9332 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009333 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009334 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009335 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009336 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009337
Chris Lattner2eefe512004-04-09 19:05:30 +00009338 // Selecting between two integer constants?
9339 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9340 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009341 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009342 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009343 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009344 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009345 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009346 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009347 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009348 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009349 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009350 }
Chris Lattner457dd822004-06-09 07:59:58 +00009351
Reid Spencere4d87aa2006-12-23 06:05:41 +00009352 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009353 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009354 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009355 // non-constant value, eliminate this whole mess. This corresponds to
9356 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009357 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009358 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009359 cast<Constant>(IC->getOperand(1))->isNullValue())
9360 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9361 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009362 isa<ConstantInt>(ICA->getOperand(1)) &&
9363 (ICA->getOperand(1) == TrueValC ||
9364 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009365 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9366 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009367 // know whether we have a icmp_ne or icmp_eq and whether the
9368 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009369 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009370 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009371 Value *V = ICA;
9372 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009373 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009374 Instruction::Xor, V, ICA->getOperand(1)), SI);
9375 return ReplaceInstUsesWith(SI, V);
9376 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009377 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009378 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009379
9380 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009381 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9382 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009383 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009384 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9385 // This is not safe in general for floating point:
9386 // consider X== -0, Y== +0.
9387 // It becomes safe if either operand is a nonzero constant.
9388 ConstantFP *CFPt, *CFPf;
9389 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9390 !CFPt->getValueAPF().isZero()) ||
9391 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9392 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009393 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009394 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009395 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009396 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009397 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009398 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009399
Reid Spencere4d87aa2006-12-23 06:05:41 +00009400 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009401 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009402 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9403 // This is not safe in general for floating point:
9404 // consider X== -0, Y== +0.
9405 // It becomes safe if either operand is a nonzero constant.
9406 ConstantFP *CFPt, *CFPf;
9407 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9408 !CFPt->getValueAPF().isZero()) ||
9409 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9410 !CFPf->getValueAPF().isZero()))
9411 return ReplaceInstUsesWith(SI, FalseVal);
9412 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009413 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009414 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9415 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009416 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009417 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009418 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009419 }
9420
9421 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009422 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9423 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9424 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009425
Chris Lattner87875da2005-01-13 22:52:24 +00009426 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9427 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9428 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009429 Instruction *AddOp = 0, *SubOp = 0;
9430
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009431 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9432 if (TI->getOpcode() == FI->getOpcode())
9433 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9434 return IV;
9435
9436 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9437 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009438 if ((TI->getOpcode() == Instruction::Sub &&
9439 FI->getOpcode() == Instruction::Add) ||
9440 (TI->getOpcode() == Instruction::FSub &&
9441 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009442 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009443 } else if ((FI->getOpcode() == Instruction::Sub &&
9444 TI->getOpcode() == Instruction::Add) ||
9445 (FI->getOpcode() == Instruction::FSub &&
9446 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009447 AddOp = TI; SubOp = FI;
9448 }
9449
9450 if (AddOp) {
9451 Value *OtherAddOp = 0;
9452 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9453 OtherAddOp = AddOp->getOperand(1);
9454 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9455 OtherAddOp = AddOp->getOperand(0);
9456 }
9457
9458 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009459 // So at this point we know we have (Y -> OtherAddOp):
9460 // select C, (add X, Y), (sub X, Z)
9461 Value *NegVal; // Compute -Z
9462 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009463 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009464 } else {
9465 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009466 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009467 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009468 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009469
9470 Value *NewTrueOp = OtherAddOp;
9471 Value *NewFalseOp = NegVal;
9472 if (AddOp != TI)
9473 std::swap(NewTrueOp, NewFalseOp);
9474 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009475 SelectInst::Create(CondVal, NewTrueOp,
9476 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009477
9478 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009479 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009480 }
9481 }
9482 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009483
Chris Lattnere576b912004-04-09 23:46:01 +00009484 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009485 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009486 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9487 if (FoldI)
9488 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009489 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009490
Chris Lattner5d1704d2009-09-27 19:57:57 +00009491 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009492 // to be live in the predecessor blocks. If they are instructions in SI's
9493 // block, we can't map to the predecessor.
Chris Lattner5d1704d2009-09-27 19:57:57 +00009494 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009495 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9496 isa<PHINode>(SI.getTrueValue())) &&
9497 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9498 isa<PHINode>(SI.getFalseValue())))
Chris Lattner5d1704d2009-09-27 19:57:57 +00009499 if (Instruction *NV = FoldOpIntoPhi(SI))
9500 return NV;
9501
Chris Lattnera1df33c2005-04-24 07:30:14 +00009502 if (BinaryOperator::isNot(CondVal)) {
9503 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9504 SI.setOperand(1, FalseVal);
9505 SI.setOperand(2, TrueVal);
9506 return &SI;
9507 }
9508
Chris Lattner3d69f462004-03-12 05:52:32 +00009509 return 0;
9510}
9511
Dan Gohmaneee962e2008-04-10 18:43:06 +00009512/// EnforceKnownAlignment - If the specified pointer points to an object that
9513/// we control, modify the object's alignment to PrefAlign. This isn't
9514/// often possible though. If alignment is important, a more reliable approach
9515/// is to simply align all global variables and allocation instructions to
9516/// their preferred alignment from the beginning.
9517///
9518static unsigned EnforceKnownAlignment(Value *V,
9519 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009520
Dan Gohmaneee962e2008-04-10 18:43:06 +00009521 User *U = dyn_cast<User>(V);
9522 if (!U) return Align;
9523
Dan Gohmanca178902009-07-17 20:47:02 +00009524 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009525 default: break;
9526 case Instruction::BitCast:
9527 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9528 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009529 // If all indexes are zero, it is just the alignment of the base pointer.
9530 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009531 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009532 if (!isa<Constant>(*i) ||
9533 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009534 AllZeroOperands = false;
9535 break;
9536 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009537
9538 if (AllZeroOperands) {
9539 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009540 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009541 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009542 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009543 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009544 }
9545
9546 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9547 // If there is a large requested alignment and we can, bump up the alignment
9548 // of the global.
9549 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009550 if (GV->getAlignment() >= PrefAlign)
9551 Align = GV->getAlignment();
9552 else {
9553 GV->setAlignment(PrefAlign);
9554 Align = PrefAlign;
9555 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009556 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009557 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9558 // If there is a requested alignment and if this is an alloca, round up.
9559 if (AI->getAlignment() >= PrefAlign)
9560 Align = AI->getAlignment();
9561 else {
9562 AI->setAlignment(PrefAlign);
9563 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009564 }
9565 }
9566
9567 return Align;
9568}
9569
9570/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9571/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9572/// and it is more than the alignment of the ultimate object, see if we can
9573/// increase the alignment of the ultimate object, making this check succeed.
9574unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9575 unsigned PrefAlign) {
9576 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9577 sizeof(PrefAlign) * CHAR_BIT;
9578 APInt Mask = APInt::getAllOnesValue(BitWidth);
9579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9580 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9581 unsigned TrailZ = KnownZero.countTrailingOnes();
9582 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9583
9584 if (PrefAlign > Align)
9585 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9586
9587 // We don't need to make any adjustment.
9588 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009589}
9590
Chris Lattnerf497b022008-01-13 23:50:23 +00009591Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009592 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009593 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009594 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009595 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009596
9597 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009598 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009599 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009600 return MI;
9601 }
9602
9603 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9604 // load/store.
9605 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9606 if (MemOpLength == 0) return 0;
9607
Chris Lattner37ac6082008-01-14 00:28:35 +00009608 // Source and destination pointer types are always "i8*" for intrinsic. See
9609 // if the size is something we can handle with a single primitive load/store.
9610 // A single load+store correctly handles overlapping memory in the memmove
9611 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009612 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009613 if (Size == 0) return MI; // Delete this mem transfer.
9614
9615 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009616 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009617
Chris Lattner37ac6082008-01-14 00:28:35 +00009618 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009619 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009620 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009621
9622 // Memcpy forces the use of i8* for the source and destination. That means
9623 // that if you're using memcpy to move one double around, you'll get a cast
9624 // from double* to i8*. We'd much rather use a double load+store rather than
9625 // an i64 load+store, here because this improves the odds that the source or
9626 // dest address will be promotable. See if we can find a better type than the
9627 // integer datatype.
9628 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9629 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009630 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009631 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9632 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009633 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009634 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9635 if (STy->getNumElements() == 1)
9636 SrcETy = STy->getElementType(0);
9637 else
9638 break;
9639 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9640 if (ATy->getNumElements() == 1)
9641 SrcETy = ATy->getElementType();
9642 else
9643 break;
9644 } else
9645 break;
9646 }
9647
Dan Gohman8f8e2692008-05-23 01:52:21 +00009648 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009649 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009650 }
9651 }
9652
9653
Chris Lattnerf497b022008-01-13 23:50:23 +00009654 // If the memcpy/memmove provides better alignment info than we can
9655 // infer, use it.
9656 SrcAlign = std::max(SrcAlign, CopyAlign);
9657 DstAlign = std::max(DstAlign, CopyAlign);
9658
Chris Lattner08142f22009-08-30 19:47:22 +00009659 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9660 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009661 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9662 InsertNewInstBefore(L, *MI);
9663 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9664
9665 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009666 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009667 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009668}
Chris Lattner3d69f462004-03-12 05:52:32 +00009669
Chris Lattner69ea9d22008-04-30 06:39:11 +00009670Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9671 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009672 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009673 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009674 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009675 return MI;
9676 }
9677
9678 // Extract the length and alignment and fill if they are constant.
9679 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9680 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009681 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009682 return 0;
9683 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009684 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009685
9686 // If the length is zero, this is a no-op
9687 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9688
9689 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9690 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009691 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009692
9693 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009694 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009695
9696 // Alignment 0 is identity for alignment 1 for memset, but not store.
9697 if (Alignment == 0) Alignment = 1;
9698
9699 // Extract the fill value and store.
9700 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009701 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009702 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009703
9704 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009705 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009706 return MI;
9707 }
9708
9709 return 0;
9710}
9711
9712
Chris Lattner8b0ea312006-01-13 20:11:04 +00009713/// visitCallInst - CallInst simplification. This mostly only handles folding
9714/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9715/// the heavy lifting.
9716///
Chris Lattner9fe38862003-06-19 17:00:31 +00009717Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009718 // If the caller function is nounwind, mark the call as nounwind, even if the
9719 // callee isn't.
9720 if (CI.getParent()->getParent()->doesNotThrow() &&
9721 !CI.doesNotThrow()) {
9722 CI.setDoesNotThrow();
9723 return &CI;
9724 }
9725
Chris Lattner8b0ea312006-01-13 20:11:04 +00009726 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9727 if (!II) return visitCallSite(&CI);
9728
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009729 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9730 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009731 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009732 bool Changed = false;
9733
9734 // memmove/cpy/set of zero bytes is a noop.
9735 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9736 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9737
Chris Lattner35b9e482004-10-12 04:52:52 +00009738 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009739 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009740 // Replace the instruction with just byte operations. We would
9741 // transform other cases to loads/stores, but we don't know if
9742 // alignment is sufficient.
9743 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009744 }
9745
Chris Lattner35b9e482004-10-12 04:52:52 +00009746 // If we have a memmove and the source operation is a constant global,
9747 // then the source and dest pointers can't alias, so we can change this
9748 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009749 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009750 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9751 if (GVSrc->isConstant()) {
9752 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009753 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9754 const Type *Tys[1];
9755 Tys[0] = CI.getOperand(3)->getType();
9756 CI.setOperand(0,
9757 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009758 Changed = true;
9759 }
Chris Lattnera935db82008-05-28 05:30:41 +00009760
9761 // memmove(x,x,size) -> noop.
9762 if (MMI->getSource() == MMI->getDest())
9763 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009764 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009765
Chris Lattner95a959d2006-03-06 20:18:44 +00009766 // If we can determine a pointer alignment that is bigger than currently
9767 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009768 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009769 if (Instruction *I = SimplifyMemTransfer(MI))
9770 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009771 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9772 if (Instruction *I = SimplifyMemSet(MSI))
9773 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009774 }
9775
Chris Lattner8b0ea312006-01-13 20:11:04 +00009776 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009777 }
9778
9779 switch (II->getIntrinsicID()) {
9780 default: break;
9781 case Intrinsic::bswap:
9782 // bswap(bswap(x)) -> x
9783 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9784 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9785 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9786 break;
9787 case Intrinsic::ppc_altivec_lvx:
9788 case Intrinsic::ppc_altivec_lvxl:
9789 case Intrinsic::x86_sse_loadu_ps:
9790 case Intrinsic::x86_sse2_loadu_pd:
9791 case Intrinsic::x86_sse2_loadu_dq:
9792 // Turn PPC lvx -> load if the pointer is known aligned.
9793 // Turn X86 loadups -> load if the pointer is known aligned.
9794 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009795 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9796 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009797 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009798 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009799 break;
9800 case Intrinsic::ppc_altivec_stvx:
9801 case Intrinsic::ppc_altivec_stvxl:
9802 // Turn stvx -> store if the pointer is known aligned.
9803 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9804 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009805 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009806 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009807 return new StoreInst(II->getOperand(1), Ptr);
9808 }
9809 break;
9810 case Intrinsic::x86_sse_storeu_ps:
9811 case Intrinsic::x86_sse2_storeu_pd:
9812 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009813 // Turn X86 storeu -> store if the pointer is known aligned.
9814 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9815 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009816 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009817 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009818 return new StoreInst(II->getOperand(2), Ptr);
9819 }
9820 break;
9821
9822 case Intrinsic::x86_sse_cvttss2si: {
9823 // These intrinsics only demands the 0th element of its input vector. If
9824 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009825 unsigned VWidth =
9826 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9827 APInt DemandedElts(VWidth, 1);
9828 APInt UndefElts(VWidth, 0);
9829 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009830 UndefElts)) {
9831 II->setOperand(1, V);
9832 return II;
9833 }
9834 break;
9835 }
9836
9837 case Intrinsic::ppc_altivec_vperm:
9838 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9839 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9840 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009841
Chris Lattner0521e3c2008-06-18 04:33:20 +00009842 // Check that all of the elements are integer constants or undefs.
9843 bool AllEltsOk = true;
9844 for (unsigned i = 0; i != 16; ++i) {
9845 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9846 !isa<UndefValue>(Mask->getOperand(i))) {
9847 AllEltsOk = false;
9848 break;
9849 }
9850 }
9851
9852 if (AllEltsOk) {
9853 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009854 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9855 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009856 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009857
Chris Lattner0521e3c2008-06-18 04:33:20 +00009858 // Only extract each element once.
9859 Value *ExtractedElts[32];
9860 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9861
Chris Lattnere2ed0572006-04-06 19:19:17 +00009862 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009863 if (isa<UndefValue>(Mask->getOperand(i)))
9864 continue;
9865 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9866 Idx &= 31; // Match the hardware behavior.
9867
9868 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009869 ExtractedElts[Idx] =
9870 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9871 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9872 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009873 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009874
Chris Lattner0521e3c2008-06-18 04:33:20 +00009875 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009876 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9877 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9878 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009879 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009880 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009881 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009882 }
9883 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009884
Chris Lattner0521e3c2008-06-18 04:33:20 +00009885 case Intrinsic::stackrestore: {
9886 // If the save is right next to the restore, remove the restore. This can
9887 // happen when variable allocas are DCE'd.
9888 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9889 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9890 BasicBlock::iterator BI = SS;
9891 if (&*++BI == II)
9892 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009893 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009894 }
9895
9896 // Scan down this block to see if there is another stack restore in the
9897 // same block without an intervening call/alloca.
9898 BasicBlock::iterator BI = II;
9899 TerminatorInst *TI = II->getParent()->getTerminator();
9900 bool CannotRemove = false;
9901 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009902 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009903 CannotRemove = true;
9904 break;
9905 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009906 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9907 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9908 // If there is a stackrestore below this one, remove this one.
9909 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9910 return EraseInstFromFunction(CI);
9911 // Otherwise, ignore the intrinsic.
9912 } else {
9913 // If we found a non-intrinsic call, we can't remove the stack
9914 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009915 CannotRemove = true;
9916 break;
9917 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009918 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009919 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009920
9921 // If the stack restore is in a return/unwind block and if there are no
9922 // allocas or calls between the restore and the return, nuke the restore.
9923 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9924 return EraseInstFromFunction(CI);
9925 break;
9926 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009927 }
9928
Chris Lattner8b0ea312006-01-13 20:11:04 +00009929 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009930}
9931
9932// InvokeInst simplification
9933//
9934Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009935 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009936}
9937
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009938/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9939/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009940static bool isSafeToEliminateVarargsCast(const CallSite CS,
9941 const CastInst * const CI,
9942 const TargetData * const TD,
9943 const int ix) {
9944 if (!CI->isLosslessCast())
9945 return false;
9946
9947 // The size of ByVal arguments is derived from the type, so we
9948 // can't change to a type with a different size. If the size were
9949 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009950 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009951 return true;
9952
9953 const Type* SrcTy =
9954 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9955 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9956 if (!SrcTy->isSized() || !DstTy->isSized())
9957 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009958 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009959 return false;
9960 return true;
9961}
9962
Chris Lattnera44d8a22003-10-07 22:32:43 +00009963// visitCallSite - Improvements for call and invoke instructions.
9964//
9965Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009966 bool Changed = false;
9967
9968 // If the callee is a constexpr cast of a function, attempt to move the cast
9969 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009970 if (transformConstExprCastCall(CS)) return 0;
9971
Chris Lattner6c266db2003-10-07 22:54:13 +00009972 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009973
Chris Lattner08b22ec2005-05-13 07:09:09 +00009974 if (Function *CalleeF = dyn_cast<Function>(Callee))
9975 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9976 Instruction *OldCall = CS.getInstruction();
9977 // If the call and callee calling conventions don't match, this call must
9978 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009979 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009980 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +00009981 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00009982 // If OldCall dues not return void then replaceAllUsesWith undef.
9983 // This allows ValueHandlers and custom metadata to adjust itself.
9984 if (OldCall->getType() != Type::getVoidTy(*Context))
9985 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009986 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9987 return EraseInstFromFunction(*OldCall);
9988 return 0;
9989 }
9990
Chris Lattner17be6352004-10-18 02:59:09 +00009991 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9992 // This instruction is not reachable, just remove it. We insert a store to
9993 // undef so that we know that this code is not reachable, despite the fact
9994 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009995 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009996 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +00009997 CS.getInstruction());
9998
Devang Patel228ebd02009-10-13 22:56:32 +00009999 // If CS dues not return void then replaceAllUsesWith undef.
10000 // This allows ValueHandlers and custom metadata to adjust itself.
10001 if (CS.getInstruction()->getType() != Type::getVoidTy(*Context))
10002 CS.getInstruction()->
10003 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010004
10005 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10006 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010007 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010008 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010009 }
Chris Lattner17be6352004-10-18 02:59:09 +000010010 return EraseInstFromFunction(*CS.getInstruction());
10011 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010012
Duncan Sandscdb6d922007-09-17 10:26:40 +000010013 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10014 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10015 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10016 return transformCallThroughTrampoline(CS);
10017
Chris Lattner6c266db2003-10-07 22:54:13 +000010018 const PointerType *PTy = cast<PointerType>(Callee->getType());
10019 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10020 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010021 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010022 // See if we can optimize any arguments passed through the varargs area of
10023 // the call.
10024 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010025 E = CS.arg_end(); I != E; ++I, ++ix) {
10026 CastInst *CI = dyn_cast<CastInst>(*I);
10027 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10028 *I = CI->getOperand(0);
10029 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010030 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010031 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010032 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010033
Duncan Sandsf0c33542007-12-19 21:13:37 +000010034 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010035 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010036 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010037 Changed = true;
10038 }
10039
Chris Lattner6c266db2003-10-07 22:54:13 +000010040 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010041}
10042
Chris Lattner9fe38862003-06-19 17:00:31 +000010043// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10044// attempt to move the cast to the arguments of the call/invoke.
10045//
10046bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10047 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10048 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010049 if (CE->getOpcode() != Instruction::BitCast ||
10050 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010051 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010052 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010053 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010054 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010055
10056 // Okay, this is a cast from a function to a different type. Unless doing so
10057 // would cause a type conversion of one of our arguments, change this call to
10058 // be a direct call with arguments casted to the appropriate types.
10059 //
10060 const FunctionType *FT = Callee->getFunctionType();
10061 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010062 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010063
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010064 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010065 return false; // TODO: Handle multiple return values.
10066
Chris Lattnerf78616b2004-01-14 06:06:08 +000010067 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010068 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010069 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010070 // Conversion is ok if changing from one pointer type to another or from
10071 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010072 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010073 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010074 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010075 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010076 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010077
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010078 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010079 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010080 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010081 return false; // Cannot transform this return value.
10082
Chris Lattner58d74912008-03-12 17:45:29 +000010083 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010084 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010085 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010086 return false; // Attribute not compatible with transformed value.
10087 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010088
Chris Lattnerf78616b2004-01-14 06:06:08 +000010089 // If the callsite is an invoke instruction, and the return value is used by
10090 // a PHI node in a successor, we cannot change the return type of the call
10091 // because there is no place to put the cast instruction (without breaking
10092 // the critical edge). Bail out in this case.
10093 if (!Caller->use_empty())
10094 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10095 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10096 UI != E; ++UI)
10097 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10098 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010099 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010100 return false;
10101 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010102
10103 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10104 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010105
Chris Lattner9fe38862003-06-19 17:00:31 +000010106 CallSite::arg_iterator AI = CS.arg_begin();
10107 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10108 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010109 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010110
10111 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010112 return false; // Cannot transform this parameter value.
10113
Devang Patel19c87462008-09-26 22:53:05 +000010114 if (CallerPAL.getParamAttributes(i + 1)
10115 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010116 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010117
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010118 // Converting from one pointer type to another or between a pointer and an
10119 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010120 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010121 (TD && ((isa<PointerType>(ParamTy) ||
10122 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10123 (isa<PointerType>(ActTy) ||
10124 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010125 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010126 }
10127
10128 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010129 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010130 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010131
Chris Lattner58d74912008-03-12 17:45:29 +000010132 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10133 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010134 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010135 // won't be dropping them. Check that these extra arguments have attributes
10136 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010137 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10138 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010139 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010140 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010141 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010142 return false;
10143 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010144
Chris Lattner9fe38862003-06-19 17:00:31 +000010145 // Okay, we decided that this is a safe thing to do: go ahead and start
10146 // inserting cast instructions as necessary...
10147 std::vector<Value*> Args;
10148 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010149 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010150 attrVec.reserve(NumCommonArgs);
10151
10152 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010153 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010154
10155 // If the return value is not being used, the type may not be compatible
10156 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010157 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010158
10159 // Add the new return attributes.
10160 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010161 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010162
10163 AI = CS.arg_begin();
10164 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10165 const Type *ParamTy = FT->getParamType(i);
10166 if ((*AI)->getType() == ParamTy) {
10167 Args.push_back(*AI);
10168 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010169 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010170 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010171 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010172 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010173
10174 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010175 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010176 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010177 }
10178
10179 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010180 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010181 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010182 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010183
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010184 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010185 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010186 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010187 errs() << "WARNING: While resolving call to function '"
10188 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010189 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010190 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010191 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10192 const Type *PTy = getPromotedType((*AI)->getType());
10193 if (PTy != (*AI)->getType()) {
10194 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010195 Instruction::CastOps opcode =
10196 CastInst::getCastOpcode(*AI, false, PTy, false);
10197 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010198 } else {
10199 Args.push_back(*AI);
10200 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010201
Duncan Sandse1e520f2008-01-13 08:02:44 +000010202 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010203 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010204 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010205 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010206 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010207 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010208
Devang Patel19c87462008-09-26 22:53:05 +000010209 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10210 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10211
Owen Anderson1d0be152009-08-13 21:58:54 +000010212 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010213 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010214
Eric Christophera66297a2009-07-25 02:45:27 +000010215 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10216 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010217
Chris Lattner9fe38862003-06-19 17:00:31 +000010218 Instruction *NC;
10219 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010220 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010221 Args.begin(), Args.end(),
10222 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010223 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010224 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010225 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010226 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10227 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010228 CallInst *CI = cast<CallInst>(Caller);
10229 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010230 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010231 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010232 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010233 }
10234
Chris Lattner6934a042007-02-11 01:23:03 +000010235 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010236 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010237 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010238 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010239 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010240 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010241 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010242
10243 // If this is an invoke instruction, we should insert it after the first
10244 // non-phi, instruction in the normal successor block.
10245 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010246 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010247 InsertNewInstBefore(NC, *I);
10248 } else {
10249 // Otherwise, it's a call, just insert cast right after the call instr
10250 InsertNewInstBefore(NC, *Caller);
10251 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010252 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010253 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010254 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010255 }
10256 }
10257
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010258
Chris Lattner931f8f32009-08-31 05:17:58 +000010259 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010260 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010261
10262 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010263 return true;
10264}
10265
Duncan Sandscdb6d922007-09-17 10:26:40 +000010266// transformCallThroughTrampoline - Turn a call to a function created by the
10267// init_trampoline intrinsic into a direct call to the underlying function.
10268//
10269Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10270 Value *Callee = CS.getCalledValue();
10271 const PointerType *PTy = cast<PointerType>(Callee->getType());
10272 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010273 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010274
10275 // If the call already has the 'nest' attribute somewhere then give up -
10276 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010277 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010278 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010279
10280 IntrinsicInst *Tramp =
10281 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10282
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010283 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010284 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10285 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10286
Devang Patel05988662008-09-25 21:00:45 +000010287 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010288 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010289 unsigned NestIdx = 1;
10290 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010291 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010292
10293 // Look for a parameter marked with the 'nest' attribute.
10294 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10295 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010296 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010297 // Record the parameter type and any other attributes.
10298 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010299 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010300 break;
10301 }
10302
10303 if (NestTy) {
10304 Instruction *Caller = CS.getInstruction();
10305 std::vector<Value*> NewArgs;
10306 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10307
Devang Patel05988662008-09-25 21:00:45 +000010308 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010309 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010310
Duncan Sandscdb6d922007-09-17 10:26:40 +000010311 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010312 // mean appending it. Likewise for attributes.
10313
Devang Patel19c87462008-09-26 22:53:05 +000010314 // Add any result attributes.
10315 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010316 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010317
Duncan Sandscdb6d922007-09-17 10:26:40 +000010318 {
10319 unsigned Idx = 1;
10320 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10321 do {
10322 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010323 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010324 Value *NestVal = Tramp->getOperand(3);
10325 if (NestVal->getType() != NestTy)
10326 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10327 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010328 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010329 }
10330
10331 if (I == E)
10332 break;
10333
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010334 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010335 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010336 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010337 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010338 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010339
10340 ++Idx, ++I;
10341 } while (1);
10342 }
10343
Devang Patel19c87462008-09-26 22:53:05 +000010344 // Add any function attributes.
10345 if (Attributes Attr = Attrs.getFnAttributes())
10346 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10347
Duncan Sandscdb6d922007-09-17 10:26:40 +000010348 // The trampoline may have been bitcast to a bogus type (FTy).
10349 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010350 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010351
Duncan Sandscdb6d922007-09-17 10:26:40 +000010352 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353 NewTypes.reserve(FTy->getNumParams()+1);
10354
Duncan Sandscdb6d922007-09-17 10:26:40 +000010355 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010356 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010357 {
10358 unsigned Idx = 1;
10359 FunctionType::param_iterator I = FTy->param_begin(),
10360 E = FTy->param_end();
10361
10362 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010363 if (Idx == NestIdx)
10364 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010365 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366
10367 if (I == E)
10368 break;
10369
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010370 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010371 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010372
10373 ++Idx, ++I;
10374 } while (1);
10375 }
10376
10377 // Replace the trampoline call with a direct call. Let the generic
10378 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010379 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010380 FTy->isVarArg());
10381 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010382 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010383 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010384 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010385 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10386 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387
10388 Instruction *NewCaller;
10389 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010390 NewCaller = InvokeInst::Create(NewCallee,
10391 II->getNormalDest(), II->getUnwindDest(),
10392 NewArgs.begin(), NewArgs.end(),
10393 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010394 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010395 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010397 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10398 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399 if (cast<CallInst>(Caller)->isTailCall())
10400 cast<CallInst>(NewCaller)->setTailCall();
10401 cast<CallInst>(NewCaller)->
10402 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010403 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404 }
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010405 if (Caller->getType() != Type::getVoidTy(*Context))
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406 Caller->replaceAllUsesWith(NewCaller);
10407 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010408 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409 return 0;
10410 }
10411 }
10412
10413 // Replace the trampoline call with a direct call. Since there is no 'nest'
10414 // parameter, there is no need to adjust the argument list. Let the generic
10415 // code sort out any function type mismatches.
10416 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010417 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010418 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010419 CS.setCalledFunction(NewCallee);
10420 return CS.getInstruction();
10421}
10422
Dan Gohman9ad29202009-09-16 16:50:24 +000010423/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10424/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010425/// and a single binop.
10426Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10427 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010428 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010429 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010430 Value *LHSVal = FirstInst->getOperand(0);
10431 Value *RHSVal = FirstInst->getOperand(1);
10432
10433 const Type *LHSType = LHSVal->getType();
10434 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010435
Dan Gohman9ad29202009-09-16 16:50:24 +000010436 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010437 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010438 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010439 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010440 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010441 // types or GEP's with different index types.
10442 I->getOperand(0)->getType() != LHSType ||
10443 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010444 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010445
10446 // If they are CmpInst instructions, check their predicates
10447 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10448 if (cast<CmpInst>(I)->getPredicate() !=
10449 cast<CmpInst>(FirstInst)->getPredicate())
10450 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010451
10452 // Keep track of which operand needs a phi node.
10453 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10454 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010455 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010456
10457 // If both LHS and RHS would need a PHI, don't do this transformation,
10458 // because it would increase the number of PHIs entering the block,
10459 // which leads to higher register pressure. This is especially
10460 // bad when the PHIs are in the header of a loop.
10461 if (!LHSVal && !RHSVal)
10462 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010463
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010464 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010465
Chris Lattner7da52b22006-11-01 04:51:18 +000010466 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010467 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010468 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010469 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010470 NewLHS = PHINode::Create(LHSType,
10471 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010472 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10473 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010474 InsertNewInstBefore(NewLHS, PN);
10475 LHSVal = NewLHS;
10476 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010477
10478 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010479 NewRHS = PHINode::Create(RHSType,
10480 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010481 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10482 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010483 InsertNewInstBefore(NewRHS, PN);
10484 RHSVal = NewRHS;
10485 }
10486
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010487 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010488 if (NewLHS || NewRHS) {
10489 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10490 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10491 if (NewLHS) {
10492 Value *NewInLHS = InInst->getOperand(0);
10493 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10494 }
10495 if (NewRHS) {
10496 Value *NewInRHS = InInst->getOperand(1);
10497 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10498 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010499 }
10500 }
10501
Chris Lattner7da52b22006-11-01 04:51:18 +000010502 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010503 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010504 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010505 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010506 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010507}
10508
Chris Lattner05f18922008-12-01 02:34:36 +000010509Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10510 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10511
10512 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10513 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010514 // This is true if all GEP bases are allocas and if all indices into them are
10515 // constants.
10516 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010517
10518 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010519 // more than one phi, which leads to higher register pressure. This is
10520 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010521 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010522
Dan Gohman9ad29202009-09-16 16:50:24 +000010523 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010524 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10525 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10526 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10527 GEP->getNumOperands() != FirstInst->getNumOperands())
10528 return 0;
10529
Chris Lattner36d3e322009-02-21 00:46:50 +000010530 // Keep track of whether or not all GEPs are of alloca pointers.
10531 if (AllBasePointersAreAllocas &&
10532 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10533 !GEP->hasAllConstantIndices()))
10534 AllBasePointersAreAllocas = false;
10535
Chris Lattner05f18922008-12-01 02:34:36 +000010536 // Compare the operand lists.
10537 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10538 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10539 continue;
10540
10541 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10542 // if one of the PHIs has a constant for the index. The index may be
10543 // substantially cheaper to compute for the constants, so making it a
10544 // variable index could pessimize the path. This also handles the case
10545 // for struct indices, which must always be constant.
10546 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10547 isa<ConstantInt>(GEP->getOperand(op)))
10548 return 0;
10549
10550 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10551 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010552
10553 // If we already needed a PHI for an earlier operand, and another operand
10554 // also requires a PHI, we'd be introducing more PHIs than we're
10555 // eliminating, which increases register pressure on entry to the PHI's
10556 // block.
10557 if (NeededPhi)
10558 return 0;
10559
Chris Lattner05f18922008-12-01 02:34:36 +000010560 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010561 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010562 }
10563 }
10564
Chris Lattner36d3e322009-02-21 00:46:50 +000010565 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010566 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010567 // offset calculation, but all the predecessors will have to materialize the
10568 // stack address into a register anyway. We'd actually rather *clone* the
10569 // load up into the predecessors so that we have a load of a gep of an alloca,
10570 // which can usually all be folded into the load.
10571 if (AllBasePointersAreAllocas)
10572 return 0;
10573
Chris Lattner05f18922008-12-01 02:34:36 +000010574 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10575 // that is variable.
10576 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10577
10578 bool HasAnyPHIs = false;
10579 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10580 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10581 Value *FirstOp = FirstInst->getOperand(i);
10582 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10583 FirstOp->getName()+".pn");
10584 InsertNewInstBefore(NewPN, PN);
10585
10586 NewPN->reserveOperandSpace(e);
10587 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10588 OperandPhis[i] = NewPN;
10589 FixedOperands[i] = NewPN;
10590 HasAnyPHIs = true;
10591 }
10592
10593
10594 // Add all operands to the new PHIs.
10595 if (HasAnyPHIs) {
10596 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10597 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10598 BasicBlock *InBB = PN.getIncomingBlock(i);
10599
10600 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10601 if (PHINode *OpPhi = OperandPhis[op])
10602 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10603 }
10604 }
10605
10606 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010607 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10608 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10609 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010610 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10611 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010612}
10613
10614
Chris Lattner21550882009-02-23 05:56:17 +000010615/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10616/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010617/// obvious the value of the load is not changed from the point of the load to
10618/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010619///
10620/// Finally, it is safe, but not profitable, to sink a load targetting a
10621/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10622/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010623static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010624 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10625
10626 for (++BBI; BBI != E; ++BBI)
10627 if (BBI->mayWriteToMemory())
10628 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010629
10630 // Check for non-address taken alloca. If not address-taken already, it isn't
10631 // profitable to do this xform.
10632 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10633 bool isAddressTaken = false;
10634 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10635 UI != E; ++UI) {
10636 if (isa<LoadInst>(UI)) continue;
10637 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10638 // If storing TO the alloca, then the address isn't taken.
10639 if (SI->getOperand(1) == AI) continue;
10640 }
10641 isAddressTaken = true;
10642 break;
10643 }
10644
Chris Lattner36d3e322009-02-21 00:46:50 +000010645 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010646 return false;
10647 }
10648
Chris Lattner36d3e322009-02-21 00:46:50 +000010649 // If this load is a load from a GEP with a constant offset from an alloca,
10650 // then we don't want to sink it. In its present form, it will be
10651 // load [constant stack offset]. Sinking it will cause us to have to
10652 // materialize the stack addresses in each predecessor in a register only to
10653 // do a shared load from register in the successor.
10654 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10655 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10656 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10657 return false;
10658
Chris Lattner76c73142006-11-01 07:13:54 +000010659 return true;
10660}
10661
Chris Lattner9fe38862003-06-19 17:00:31 +000010662
Chris Lattnerbac32862004-11-14 19:13:23 +000010663// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10664// operator and they all are only used by the PHI, PHI together their
10665// inputs, and do the operation once, to the result of the PHI.
10666Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10667 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10668
10669 // Scan the instruction, looking for input operations that can be folded away.
10670 // If all input operands to the phi are the same instruction (e.g. a cast from
10671 // the same type or "+42") we can pull the operation through the PHI, reducing
10672 // code size and simplifying code.
10673 Constant *ConstantOp = 0;
10674 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010675 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010676 if (isa<CastInst>(FirstInst)) {
10677 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010678 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010679 // Can fold binop, compare or shift here if the RHS is a constant,
10680 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010681 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010682 if (ConstantOp == 0)
10683 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010684 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10685 isVolatile = LI->isVolatile();
10686 // We can't sink the load if the loaded value could be modified between the
10687 // load and the PHI.
10688 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010689 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010690 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010691
10692 // If the PHI is of volatile loads and the load block has multiple
10693 // successors, sinking it would remove a load of the volatile value from
10694 // the path through the other successor.
10695 if (isVolatile &&
10696 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10697 return 0;
10698
Chris Lattner9c080502006-11-01 07:43:41 +000010699 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010700 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010701 } else {
10702 return 0; // Cannot fold this operation.
10703 }
10704
10705 // Check to see if all arguments are the same operation.
10706 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10707 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10708 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010709 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010710 return 0;
10711 if (CastSrcTy) {
10712 if (I->getOperand(0)->getType() != CastSrcTy)
10713 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010714 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010715 // We can't sink the load if the loaded value could be modified between
10716 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010717 if (LI->isVolatile() != isVolatile ||
10718 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010719 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010720 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010721
Chris Lattner71042962008-07-08 17:18:32 +000010722 // If the PHI is of volatile loads and the load block has multiple
10723 // successors, sinking it would remove a load of the volatile value from
10724 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010725 if (isVolatile &&
10726 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10727 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010728
Chris Lattnerbac32862004-11-14 19:13:23 +000010729 } else if (I->getOperand(1) != ConstantOp) {
10730 return 0;
10731 }
10732 }
10733
10734 // Okay, they are all the same operation. Create a new PHI node of the
10735 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010736 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10737 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010738 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010739
10740 Value *InVal = FirstInst->getOperand(0);
10741 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010742
10743 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010744 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10745 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10746 if (NewInVal != InVal)
10747 InVal = 0;
10748 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10749 }
10750
10751 Value *PhiVal;
10752 if (InVal) {
10753 // The new PHI unions all of the same values together. This is really
10754 // common, so we handle it intelligently here for compile-time speed.
10755 PhiVal = InVal;
10756 delete NewPN;
10757 } else {
10758 InsertNewInstBefore(NewPN, PN);
10759 PhiVal = NewPN;
10760 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010761
Chris Lattnerbac32862004-11-14 19:13:23 +000010762 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010763 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010764 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010765 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010766 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010767 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010768 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010769 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010770 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10771
10772 // If this was a volatile load that we are merging, make sure to loop through
10773 // and mark all the input loads as non-volatile. If we don't do this, we will
10774 // insert a new volatile load and the old ones will not be deletable.
10775 if (isVolatile)
10776 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10777 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10778
10779 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010780}
Chris Lattnera1be5662002-05-02 17:06:02 +000010781
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010782/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10783/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010784static bool DeadPHICycle(PHINode *PN,
10785 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010786 if (PN->use_empty()) return true;
10787 if (!PN->hasOneUse()) return false;
10788
10789 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010790 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010791 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010792
10793 // Don't scan crazily complex things.
10794 if (PotentiallyDeadPHIs.size() == 16)
10795 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010796
10797 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10798 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010799
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010800 return false;
10801}
10802
Chris Lattnercf5008a2007-11-06 21:52:06 +000010803/// PHIsEqualValue - Return true if this phi node is always equal to
10804/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10805/// z = some value; x = phi (y, z); y = phi (x, z)
10806static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10807 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10808 // See if we already saw this PHI node.
10809 if (!ValueEqualPHIs.insert(PN))
10810 return true;
10811
10812 // Don't scan crazily complex things.
10813 if (ValueEqualPHIs.size() == 16)
10814 return false;
10815
10816 // Scan the operands to see if they are either phi nodes or are equal to
10817 // the value.
10818 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10819 Value *Op = PN->getIncomingValue(i);
10820 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10821 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10822 return false;
10823 } else if (Op != NonPhiInVal)
10824 return false;
10825 }
10826
10827 return true;
10828}
10829
10830
Chris Lattner473945d2002-05-06 18:06:38 +000010831// PHINode simplification
10832//
Chris Lattner7e708292002-06-25 16:13:24 +000010833Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010834 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010835 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010836
Owen Anderson7e057142006-07-10 22:03:18 +000010837 if (Value *V = PN.hasConstantValue())
10838 return ReplaceInstUsesWith(PN, V);
10839
Owen Anderson7e057142006-07-10 22:03:18 +000010840 // If all PHI operands are the same operation, pull them through the PHI,
10841 // reducing code size.
10842 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010843 isa<Instruction>(PN.getIncomingValue(1)) &&
10844 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10845 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10846 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10847 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010848 PN.getIncomingValue(0)->hasOneUse())
10849 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10850 return Result;
10851
10852 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10853 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10854 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010855 if (PN.hasOneUse()) {
10856 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10857 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010858 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010859 PotentiallyDeadPHIs.insert(&PN);
10860 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010861 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010862 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010863
10864 // If this phi has a single use, and if that use just computes a value for
10865 // the next iteration of a loop, delete the phi. This occurs with unused
10866 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10867 // common case here is good because the only other things that catch this
10868 // are induction variable analysis (sometimes) and ADCE, which is only run
10869 // late.
10870 if (PHIUser->hasOneUse() &&
10871 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10872 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010873 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010874 }
10875 }
Owen Anderson7e057142006-07-10 22:03:18 +000010876
Chris Lattnercf5008a2007-11-06 21:52:06 +000010877 // We sometimes end up with phi cycles that non-obviously end up being the
10878 // same value, for example:
10879 // z = some value; x = phi (y, z); y = phi (x, z)
10880 // where the phi nodes don't necessarily need to be in the same block. Do a
10881 // quick check to see if the PHI node only contains a single non-phi value, if
10882 // so, scan to see if the phi cycle is actually equal to that value.
10883 {
10884 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10885 // Scan for the first non-phi operand.
10886 while (InValNo != NumOperandVals &&
10887 isa<PHINode>(PN.getIncomingValue(InValNo)))
10888 ++InValNo;
10889
10890 if (InValNo != NumOperandVals) {
10891 Value *NonPhiInVal = PN.getOperand(InValNo);
10892
10893 // Scan the rest of the operands to see if there are any conflicts, if so
10894 // there is no need to recursively scan other phis.
10895 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10896 Value *OpVal = PN.getIncomingValue(InValNo);
10897 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10898 break;
10899 }
10900
10901 // If we scanned over all operands, then we have one unique value plus
10902 // phi values. Scan PHI nodes to see if they all merge in each other or
10903 // the value.
10904 if (InValNo == NumOperandVals) {
10905 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10906 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10907 return ReplaceInstUsesWith(PN, NonPhiInVal);
10908 }
10909 }
10910 }
Chris Lattner60921c92003-12-19 05:58:40 +000010911 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010912}
10913
Chris Lattner7e708292002-06-25 16:13:24 +000010914Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010915 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010916 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010917 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010918 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010919
Chris Lattnere87597f2004-10-16 18:11:37 +000010920 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010921 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010922
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010923 bool HasZeroPointerIndex = false;
10924 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10925 HasZeroPointerIndex = C->isNullValue();
10926
10927 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010928 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010929
Chris Lattner28977af2004-04-05 01:30:19 +000010930 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010931 if (TD) {
10932 bool MadeChange = false;
10933 unsigned PtrSize = TD->getPointerSizeInBits();
10934
10935 gep_type_iterator GTI = gep_type_begin(GEP);
10936 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10937 I != E; ++I, ++GTI) {
10938 if (!isa<SequentialType>(*GTI)) continue;
10939
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010940 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010941 // to what we need. If narrower, sign-extend it to what we need. This
10942 // explicit cast can make subsequent optimizations more obvious.
10943 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010944 if (OpBits == PtrSize)
10945 continue;
10946
Chris Lattner2345d1d2009-08-30 20:01:10 +000010947 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010948 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010949 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010950 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010951 }
Chris Lattner28977af2004-04-05 01:30:19 +000010952
Chris Lattner90ac28c2002-08-02 19:29:35 +000010953 // Combine Indices - If the source pointer to this getelementptr instruction
10954 // is a getelementptr instruction, combine the indices of the two
10955 // getelementptr instructions into a single instruction.
10956 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010957 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010958 // Note that if our source is a gep chain itself that we wait for that
10959 // chain to be resolved before we perform this transformation. This
10960 // avoids us creating a TON of code in some cases.
10961 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010962 if (GetElementPtrInst *SrcGEP =
10963 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10964 if (SrcGEP->getNumOperands() == 2)
10965 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010966
Chris Lattner72588fc2007-02-15 22:48:32 +000010967 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010968
10969 // Find out whether the last index in the source GEP is a sequential idx.
10970 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010971 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10972 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010973 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010974
Chris Lattner90ac28c2002-08-02 19:29:35 +000010975 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010976 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010977 // Replace: gep (gep %P, long B), long A, ...
10978 // With: T = long A+B; gep %P, T, ...
10979 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010980 Value *Sum;
10981 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10982 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010983 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010984 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010985 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010986 Sum = SO1;
10987 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010988 // If they aren't the same type, then the input hasn't been processed
10989 // by the loop above yet (which canonicalizes sequential index types to
10990 // intptr_t). Just avoid transforming this until the input has been
10991 // normalized.
10992 if (SO1->getType() != GO1->getType())
10993 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010994 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010995 }
Chris Lattner620ce142004-05-07 22:09:22 +000010996
Chris Lattnerab984842009-08-30 05:30:55 +000010997 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010998 if (Src->getNumOperands() == 2) {
10999 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011000 GEP.setOperand(1, Sum);
11001 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011002 }
Chris Lattnerab984842009-08-30 05:30:55 +000011003 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011004 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011005 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011006 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011007 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011008 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011009 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011010 Indices.append(Src->op_begin()+1, Src->op_end());
11011 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011012 }
11013
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011014 if (!Indices.empty())
11015 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11016 Src->isInBounds()) ?
11017 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11018 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011019 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011020 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011021 }
11022
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011023 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11024 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011025 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011026
Chris Lattner2de23192009-08-30 20:38:21 +000011027 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11028 // want to change the gep until the bitcasts are eliminated.
11029 if (getBitCastOperand(X)) {
11030 Worklist.AddValue(PtrOp);
11031 return 0;
11032 }
11033
Chris Lattner963f4ba2009-08-30 20:36:46 +000011034 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11035 // into : GEP [10 x i8]* X, i32 0, ...
11036 //
11037 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11038 // into : GEP i8* X, ...
11039 //
11040 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011041 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011042 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11043 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011044 if (const ArrayType *CATy =
11045 dyn_cast<ArrayType>(CPTy->getElementType())) {
11046 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11047 if (CATy->getElementType() == XTy->getElementType()) {
11048 // -> GEP i8* X, ...
11049 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011050 return cast<GEPOperator>(&GEP)->isInBounds() ?
11051 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11052 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011053 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11054 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011055 }
11056
11057 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011058 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011059 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011060 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011061 // At this point, we know that the cast source type is a pointer
11062 // to an array of the same type as the destination pointer
11063 // array. Because the array type is never stepped over (there
11064 // is a leading zero) we can fold the cast into this GEP.
11065 GEP.setOperand(0, X);
11066 return &GEP;
11067 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011068 }
11069 }
Chris Lattnereed48272005-09-13 00:40:14 +000011070 } else if (GEP.getNumOperands() == 2) {
11071 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011072 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11073 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011074 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11075 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011076 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011077 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11078 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011079 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011080 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011081 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011082 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11083 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011084 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011085 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011086 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011087 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011088
11089 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011090 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011091 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011092 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011093
Owen Anderson1d0be152009-08-13 21:58:54 +000011094 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011095 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011096 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011097
11098 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11099 // allow either a mul, shift, or constant here.
11100 Value *NewIdx = 0;
11101 ConstantInt *Scale = 0;
11102 if (ArrayEltSize == 1) {
11103 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011104 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011105 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011106 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011107 Scale = CI;
11108 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11109 if (Inst->getOpcode() == Instruction::Shl &&
11110 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011111 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11112 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011113 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011114 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011115 NewIdx = Inst->getOperand(0);
11116 } else if (Inst->getOpcode() == Instruction::Mul &&
11117 isa<ConstantInt>(Inst->getOperand(1))) {
11118 Scale = cast<ConstantInt>(Inst->getOperand(1));
11119 NewIdx = Inst->getOperand(0);
11120 }
11121 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011122
Chris Lattner7835cdd2005-09-13 18:36:04 +000011123 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011124 // out, perform the transformation. Note, we don't know whether Scale is
11125 // signed or not. We'll use unsigned version of division/modulo
11126 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011127 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011128 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011129 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011130 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011131 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011132 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11133 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011134 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011135 }
11136
11137 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011138 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011139 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011140 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011141 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11142 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11143 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011144 // The NewGEP must be pointer typed, so must the old one -> BitCast
11145 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011146 }
11147 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011148 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011149 }
Chris Lattner58407792009-01-09 04:53:57 +000011150
Chris Lattner46cd5a12009-01-09 05:44:56 +000011151 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011152 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011153 /// Y = gep X, <...constant indices...>
11154 /// into a gep of the original struct. This is important for SROA and alias
11155 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011156 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011157 if (TD &&
11158 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011159 // Determine how much the GEP moves the pointer. We are guaranteed to get
11160 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011161 ConstantInt *OffsetV =
11162 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011163 int64_t Offset = OffsetV->getSExtValue();
11164
11165 // If this GEP instruction doesn't move the pointer, just replace the GEP
11166 // with a bitcast of the real input to the dest type.
11167 if (Offset == 0) {
11168 // If the bitcast is of an allocation, and the allocation will be
11169 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011170 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11171 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011172 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11173 if (Instruction *I = visitBitCast(*BCI)) {
11174 if (I != BCI) {
11175 I->takeName(BCI);
11176 BCI->getParent()->getInstList().insert(BCI, I);
11177 ReplaceInstUsesWith(*BCI, I);
11178 }
11179 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011180 }
Chris Lattner58407792009-01-09 04:53:57 +000011181 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011182 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011183 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011184
11185 // Otherwise, if the offset is non-zero, we need to find out if there is a
11186 // field at Offset in 'A's type. If so, we can pull the cast through the
11187 // GEP.
11188 SmallVector<Value*, 8> NewIndices;
11189 const Type *InTy =
11190 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011191 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011192 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11193 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11194 NewIndices.end()) :
11195 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11196 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011197
11198 if (NGEP->getType() == GEP.getType())
11199 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011200 NGEP->takeName(&GEP);
11201 return new BitCastInst(NGEP, GEP.getType());
11202 }
Chris Lattner58407792009-01-09 04:53:57 +000011203 }
11204 }
11205
Chris Lattner8a2a3112001-12-14 16:52:21 +000011206 return 0;
11207}
11208
Chris Lattner0864acf2002-11-04 16:18:53 +000011209Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11210 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011211 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011212 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11213 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011214 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011215 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011216
11217 // Create and insert the replacement instruction...
11218 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011219 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011220 else {
11221 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011222 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011223 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011224 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011225
Chris Lattner0864acf2002-11-04 16:18:53 +000011226 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011227 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011228 //
11229 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011230 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011231
11232 // Now that I is pointing to the first non-allocation-inst in the block,
11233 // insert our getelementptr instruction...
11234 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011235 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011236 Value *Idx[2];
11237 Idx[0] = NullIdx;
11238 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011239 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11240 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011241
11242 // Now make everything use the getelementptr instead of the original
11243 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011244 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011245 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011246 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011247 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011248 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011249
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011250 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011251 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011252 // Note that we only do this for alloca's, because malloc should allocate
11253 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011254 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011255 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011256
11257 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11258 if (AI.getAlignment() == 0)
11259 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11260 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011261
Chris Lattner0864acf2002-11-04 16:18:53 +000011262 return 0;
11263}
11264
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011265Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11266 Value *Op = FI.getOperand(0);
11267
Chris Lattner17be6352004-10-18 02:59:09 +000011268 // free undef -> unreachable.
11269 if (isa<UndefValue>(Op)) {
11270 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011271 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000011272 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011273 return EraseInstFromFunction(FI);
11274 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011275
Chris Lattner6160e852004-02-28 04:57:37 +000011276 // If we have 'free null' delete the instruction. This can happen in stl code
11277 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011278 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011279 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011280
11281 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11282 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11283 FI.setOperand(0, CI->getOperand(0));
11284 return &FI;
11285 }
11286
11287 // Change free (gep X, 0,0,0,0) into free(X)
11288 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11289 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011290 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011291 FI.setOperand(0, GEPI->getOperand(0));
11292 return &FI;
11293 }
11294 }
11295
11296 // Change free(malloc) into nothing, if the malloc has a single use.
11297 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11298 if (MI->hasOneUse()) {
11299 EraseInstFromFunction(FI);
11300 return EraseInstFromFunction(*MI);
11301 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011302 if (isMalloc(Op)) {
11303 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11304 if (Op->hasOneUse() && CI->hasOneUse()) {
11305 EraseInstFromFunction(FI);
11306 EraseInstFromFunction(*CI);
11307 return EraseInstFromFunction(*cast<Instruction>(Op));
11308 }
11309 } else {
11310 // Op is a call to malloc
11311 if (Op->hasOneUse()) {
11312 EraseInstFromFunction(FI);
11313 return EraseInstFromFunction(*cast<Instruction>(Op));
11314 }
11315 }
11316 }
Chris Lattner6160e852004-02-28 04:57:37 +000011317
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011318 return 0;
11319}
11320
11321
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011322/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011323static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011324 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011325 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011326 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011327 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011328
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011329 if (TD) {
11330 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11331 // Instead of loading constant c string, use corresponding integer value
11332 // directly if string length is small enough.
11333 std::string Str;
11334 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11335 unsigned len = Str.length();
11336 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11337 unsigned numBits = Ty->getPrimitiveSizeInBits();
11338 // Replace LI with immediate integer store.
11339 if ((numBits >> 3) == len + 1) {
11340 APInt StrVal(numBits, 0);
11341 APInt SingleChar(numBits, 0);
11342 if (TD->isLittleEndian()) {
11343 for (signed i = len-1; i >= 0; i--) {
11344 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11345 StrVal = (StrVal << 8) | SingleChar;
11346 }
11347 } else {
11348 for (unsigned i = 0; i < len; i++) {
11349 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11350 StrVal = (StrVal << 8) | SingleChar;
11351 }
11352 // Append NULL at the end.
11353 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011354 StrVal = (StrVal << 8) | SingleChar;
11355 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011356 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011357 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011358 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011359 }
11360 }
11361 }
11362
Mon P Wang6753f952009-02-07 22:19:29 +000011363 const PointerType *DestTy = cast<PointerType>(CI->getType());
11364 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011365 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011366
11367 // If the address spaces don't match, don't eliminate the cast.
11368 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11369 return 0;
11370
Chris Lattnerb89e0712004-07-13 01:49:43 +000011371 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011372
Reid Spencer42230162007-01-22 05:51:25 +000011373 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011374 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011375 // If the source is an array, the code below will not succeed. Check to
11376 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11377 // constants.
11378 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11379 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11380 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011381 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011382 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011383 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011384 SrcTy = cast<PointerType>(CastOp->getType());
11385 SrcPTy = SrcTy->getElementType();
11386 }
11387
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011388 if (IC.getTargetData() &&
11389 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011390 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011391 // Do not allow turning this into a load of an integer, which is then
11392 // casted to a pointer, this pessimizes pointer analysis a lot.
11393 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011394 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11395 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011396
Chris Lattnerf9527852005-01-31 04:50:46 +000011397 // Okay, we are casting from one integer or pointer type to another of
11398 // the same size. Instead of casting the pointer before the load, cast
11399 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011400 Value *NewLoad =
11401 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011402 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011403 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011404 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011405 }
11406 }
11407 return 0;
11408}
11409
Chris Lattner833b8a42003-06-26 05:06:25 +000011410Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11411 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011412
Dan Gohman9941f742007-07-20 16:34:21 +000011413 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011414 if (TD) {
11415 unsigned KnownAlign =
11416 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11417 if (KnownAlign >
11418 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11419 LI.getAlignment()))
11420 LI.setAlignment(KnownAlign);
11421 }
Dan Gohman9941f742007-07-20 16:34:21 +000011422
Chris Lattner963f4ba2009-08-30 20:36:46 +000011423 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011424 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011425 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011426 return Res;
11427
11428 // None of the following transforms are legal for volatile loads.
11429 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011430
Dan Gohman2276a7b2008-10-15 23:19:35 +000011431 // Do really simple store-to-load forwarding and load CSE, to catch cases
11432 // where there are several consequtive memory accesses to the same location,
11433 // separated by a few arithmetic operations.
11434 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011435 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11436 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011437
Christopher Lambb15147e2007-12-29 07:56:53 +000011438 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11439 const Value *GEPI0 = GEPI->getOperand(0);
11440 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011441 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011442 // Insert a new store to null instruction before the load to indicate
11443 // that this code is not reachable. We do this instead of inserting
11444 // an unreachable instruction directly because we cannot modify the
11445 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011446 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011447 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011448 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011449 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011450 }
Chris Lattner37366c12005-05-01 04:24:53 +000011451
Chris Lattnere87597f2004-10-16 18:11:37 +000011452 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011453 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011454 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011455 if (isa<UndefValue>(C) ||
11456 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011457 // Insert a new store to null instruction before the load to indicate that
11458 // this code is not reachable. We do this instead of inserting an
11459 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011460 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011461 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011462 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011463 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011464
Chris Lattnere87597f2004-10-16 18:11:37 +000011465 // Instcombine load (constant global) into the value loaded.
11466 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011467 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011468 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011469
Chris Lattnere87597f2004-10-16 18:11:37 +000011470 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011471 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011472 if (CE->getOpcode() == Instruction::GetElementPtr) {
11473 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011474 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011475 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +000011476 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011477 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011478 if (CE->getOperand(0)->isNullValue()) {
11479 // Insert a new store to null instruction before the load to indicate
11480 // that this code is not reachable. We do this instead of inserting
11481 // an unreachable instruction directly because we cannot modify the
11482 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011483 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011484 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011485 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011486 }
11487
Reid Spencer3da59db2006-11-27 01:05:10 +000011488 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011489 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011490 return Res;
11491 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011492 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011493 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011494
11495 // If this load comes from anywhere in a constant global, and if the global
11496 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011497 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011498 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011499 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011500 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011501 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011502 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011503 }
11504 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011505
Chris Lattner37366c12005-05-01 04:24:53 +000011506 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011507 // Change select and PHI nodes to select values instead of addresses: this
11508 // helps alias analysis out a lot, allows many others simplifications, and
11509 // exposes redundancy in the code.
11510 //
11511 // Note that we cannot do the transformation unless we know that the
11512 // introduced loads cannot trap! Something like this is valid as long as
11513 // the condition is always false: load (select bool %C, int* null, int* %G),
11514 // but it would not be valid if we transformed it to load from null
11515 // unconditionally.
11516 //
11517 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11518 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011519 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11520 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011521 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11522 SI->getOperand(1)->getName()+".val");
11523 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11524 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011525 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011526 }
11527
Chris Lattner684fe212004-09-23 15:46:00 +000011528 // load (select (cond, null, P)) -> load P
11529 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11530 if (C->isNullValue()) {
11531 LI.setOperand(0, SI->getOperand(2));
11532 return &LI;
11533 }
11534
11535 // load (select (cond, P, null)) -> load P
11536 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11537 if (C->isNullValue()) {
11538 LI.setOperand(0, SI->getOperand(1));
11539 return &LI;
11540 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011541 }
11542 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011543 return 0;
11544}
11545
Reid Spencer55af2b52007-01-19 21:20:31 +000011546/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011547/// when possible. This makes it generally easy to do alias analysis and/or
11548/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011549static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11550 User *CI = cast<User>(SI.getOperand(1));
11551 Value *CastOp = CI->getOperand(0);
11552
11553 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011554 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11555 if (SrcTy == 0) return 0;
11556
11557 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011558
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011559 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11560 return 0;
11561
Chris Lattner3914f722009-01-24 01:00:13 +000011562 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11563 /// to its first element. This allows us to handle things like:
11564 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11565 /// on 32-bit hosts.
11566 SmallVector<Value*, 4> NewGEPIndices;
11567
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011568 // If the source is an array, the code below will not succeed. Check to
11569 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11570 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011571 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11572 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011573 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011574 NewGEPIndices.push_back(Zero);
11575
11576 while (1) {
11577 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011578 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011579 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011580 NewGEPIndices.push_back(Zero);
11581 SrcPTy = STy->getElementType(0);
11582 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11583 NewGEPIndices.push_back(Zero);
11584 SrcPTy = ATy->getElementType();
11585 } else {
11586 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011587 }
Chris Lattner3914f722009-01-24 01:00:13 +000011588 }
11589
Owen Andersondebcb012009-07-29 22:17:13 +000011590 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011591 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011592
11593 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11594 return 0;
11595
Chris Lattner71759c42009-01-16 20:12:52 +000011596 // If the pointers point into different address spaces or if they point to
11597 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011598 if (!IC.getTargetData() ||
11599 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011600 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011601 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11602 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011603 return 0;
11604
11605 // Okay, we are casting from one integer or pointer type to another of
11606 // the same size. Instead of casting the pointer before
11607 // the store, cast the value to be stored.
11608 Value *NewCast;
11609 Value *SIOp0 = SI.getOperand(0);
11610 Instruction::CastOps opcode = Instruction::BitCast;
11611 const Type* CastSrcTy = SIOp0->getType();
11612 const Type* CastDstTy = SrcPTy;
11613 if (isa<PointerType>(CastDstTy)) {
11614 if (CastSrcTy->isInteger())
11615 opcode = Instruction::IntToPtr;
11616 } else if (isa<IntegerType>(CastDstTy)) {
11617 if (isa<PointerType>(SIOp0->getType()))
11618 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011619 }
Chris Lattner3914f722009-01-24 01:00:13 +000011620
11621 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11622 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011623 if (!NewGEPIndices.empty())
11624 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11625 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011626
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011627 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11628 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011629 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011630}
11631
Chris Lattner4aebaee2008-11-27 08:56:30 +000011632/// equivalentAddressValues - Test if A and B will obviously have the same
11633/// value. This includes recognizing that %t0 and %t1 will have the same
11634/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011635/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011636/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011637/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011638/// %t2 = load i32* %t1
11639///
11640static bool equivalentAddressValues(Value *A, Value *B) {
11641 // Test if the values are trivially equivalent.
11642 if (A == B) return true;
11643
11644 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011645 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11646 // its only used to compare two uses within the same basic block, which
11647 // means that they'll always either have the same value or one of them
11648 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011649 if (isa<BinaryOperator>(A) ||
11650 isa<CastInst>(A) ||
11651 isa<PHINode>(A) ||
11652 isa<GetElementPtrInst>(A))
11653 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011654 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011655 return true;
11656
11657 // Otherwise they may not be equivalent.
11658 return false;
11659}
11660
Dale Johannesen4945c652009-03-03 21:26:39 +000011661// If this instruction has two uses, one of which is a llvm.dbg.declare,
11662// return the llvm.dbg.declare.
11663DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11664 if (!V->hasNUses(2))
11665 return 0;
11666 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11667 UI != E; ++UI) {
11668 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11669 return DI;
11670 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11671 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11672 return DI;
11673 }
11674 }
11675 return 0;
11676}
11677
Chris Lattner2f503e62005-01-31 05:36:43 +000011678Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11679 Value *Val = SI.getOperand(0);
11680 Value *Ptr = SI.getOperand(1);
11681
11682 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011683 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011684 ++NumCombined;
11685 return 0;
11686 }
Chris Lattner836692d2007-01-15 06:51:56 +000011687
11688 // If the RHS is an alloca with a single use, zapify the store, making the
11689 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011690 // If the RHS is an alloca with a two uses, the other one being a
11691 // llvm.dbg.declare, zapify the store and the declare, making the
11692 // alloca dead. We must do this to prevent declare's from affecting
11693 // codegen.
11694 if (!SI.isVolatile()) {
11695 if (Ptr->hasOneUse()) {
11696 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011697 EraseInstFromFunction(SI);
11698 ++NumCombined;
11699 return 0;
11700 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011701 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11702 if (isa<AllocaInst>(GEP->getOperand(0))) {
11703 if (GEP->getOperand(0)->hasOneUse()) {
11704 EraseInstFromFunction(SI);
11705 ++NumCombined;
11706 return 0;
11707 }
11708 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11709 EraseInstFromFunction(*DI);
11710 EraseInstFromFunction(SI);
11711 ++NumCombined;
11712 return 0;
11713 }
11714 }
11715 }
11716 }
11717 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11718 EraseInstFromFunction(*DI);
11719 EraseInstFromFunction(SI);
11720 ++NumCombined;
11721 return 0;
11722 }
Chris Lattner836692d2007-01-15 06:51:56 +000011723 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011724
Dan Gohman9941f742007-07-20 16:34:21 +000011725 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011726 if (TD) {
11727 unsigned KnownAlign =
11728 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11729 if (KnownAlign >
11730 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11731 SI.getAlignment()))
11732 SI.setAlignment(KnownAlign);
11733 }
Dan Gohman9941f742007-07-20 16:34:21 +000011734
Dale Johannesenacb51a32009-03-03 01:43:03 +000011735 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011736 // stores to the same location, separated by a few arithmetic operations. This
11737 // situation often occurs with bitfield accesses.
11738 BasicBlock::iterator BBI = &SI;
11739 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11740 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011741 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011742 // Don't count debug info directives, lest they affect codegen,
11743 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11744 // It is necessary for correctness to skip those that feed into a
11745 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011746 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011747 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011748 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011749 continue;
11750 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011751
11752 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11753 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011754 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11755 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011756 ++NumDeadStore;
11757 ++BBI;
11758 EraseInstFromFunction(*PrevSI);
11759 continue;
11760 }
11761 break;
11762 }
11763
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011764 // If this is a load, we have to stop. However, if the loaded value is from
11765 // the pointer we're loading and is producing the pointer we're storing,
11766 // then *this* store is dead (X = load P; store X -> P).
11767 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011768 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11769 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011770 EraseInstFromFunction(SI);
11771 ++NumCombined;
11772 return 0;
11773 }
11774 // Otherwise, this is a load from some other location. Stores before it
11775 // may not be dead.
11776 break;
11777 }
11778
Chris Lattner9ca96412006-02-08 03:25:32 +000011779 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011780 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011781 break;
11782 }
11783
11784
11785 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011786
11787 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011788 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011789 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011790 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011791 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011792 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011793 ++NumCombined;
11794 }
11795 return 0; // Do not modify these!
11796 }
11797
11798 // store undef, Ptr -> noop
11799 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011800 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011801 ++NumCombined;
11802 return 0;
11803 }
11804
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011805 // If the pointer destination is a cast, see if we can fold the cast into the
11806 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011807 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011808 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11809 return Res;
11810 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011811 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011812 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11813 return Res;
11814
Chris Lattner408902b2005-09-12 23:23:25 +000011815
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011816 // If this store is the last instruction in the basic block (possibly
11817 // excepting debug info instructions and the pointer bitcasts that feed
11818 // into them), and if the block ends with an unconditional branch, try
11819 // to move it to the successor block.
11820 BBI = &SI;
11821 do {
11822 ++BBI;
11823 } while (isa<DbgInfoIntrinsic>(BBI) ||
11824 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011825 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011826 if (BI->isUnconditional())
11827 if (SimplifyStoreAtEndOfBlock(SI))
11828 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011829
Chris Lattner2f503e62005-01-31 05:36:43 +000011830 return 0;
11831}
11832
Chris Lattner3284d1f2007-04-15 00:07:55 +000011833/// SimplifyStoreAtEndOfBlock - Turn things like:
11834/// if () { *P = v1; } else { *P = v2 }
11835/// into a phi node with a store in the successor.
11836///
Chris Lattner31755a02007-04-15 01:02:18 +000011837/// Simplify things like:
11838/// *P = v1; if () { *P = v2; }
11839/// into a phi node with a store in the successor.
11840///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011841bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11842 BasicBlock *StoreBB = SI.getParent();
11843
11844 // Check to see if the successor block has exactly two incoming edges. If
11845 // so, see if the other predecessor contains a store to the same location.
11846 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011847 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011848
11849 // Determine whether Dest has exactly two predecessors and, if so, compute
11850 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011851 pred_iterator PI = pred_begin(DestBB);
11852 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011853 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011854 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011855 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011856 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011857 return false;
11858
11859 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011860 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011861 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011862 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011863 }
Chris Lattner31755a02007-04-15 01:02:18 +000011864 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011865 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011866
11867 // Bail out if all the relevant blocks aren't distinct (this can happen,
11868 // for example, if SI is in an infinite loop)
11869 if (StoreBB == DestBB || OtherBB == DestBB)
11870 return false;
11871
Chris Lattner31755a02007-04-15 01:02:18 +000011872 // Verify that the other block ends in a branch and is not otherwise empty.
11873 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011874 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011875 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011876 return false;
11877
Chris Lattner31755a02007-04-15 01:02:18 +000011878 // If the other block ends in an unconditional branch, check for the 'if then
11879 // else' case. there is an instruction before the branch.
11880 StoreInst *OtherStore = 0;
11881 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011882 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011883 // Skip over debugging info.
11884 while (isa<DbgInfoIntrinsic>(BBI) ||
11885 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11886 if (BBI==OtherBB->begin())
11887 return false;
11888 --BBI;
11889 }
11890 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011891 OtherStore = dyn_cast<StoreInst>(BBI);
11892 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11893 return false;
11894 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011895 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011896 // destinations is StoreBB, then we have the if/then case.
11897 if (OtherBr->getSuccessor(0) != StoreBB &&
11898 OtherBr->getSuccessor(1) != StoreBB)
11899 return false;
11900
11901 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011902 // if/then triangle. See if there is a store to the same ptr as SI that
11903 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011904 for (;; --BBI) {
11905 // Check to see if we find the matching store.
11906 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11907 if (OtherStore->getOperand(1) != SI.getOperand(1))
11908 return false;
11909 break;
11910 }
Eli Friedman6903a242008-06-13 22:02:12 +000011911 // If we find something that may be using or overwriting the stored
11912 // value, or if we run out of instructions, we can't do the xform.
11913 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011914 BBI == OtherBB->begin())
11915 return false;
11916 }
11917
11918 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011919 // make sure nothing reads or overwrites the stored value in
11920 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011921 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11922 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011923 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011924 return false;
11925 }
11926 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011927
Chris Lattner31755a02007-04-15 01:02:18 +000011928 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011929 Value *MergedVal = OtherStore->getOperand(0);
11930 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011931 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011932 PN->reserveOperandSpace(2);
11933 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011934 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11935 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011936 }
11937
11938 // Advance to a place where it is safe to insert the new store and
11939 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011940 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011941 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11942 OtherStore->isVolatile()), *BBI);
11943
11944 // Nuke the old stores.
11945 EraseInstFromFunction(SI);
11946 EraseInstFromFunction(*OtherStore);
11947 ++NumCombined;
11948 return true;
11949}
11950
Chris Lattner2f503e62005-01-31 05:36:43 +000011951
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011952Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11953 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011954 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011955 BasicBlock *TrueDest;
11956 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011957 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011958 !isa<Constant>(X)) {
11959 // Swap Destinations and condition...
11960 BI.setCondition(X);
11961 BI.setSuccessor(0, FalseDest);
11962 BI.setSuccessor(1, TrueDest);
11963 return &BI;
11964 }
11965
Reid Spencere4d87aa2006-12-23 06:05:41 +000011966 // Cannonicalize fcmp_one -> fcmp_oeq
11967 FCmpInst::Predicate FPred; Value *Y;
11968 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011969 TrueDest, FalseDest)) &&
11970 BI.getCondition()->hasOneUse())
11971 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11972 FPred == FCmpInst::FCMP_OGE) {
11973 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11974 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11975
11976 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011977 BI.setSuccessor(0, FalseDest);
11978 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011979 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011980 return &BI;
11981 }
11982
11983 // Cannonicalize icmp_ne -> icmp_eq
11984 ICmpInst::Predicate IPred;
11985 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011986 TrueDest, FalseDest)) &&
11987 BI.getCondition()->hasOneUse())
11988 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11989 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11990 IPred == ICmpInst::ICMP_SGE) {
11991 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11992 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11993 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011994 BI.setSuccessor(0, FalseDest);
11995 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011996 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011997 return &BI;
11998 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011999
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012000 return 0;
12001}
Chris Lattner0864acf2002-11-04 16:18:53 +000012002
Chris Lattner46238a62004-07-03 00:26:11 +000012003Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12004 Value *Cond = SI.getCondition();
12005 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12006 if (I->getOpcode() == Instruction::Add)
12007 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12008 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12009 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012010 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012011 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012012 AddRHS));
12013 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012014 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012015 return &SI;
12016 }
12017 }
12018 return 0;
12019}
12020
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012021Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012022 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012023
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012024 if (!EV.hasIndices())
12025 return ReplaceInstUsesWith(EV, Agg);
12026
12027 if (Constant *C = dyn_cast<Constant>(Agg)) {
12028 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012029 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012030
12031 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012032 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012033
12034 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12035 // Extract the element indexed by the first index out of the constant
12036 Value *V = C->getOperand(*EV.idx_begin());
12037 if (EV.getNumIndices() > 1)
12038 // Extract the remaining indices out of the constant indexed by the
12039 // first index
12040 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12041 else
12042 return ReplaceInstUsesWith(EV, V);
12043 }
12044 return 0; // Can't handle other constants
12045 }
12046 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12047 // We're extracting from an insertvalue instruction, compare the indices
12048 const unsigned *exti, *exte, *insi, *inse;
12049 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12050 exte = EV.idx_end(), inse = IV->idx_end();
12051 exti != exte && insi != inse;
12052 ++exti, ++insi) {
12053 if (*insi != *exti)
12054 // The insert and extract both reference distinctly different elements.
12055 // This means the extract is not influenced by the insert, and we can
12056 // replace the aggregate operand of the extract with the aggregate
12057 // operand of the insert. i.e., replace
12058 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12059 // %E = extractvalue { i32, { i32 } } %I, 0
12060 // with
12061 // %E = extractvalue { i32, { i32 } } %A, 0
12062 return ExtractValueInst::Create(IV->getAggregateOperand(),
12063 EV.idx_begin(), EV.idx_end());
12064 }
12065 if (exti == exte && insi == inse)
12066 // Both iterators are at the end: Index lists are identical. Replace
12067 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12068 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12069 // with "i32 42"
12070 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12071 if (exti == exte) {
12072 // The extract list is a prefix of the insert list. i.e. replace
12073 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12074 // %E = extractvalue { i32, { i32 } } %I, 1
12075 // with
12076 // %X = extractvalue { i32, { i32 } } %A, 1
12077 // %E = insertvalue { i32 } %X, i32 42, 0
12078 // by switching the order of the insert and extract (though the
12079 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012080 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12081 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012082 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12083 insi, inse);
12084 }
12085 if (insi == inse)
12086 // The insert list is a prefix of the extract list
12087 // We can simply remove the common indices from the extract and make it
12088 // operate on the inserted value instead of the insertvalue result.
12089 // i.e., replace
12090 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12091 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12092 // with
12093 // %E extractvalue { i32 } { i32 42 }, 0
12094 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12095 exti, exte);
12096 }
12097 // Can't simplify extracts from other values. Note that nested extracts are
12098 // already simplified implicitely by the above (extract ( extract (insert) )
12099 // will be translated into extract ( insert ( extract ) ) first and then just
12100 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012101 return 0;
12102}
12103
Chris Lattner220b0cf2006-03-05 00:22:33 +000012104/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12105/// is to leave as a vector operation.
12106static bool CheapToScalarize(Value *V, bool isConstant) {
12107 if (isa<ConstantAggregateZero>(V))
12108 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012109 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012110 if (isConstant) return true;
12111 // If all elts are the same, we can extract.
12112 Constant *Op0 = C->getOperand(0);
12113 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12114 if (C->getOperand(i) != Op0)
12115 return false;
12116 return true;
12117 }
12118 Instruction *I = dyn_cast<Instruction>(V);
12119 if (!I) return false;
12120
12121 // Insert element gets simplified to the inserted element or is deleted if
12122 // this is constant idx extract element and its a constant idx insertelt.
12123 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12124 isa<ConstantInt>(I->getOperand(2)))
12125 return true;
12126 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12127 return true;
12128 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12129 if (BO->hasOneUse() &&
12130 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12131 CheapToScalarize(BO->getOperand(1), isConstant)))
12132 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012133 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12134 if (CI->hasOneUse() &&
12135 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12136 CheapToScalarize(CI->getOperand(1), isConstant)))
12137 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012138
12139 return false;
12140}
12141
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012142/// Read and decode a shufflevector mask.
12143///
12144/// It turns undef elements into values that are larger than the number of
12145/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012146static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12147 unsigned NElts = SVI->getType()->getNumElements();
12148 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12149 return std::vector<unsigned>(NElts, 0);
12150 if (isa<UndefValue>(SVI->getOperand(2)))
12151 return std::vector<unsigned>(NElts, 2*NElts);
12152
12153 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012154 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012155 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12156 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012157 Result.push_back(NElts*2); // undef -> 8
12158 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012159 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012160 return Result;
12161}
12162
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012163/// FindScalarElement - Given a vector and an element number, see if the scalar
12164/// value is already around as a register, for example if it were inserted then
12165/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012166static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012167 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012168 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12169 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012170 unsigned Width = PTy->getNumElements();
12171 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012172 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012173
12174 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012175 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012176 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012177 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012178 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012179 return CP->getOperand(EltNo);
12180 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12181 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012182 if (!isa<ConstantInt>(III->getOperand(2)))
12183 return 0;
12184 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012185
12186 // If this is an insert to the element we are looking for, return the
12187 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012188 if (EltNo == IIElt)
12189 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012190
12191 // Otherwise, the insertelement doesn't modify the value, recurse on its
12192 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012193 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012194 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012195 unsigned LHSWidth =
12196 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012197 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012198 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012199 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012200 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012201 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012202 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012203 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012204 }
12205
12206 // Otherwise, we don't know.
12207 return 0;
12208}
12209
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012210Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012211 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012212 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012213 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012214
Dan Gohman07a96762007-07-16 14:29:03 +000012215 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012216 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012217 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012218
Reid Spencer9d6565a2007-02-15 02:26:10 +000012219 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012220 // If vector val is constant with all elements the same, replace EI with
12221 // that element. When the elements are not identical, we cannot replace yet
12222 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012223 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012224 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012225 if (C->getOperand(i) != op0) {
12226 op0 = 0;
12227 break;
12228 }
12229 if (op0)
12230 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012231 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012232
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012233 // If extracting a specified index from the vector, see if we can recursively
12234 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012235 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012236 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012237 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012238
12239 // If this is extracting an invalid index, turn this into undef, to avoid
12240 // crashing the code below.
12241 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012242 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012243
Chris Lattner867b99f2006-10-05 06:55:50 +000012244 // This instruction only demands the single element from the input vector.
12245 // If the input vector has a single use, simplify it based on this use
12246 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012247 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012248 APInt UndefElts(VectorWidth, 0);
12249 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012250 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012251 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012252 EI.setOperand(0, V);
12253 return &EI;
12254 }
12255 }
12256
Owen Andersond672ecb2009-07-03 00:17:18 +000012257 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012258 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012259
12260 // If the this extractelement is directly using a bitcast from a vector of
12261 // the same number of elements, see if we can find the source element from
12262 // it. In this case, we will end up needing to bitcast the scalars.
12263 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12264 if (const VectorType *VT =
12265 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12266 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012267 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12268 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012269 return new BitCastInst(Elt, EI.getType());
12270 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012271 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012272
Chris Lattner73fa49d2006-05-25 22:53:38 +000012273 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012274 // Push extractelement into predecessor operation if legal and
12275 // profitable to do so
12276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12277 if (I->hasOneUse() &&
12278 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12279 Value *newEI0 =
12280 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12281 EI.getName()+".lhs");
12282 Value *newEI1 =
12283 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12284 EI.getName()+".rhs");
12285 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012286 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012287 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012288 // Extracting the inserted element?
12289 if (IE->getOperand(2) == EI.getOperand(1))
12290 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12291 // If the inserted and extracted elements are constants, they must not
12292 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012293 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012294 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012295 EI.setOperand(0, IE->getOperand(0));
12296 return &EI;
12297 }
12298 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12299 // If this is extracting an element from a shufflevector, figure out where
12300 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012301 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12302 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012303 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012304 unsigned LHSWidth =
12305 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12306
12307 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012308 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012309 else if (SrcIdx < LHSWidth*2) {
12310 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012311 Src = SVI->getOperand(1);
12312 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012313 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012314 }
Eric Christophera3500da2009-07-25 02:28:41 +000012315 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012316 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12317 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012318 }
12319 }
Eli Friedman2451a642009-07-18 23:06:53 +000012320 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012321 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012322 return 0;
12323}
12324
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012325/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12326/// elements from either LHS or RHS, return the shuffle mask and true.
12327/// Otherwise, return false.
12328static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012329 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012330 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012331 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12332 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012333 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012334
12335 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012336 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012337 return true;
12338 } else if (V == LHS) {
12339 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012340 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012341 return true;
12342 } else if (V == RHS) {
12343 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012344 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012345 return true;
12346 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12347 // If this is an insert of an extract from some other vector, include it.
12348 Value *VecOp = IEI->getOperand(0);
12349 Value *ScalarOp = IEI->getOperand(1);
12350 Value *IdxOp = IEI->getOperand(2);
12351
Chris Lattnerd929f062006-04-27 21:14:21 +000012352 if (!isa<ConstantInt>(IdxOp))
12353 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012354 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012355
12356 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12357 // Okay, we can handle this if the vector we are insertinting into is
12358 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012359 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012360 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012361 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012362 return true;
12363 }
12364 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12365 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012366 EI->getOperand(0)->getType() == V->getType()) {
12367 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012368 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012369
12370 // This must be extracting from either LHS or RHS.
12371 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12372 // Okay, we can handle this if the vector we are insertinting into is
12373 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012374 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012375 // If so, update the mask to reflect the inserted value.
12376 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012377 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012378 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012379 } else {
12380 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012381 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012382 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012383
12384 }
12385 return true;
12386 }
12387 }
12388 }
12389 }
12390 }
12391 // TODO: Handle shufflevector here!
12392
12393 return false;
12394}
12395
12396/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12397/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12398/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012399static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012400 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012401 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012402 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012403 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012404 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012405
12406 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012407 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012408 return V;
12409 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012410 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012411 return V;
12412 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12413 // If this is an insert of an extract from some other vector, include it.
12414 Value *VecOp = IEI->getOperand(0);
12415 Value *ScalarOp = IEI->getOperand(1);
12416 Value *IdxOp = IEI->getOperand(2);
12417
12418 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12419 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12420 EI->getOperand(0)->getType() == V->getType()) {
12421 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012422 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12423 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012424
12425 // Either the extracted from or inserted into vector must be RHSVec,
12426 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012427 if (EI->getOperand(0) == RHS || RHS == 0) {
12428 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012429 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012430 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012431 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012432 return V;
12433 }
12434
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012435 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012436 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12437 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012438 // Everything but the extracted element is replaced with the RHS.
12439 for (unsigned i = 0; i != NumElts; ++i) {
12440 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012441 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012442 }
12443 return V;
12444 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012445
12446 // If this insertelement is a chain that comes from exactly these two
12447 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012448 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12449 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012450 return EI->getOperand(0);
12451
Chris Lattnerefb47352006-04-15 01:39:45 +000012452 }
12453 }
12454 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012455 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012456
12457 // Otherwise, can't do anything fancy. Return an identity vector.
12458 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012459 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012460 return V;
12461}
12462
12463Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12464 Value *VecOp = IE.getOperand(0);
12465 Value *ScalarOp = IE.getOperand(1);
12466 Value *IdxOp = IE.getOperand(2);
12467
Chris Lattner599ded12007-04-09 01:11:16 +000012468 // Inserting an undef or into an undefined place, remove this.
12469 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12470 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012471
Chris Lattnerefb47352006-04-15 01:39:45 +000012472 // If the inserted element was extracted from some other vector, and if the
12473 // indexes are constant, try to turn this into a shufflevector operation.
12474 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12475 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12476 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012477 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012478 unsigned ExtractedIdx =
12479 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012480 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012481
12482 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12483 return ReplaceInstUsesWith(IE, VecOp);
12484
12485 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012486 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012487
12488 // If we are extracting a value from a vector, then inserting it right
12489 // back into the same place, just use the input vector.
12490 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12491 return ReplaceInstUsesWith(IE, VecOp);
12492
Chris Lattnerefb47352006-04-15 01:39:45 +000012493 // If this insertelement isn't used by some other insertelement, turn it
12494 // (and any insertelements it points to), into one big shuffle.
12495 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12496 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012497 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012498 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012499 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012500 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012501 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012502 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012503 }
12504 }
12505 }
12506
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012507 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12508 APInt UndefElts(VWidth, 0);
12509 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12510 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12511 return &IE;
12512
Chris Lattnerefb47352006-04-15 01:39:45 +000012513 return 0;
12514}
12515
12516
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012517Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12518 Value *LHS = SVI.getOperand(0);
12519 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012520 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012521
12522 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012523
Chris Lattner867b99f2006-10-05 06:55:50 +000012524 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012525 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012526 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012527
Dan Gohman488fbfc2008-09-09 18:11:14 +000012528 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012529
12530 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12531 return 0;
12532
Evan Cheng388df622009-02-03 10:05:09 +000012533 APInt UndefElts(VWidth, 0);
12534 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12535 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012536 LHS = SVI.getOperand(0);
12537 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012538 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012539 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012540
Chris Lattner863bcff2006-05-25 23:48:38 +000012541 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12542 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12543 if (LHS == RHS || isa<UndefValue>(LHS)) {
12544 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012545 // shuffle(undef,undef,mask) -> undef.
12546 return ReplaceInstUsesWith(SVI, LHS);
12547 }
12548
Chris Lattner863bcff2006-05-25 23:48:38 +000012549 // Remap any references to RHS to use LHS.
12550 std::vector<Constant*> Elts;
12551 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012552 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012553 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012554 else {
12555 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012556 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012557 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012558 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012559 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012560 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012561 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012562 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012563 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012564 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012565 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012566 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012567 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012568 LHS = SVI.getOperand(0);
12569 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012570 MadeChange = true;
12571 }
12572
Chris Lattner7b2e27922006-05-26 00:29:06 +000012573 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012574 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012575
Chris Lattner863bcff2006-05-25 23:48:38 +000012576 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12577 if (Mask[i] >= e*2) continue; // Ignore undef values.
12578 // Is this an identity shuffle of the LHS value?
12579 isLHSID &= (Mask[i] == i);
12580
12581 // Is this an identity shuffle of the RHS value?
12582 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012583 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012584
Chris Lattner863bcff2006-05-25 23:48:38 +000012585 // Eliminate identity shuffles.
12586 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12587 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012588
Chris Lattner7b2e27922006-05-26 00:29:06 +000012589 // If the LHS is a shufflevector itself, see if we can combine it with this
12590 // one without producing an unusual shuffle. Here we are really conservative:
12591 // we are absolutely afraid of producing a shuffle mask not in the input
12592 // program, because the code gen may not be smart enough to turn a merged
12593 // shuffle into two specific shuffles: it may produce worse code. As such,
12594 // we only merge two shuffles if the result is one of the two input shuffle
12595 // masks. In this case, merging the shuffles just removes one instruction,
12596 // which we know is safe. This is good for things like turning:
12597 // (splat(splat)) -> splat.
12598 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12599 if (isa<UndefValue>(RHS)) {
12600 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12601
12602 std::vector<unsigned> NewMask;
12603 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12604 if (Mask[i] >= 2*e)
12605 NewMask.push_back(2*e);
12606 else
12607 NewMask.push_back(LHSMask[Mask[i]]);
12608
12609 // If the result mask is equal to the src shuffle or this shuffle mask, do
12610 // the replacement.
12611 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012612 unsigned LHSInNElts =
12613 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012614 std::vector<Constant*> Elts;
12615 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012616 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012617 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012618 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012619 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012620 }
12621 }
12622 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12623 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012624 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012625 }
12626 }
12627 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012628
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012629 return MadeChange ? &SVI : 0;
12630}
12631
12632
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012633
Chris Lattnerea1c4542004-12-08 23:43:58 +000012634
12635/// TryToSinkInstruction - Try to move the specified instruction from its
12636/// current block into the beginning of DestBlock, which can only happen if it's
12637/// safe to move the instruction past all of the instructions between it and the
12638/// end of its block.
12639static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12640 assert(I->hasOneUse() && "Invariants didn't hold!");
12641
Chris Lattner108e9022005-10-27 17:13:11 +000012642 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012643 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012644 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012645
Chris Lattnerea1c4542004-12-08 23:43:58 +000012646 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012647 if (isa<AllocaInst>(I) && I->getParent() ==
12648 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012649 return false;
12650
Chris Lattner96a52a62004-12-09 07:14:34 +000012651 // We can only sink load instructions if there is nothing between the load and
12652 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012653 if (I->mayReadFromMemory()) {
12654 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012655 Scan != E; ++Scan)
12656 if (Scan->mayWriteToMemory())
12657 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012658 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012659
Dan Gohman02dea8b2008-05-23 21:05:58 +000012660 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012661
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012662 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012663 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012664 ++NumSunkInst;
12665 return true;
12666}
12667
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012668
12669/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12670/// all reachable code to the worklist.
12671///
12672/// This has a couple of tricks to make the code faster and more powerful. In
12673/// particular, we constant fold and DCE instructions as we go, to avoid adding
12674/// them to the worklist (this significantly speeds up instcombine on code where
12675/// many instructions are dead or constant). Additionally, if we find a branch
12676/// whose condition is a known constant, we only visit the reachable successors.
12677///
12678static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012679 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012680 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012681 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012682 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012683 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012684
12685 std::vector<Instruction*> InstrsForInstCombineWorklist;
12686 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012687
Chris Lattner2c7718a2007-03-23 19:17:18 +000012688 while (!Worklist.empty()) {
12689 BB = Worklist.back();
12690 Worklist.pop_back();
12691
12692 // We have now visited this block! If we've already been here, ignore it.
12693 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012694
Chris Lattner2c7718a2007-03-23 19:17:18 +000012695 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12696 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012697
Chris Lattner2c7718a2007-03-23 19:17:18 +000012698 // DCE instruction if trivially dead.
12699 if (isInstructionTriviallyDead(Inst)) {
12700 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012701 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012702 Inst->eraseFromParent();
12703 continue;
12704 }
12705
12706 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012707 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012708 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12709 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012710 Inst->replaceAllUsesWith(C);
12711 ++NumConstProp;
12712 Inst->eraseFromParent();
12713 continue;
12714 }
Devang Patel7fe1dec2008-11-19 18:56:50 +000012715
Chris Lattner67f7d542009-10-12 03:58:40 +000012716 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012717 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012718
12719 // Recursively visit successors. If this is a branch or switch on a
12720 // constant, only visit the reachable successor.
12721 TerminatorInst *TI = BB->getTerminator();
12722 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12723 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12724 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012725 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012726 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012727 continue;
12728 }
12729 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12730 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12731 // See if this is an explicit destination.
12732 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12733 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012734 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012735 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012736 continue;
12737 }
12738
12739 // Otherwise it is the default destination.
12740 Worklist.push_back(SI->getSuccessor(0));
12741 continue;
12742 }
12743 }
12744
12745 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12746 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012747 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012748
12749 // Once we've found all of the instructions to add to instcombine's worklist,
12750 // add them in reverse order. This way instcombine will visit from the top
12751 // of the function down. This jives well with the way that it adds all uses
12752 // of instructions to the worklist after doing a transformation, thus avoiding
12753 // some N^2 behavior in pathological cases.
12754 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12755 InstrsForInstCombineWorklist.size());
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012756}
12757
Chris Lattnerec9c3582007-03-03 02:04:50 +000012758bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012759 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012760 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012761
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012762 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12763 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012764
Chris Lattnerb3d59702005-07-07 20:40:38 +000012765 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012766 // Do a depth-first traversal of the function, populate the worklist with
12767 // the reachable instructions. Ignore blocks that are not reachable. Keep
12768 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012769 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012770 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012771
Chris Lattnerb3d59702005-07-07 20:40:38 +000012772 // Do a quick scan over the function. If we find any blocks that are
12773 // unreachable, remove any instructions inside of them. This prevents
12774 // the instcombine code from having to deal with some bad special cases.
12775 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12776 if (!Visited.count(BB)) {
12777 Instruction *Term = BB->getTerminator();
12778 while (Term != BB->begin()) { // Remove instrs bottom-up
12779 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012780
Chris Lattnerbdff5482009-08-23 04:37:46 +000012781 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012782 // A debug intrinsic shouldn't force another iteration if we weren't
12783 // going to do one without it.
12784 if (!isa<DbgInfoIntrinsic>(I)) {
12785 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012786 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012787 }
Devang Patel228ebd02009-10-13 22:56:32 +000012788
12789
12790 // If I is not void type then replaceAllUsesWith undef.
12791 // This allows ValueHandlers and custom metadata to adjust itself.
12792 if (I->getType() != Type::getVoidTy(*Context))
12793 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012794 I->eraseFromParent();
12795 }
12796 }
12797 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012798
Chris Lattner873ff012009-08-30 05:55:36 +000012799 while (!Worklist.isEmpty()) {
12800 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012801 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012802
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012803 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012804 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012805 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012806 EraseInstFromFunction(*I);
12807 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012808 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012809 continue;
12810 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012811
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012812 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012813 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012814 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012815
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012816 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012817 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012818 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012819 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012820 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012821 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012822 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012823
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012824 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012825 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012826 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12827 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012828 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12829 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012830 if (NewC != CE) {
Dan Gohmane41a1152009-10-05 16:31:55 +000012831 *i = NewC;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012832 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012833 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012834 }
12835
Chris Lattnerea1c4542004-12-08 23:43:58 +000012836 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012837 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012838 BasicBlock *BB = I->getParent();
12839 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12840 if (UserParent != BB) {
12841 bool UserIsSuccessor = false;
12842 // See if the user is one of our successors.
12843 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12844 if (*SI == UserParent) {
12845 UserIsSuccessor = true;
12846 break;
12847 }
12848
12849 // If the user is one of our immediate successors, and if that successor
12850 // only has us as a predecessors (we'd have to split the critical edge
12851 // otherwise), we can keep going.
12852 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12853 next(pred_begin(UserParent)) == pred_end(UserParent))
12854 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012855 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012856 }
12857 }
12858
Chris Lattner74381062009-08-30 07:44:24 +000012859 // Now that we have an instruction, try combining it to simplify it.
12860 Builder->SetInsertPoint(I->getParent(), I);
12861
Reid Spencera9b81012007-03-26 17:44:01 +000012862#ifndef NDEBUG
12863 std::string OrigI;
12864#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012865 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012866 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12867
Chris Lattner90ac28c2002-08-02 19:29:35 +000012868 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012869 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012870 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012871 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012872 DEBUG(errs() << "IC: Old = " << *I << '\n'
12873 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012874
Chris Lattnerf523d062004-06-09 05:08:07 +000012875 // Everything uses the new instruction now.
12876 I->replaceAllUsesWith(Result);
12877
12878 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012879 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012880 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012881
Chris Lattner6934a042007-02-11 01:23:03 +000012882 // Move the name to the new instruction first.
12883 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012884
12885 // Insert the new instruction into the basic block...
12886 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012887 BasicBlock::iterator InsertPos = I;
12888
12889 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12890 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12891 ++InsertPos;
12892
12893 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012894
Chris Lattner7a1e9242009-08-30 06:13:40 +000012895 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012896 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012897#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012898 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12899 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012900#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012901
Chris Lattner90ac28c2002-08-02 19:29:35 +000012902 // If the instruction was modified, it's possible that it is now dead.
12903 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012904 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012905 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012906 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012907 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012908 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012909 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012910 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012911 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012912 }
12913 }
12914
Chris Lattner873ff012009-08-30 05:55:36 +000012915 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012916 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012917}
12918
Chris Lattnerec9c3582007-03-03 02:04:50 +000012919
12920bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012921 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012922 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012923
Chris Lattner74381062009-08-30 07:44:24 +000012924
12925 /// Builder - This is an IRBuilder that automatically inserts new
12926 /// instructions into the worklist when they are created.
12927 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12928 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12929 InstCombineIRInserter(Worklist));
12930 Builder = &TheBuilder;
12931
Chris Lattnerec9c3582007-03-03 02:04:50 +000012932 bool EverMadeChange = false;
12933
12934 // Iterate while there is work to do.
12935 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012936 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012937 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012938
12939 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012940 return EverMadeChange;
12941}
12942
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012943FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012944 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012945}