blob: 52b9b0438f3daec2db8c7e4b7aa23d39f784fa5c [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 Hernandezf006b182009-10-27 20:05:49 +000045#include "llvm/Analysis/MemoryBuiltins.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"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000059#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000060#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000061#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000062#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000063#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000064#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000065#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000066#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000067#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000068using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000069using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071STATISTIC(NumCombined , "Number of insts combined");
72STATISTIC(NumConstProp, "Number of constant folds");
73STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000076
Chris Lattner0e5f4992006-12-19 21:40:18 +000077namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000078 /// InstCombineWorklist - This is the worklist management logic for
79 /// InstCombine.
80 class InstCombineWorklist {
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
83
84 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
85 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 public:
87 InstCombineWorklist() {}
88
89 bool isEmpty() const { return Worklist.empty(); }
90
91 /// Add - Add the specified instruction to the worklist if it isn't already
92 /// in it.
93 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000096 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000097 }
Chris Lattner873ff012009-08-30 05:55:36 +000098 }
99
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000100 void AddValue(Value *V) {
101 if (Instruction *I = dyn_cast<Instruction>(V))
102 Add(I);
103 }
104
Chris Lattner67f7d542009-10-12 03:58:40 +0000105 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106 /// which should only be done when the worklist is empty and when the group
107 /// has no duplicates.
108 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109 assert(Worklist.empty() && "Worklist must be empty to add initial group");
110 Worklist.reserve(NumEntries+16);
111 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112 for (; NumEntries; --NumEntries) {
113 Instruction *I = List[NumEntries-1];
114 WorklistMap.insert(std::make_pair(I, Worklist.size()));
115 Worklist.push_back(I);
116 }
117 }
118
Chris Lattner7a1e9242009-08-30 06:13:40 +0000119 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000120 void Remove(Instruction *I) {
121 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122 if (It == WorklistMap.end()) return; // Not in worklist.
123
124 // Don't bother moving everything down, just null out the slot.
125 Worklist[It->second] = 0;
126
127 WorklistMap.erase(It);
128 }
129
130 Instruction *RemoveOne() {
131 Instruction *I = Worklist.back();
132 Worklist.pop_back();
133 WorklistMap.erase(I);
134 return I;
135 }
136
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000137 /// AddUsersToWorkList - When an instruction is simplified, add all users of
138 /// the instruction to the work lists because they might get more simplified
139 /// now.
140 ///
141 void AddUsersToWorkList(Instruction &I) {
142 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143 UI != UE; ++UI)
144 Add(cast<Instruction>(*UI));
145 }
146
Chris Lattner873ff012009-08-30 05:55:36 +0000147
148 /// Zap - check that the worklist is empty and nuke the backing store for
149 /// the map if it is large.
150 void Zap() {
151 assert(WorklistMap.empty() && "Worklist empty, but map not?");
152
153 // Do an explicit clear, this shrinks the map if needed.
154 WorklistMap.clear();
155 }
156 };
157} // end anonymous namespace.
158
159
160namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000161 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162 /// just like the normal insertion helper, but also adds any new instructions
163 /// to the instcombine worklist.
164 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165 InstCombineWorklist &Worklist;
166 public:
167 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168
169 void InsertHelper(Instruction *I, const Twine &Name,
170 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172 Worklist.Add(I);
173 }
174 };
175} // end anonymous namespace
176
177
178namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000179 class InstCombiner : public FunctionPass,
180 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000181 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000182 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000183 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000184 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000185 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000186 InstCombineWorklist Worklist;
187
Chris Lattner74381062009-08-30 07:44:24 +0000188 /// Builder - This is an IRBuilder that automatically inserts new
189 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000190 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000191 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000192
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000193 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000194 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000195
Owen Andersone922c022009-07-22 00:24:57 +0000196 LLVMContext *Context;
197 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000198
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000199 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000200 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000201
202 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000203
Chris Lattner97e52e42002-04-28 21:27:06 +0000204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000205 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000206 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000207 }
208
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000209 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000210
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000211 // Visitation implementation - Implement instruction combining for different
212 // instruction types. The semantics are as follows:
213 // Return Value:
214 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000215 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000216 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000217 //
Chris Lattner7e708292002-06-25 16:13:24 +0000218 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000219 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000220 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000222 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000224 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000225 Instruction *visitURem(BinaryOperator &I);
226 Instruction *visitSRem(BinaryOperator &I);
227 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000228 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000229 Instruction *commonRemTransforms(BinaryOperator &I);
230 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000231 Instruction *commonDivTransforms(BinaryOperator &I);
232 Instruction *commonIDivTransforms(BinaryOperator &I);
233 Instruction *visitUDiv(BinaryOperator &I);
234 Instruction *visitSDiv(BinaryOperator &I);
235 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000236 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000237 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000239 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000240 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000241 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000242 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000243 Instruction *visitOr (BinaryOperator &I);
244 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000245 Instruction *visitShl(BinaryOperator &I);
246 Instruction *visitAShr(BinaryOperator &I);
247 Instruction *visitLShr(BinaryOperator &I);
248 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000249 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
250 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000251 Instruction *visitFCmpInst(FCmpInst &I);
252 Instruction *visitICmpInst(ICmpInst &I);
253 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000254 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
255 Instruction *LHS,
256 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000257 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
258 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000259
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000260 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000261 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000262 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000263 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000264 Instruction *commonCastTransforms(CastInst &CI);
265 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000266 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000267 Instruction *visitTrunc(TruncInst &CI);
268 Instruction *visitZExt(ZExtInst &CI);
269 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000270 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000271 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000272 Instruction *visitFPToUI(FPToUIInst &FI);
273 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000274 Instruction *visitUIToFP(CastInst &CI);
275 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000276 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000277 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000278 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000279 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
280 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000281 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000282 Instruction *visitSelectInst(SelectInst &SI);
283 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000284 Instruction *visitCallInst(CallInst &CI);
285 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000286
287 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000288 Instruction *visitPHINode(PHINode &PN);
289 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000290 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000291 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000292 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000293 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000294 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000295 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000296 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000297 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000298 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000299 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000300
301 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000302 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000303
Chris Lattner9fe38862003-06-19 17:00:31 +0000304 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000305 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000306 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000307 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000308 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
309 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000310 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000311 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
312
Chris Lattner9fe38862003-06-19 17:00:31 +0000313
Chris Lattner28977af2004-04-05 01:30:19 +0000314 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000315 // InsertNewInstBefore - insert an instruction New before instruction Old
316 // in the program. Add the new instruction to the worklist.
317 //
Chris Lattner955f3312004-09-28 21:48:02 +0000318 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000319 assert(New && New->getParent() == 0 &&
320 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000321 BasicBlock *BB = Old.getParent();
322 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000323 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000324 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000325 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000326
Chris Lattner8b170942002-08-09 23:47:40 +0000327 // ReplaceInstUsesWith - This method is to be used when an instruction is
328 // found to be dead, replacable with another preexisting expression. Here
329 // we add all uses of I to the worklist, replace all uses of I with the new
330 // value, then return I, so that the inst combiner will know that I was
331 // modified.
332 //
333 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000334 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000335
336 // If we are replacing the instruction with itself, this must be in a
337 // segment of unreachable code, so just clobber the instruction.
338 if (&I == V)
339 V = UndefValue::get(I.getType());
340
341 I.replaceAllUsesWith(V);
342 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000343 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344
345 // EraseInstFromFunction - When dealing with an instruction that has side
346 // effects or produces a void value, we can't rely on DCE to delete the
347 // instruction. Instead, visit methods should return the value returned by
348 // this function.
349 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000350 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000351
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000352 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000353 // Make sure that we reprocess all operands now that we reduced their
354 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000355 if (I.getNumOperands() < 8) {
356 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
357 if (Instruction *Op = dyn_cast<Instruction>(*i))
358 Worklist.Add(Op);
359 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000360 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000361 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000362 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000363 return 0; // Don't do anything with FI
364 }
Chris Lattner173234a2008-06-02 01:18:21 +0000365
366 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
367 APInt &KnownOne, unsigned Depth = 0) const {
368 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
369 }
370
371 bool MaskedValueIsZero(Value *V, const APInt &Mask,
372 unsigned Depth = 0) const {
373 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
374 }
375 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
376 return llvm::ComputeNumSignBits(Op, TD, Depth);
377 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000378
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000379 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000380
Reid Spencere4d87aa2006-12-23 06:05:41 +0000381 /// SimplifyCommutative - This performs a few simplifications for
382 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000383 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000384
Reid Spencere4d87aa2006-12-23 06:05:41 +0000385 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
386 /// most-complex to least-complex order.
387 bool SimplifyCompare(CmpInst &I);
388
Chris Lattner886ab6c2009-01-31 08:15:18 +0000389 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
390 /// based on the demanded bits.
391 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
392 APInt& KnownZero, APInt& KnownOne,
393 unsigned Depth);
394 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000395 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000396 unsigned Depth=0);
397
398 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
399 /// SimplifyDemandedBits knows about. See if the instruction has any
400 /// properties that allow us to simplify its operands.
401 bool SimplifyDemandedInstructionBits(Instruction &Inst);
402
Evan Cheng388df622009-02-03 10:05:09 +0000403 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
404 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000405
Chris Lattner5d1704d2009-09-27 19:57:57 +0000406 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
407 // which has a PHI node as operand #0, see if we can fold the instruction
408 // into the PHI (which is only possible if all operands to the PHI are
409 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000410 //
411 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
412 // that would normally be unprofitable because they strongly encourage jump
413 // threading.
414 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000415
Chris Lattnerbac32862004-11-14 19:13:23 +0000416 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
417 // operator and they all are only used by the PHI, PHI together their
418 // inputs, and do the operation once, to the result of the PHI.
419 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000420 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000421 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000422 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000423
Chris Lattner7da52b22006-11-01 04:51:18 +0000424
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000425 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
426 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000427
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000428 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000429 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000430 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000431 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000432 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000433 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000434 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000435 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000436 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000437
Chris Lattnerafe91a52006-06-15 19:07:26 +0000438
Reid Spencerc55b2432006-12-13 18:21:21 +0000439 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000440
Dan Gohman6de29f82009-06-15 22:12:54 +0000441 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000442 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000443 unsigned GetOrEnforceKnownAlignment(Value *V,
444 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000445
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000446 };
Chris Lattner873ff012009-08-30 05:55:36 +0000447} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000448
Dan Gohman844731a2008-05-13 00:00:25 +0000449char InstCombiner::ID = 0;
450static RegisterPass<InstCombiner>
451X("instcombine", "Combine redundant instructions");
452
Chris Lattner4f98c562003-03-10 21:43:22 +0000453// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000454// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000455static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000456 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000457 if (BinaryOperator::isNeg(V) ||
458 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000459 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000460 return 3;
461 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000462 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000463 if (isa<Argument>(V)) return 3;
464 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000465}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000466
Chris Lattnerc8802d22003-03-11 00:12:48 +0000467// isOnlyUse - Return true if this instruction will be deleted if we stop using
468// it.
469static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000470 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000471}
472
Chris Lattner4cb170c2004-02-23 06:38:22 +0000473// getPromotedType - Return the specified type promoted as it would be to pass
474// though a va_arg area...
475static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000476 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
477 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000478 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000479 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000480 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000481}
482
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000483/// getBitCastOperand - If the specified operand is a CastInst, a constant
484/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
485/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000486static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000487 if (Operator *O = dyn_cast<Operator>(V)) {
488 if (O->getOpcode() == Instruction::BitCast)
489 return O->getOperand(0);
490 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
491 if (GEP->hasAllZeroIndices())
492 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000493 }
Chris Lattnereed48272005-09-13 00:40:14 +0000494 return 0;
495}
496
Reid Spencer3da59db2006-11-27 01:05:10 +0000497/// This function is a wrapper around CastInst::isEliminableCastPair. It
498/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000499static Instruction::CastOps
500isEliminableCastPair(
501 const CastInst *CI, ///< The first cast instruction
502 unsigned opcode, ///< The opcode of the second cast instruction
503 const Type *DstTy, ///< The target type for the second cast instruction
504 TargetData *TD ///< The target data for pointer size
505) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000506
Reid Spencer3da59db2006-11-27 01:05:10 +0000507 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
508 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000509
Reid Spencer3da59db2006-11-27 01:05:10 +0000510 // Get the opcodes of the two Cast instructions
511 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
512 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000513
Chris Lattnera0e69692009-03-24 18:35:40 +0000514 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000515 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000516 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000517
518 // We don't want to form an inttoptr or ptrtoint that converts to an integer
519 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000520 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000521 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000522 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000523 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000524 Res = 0;
525
526 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000527}
528
529/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
530/// in any code being generated. It does not require codegen if V is simple
531/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000532static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
533 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000534 if (V->getType() == Ty || isa<Constant>(V)) return false;
535
Chris Lattner01575b72006-05-25 23:24:33 +0000536 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000537 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000538 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000539 return false;
540 return true;
541}
542
Chris Lattner4f98c562003-03-10 21:43:22 +0000543// SimplifyCommutative - This performs a few simplifications for commutative
544// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000545//
Chris Lattner4f98c562003-03-10 21:43:22 +0000546// 1. Order operands such that they are listed from right (least complex) to
547// left (most complex). This puts constants before unary operators before
548// binary operators.
549//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
551// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000552//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000554 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000555 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000556 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000557
Chris Lattner4f98c562003-03-10 21:43:22 +0000558 if (!I.isAssociative()) return Changed;
559 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000560 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
561 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
562 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000563 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000564 cast<Constant>(I.getOperand(1)),
565 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566 I.setOperand(0, Op->getOperand(0));
567 I.setOperand(1, Folded);
568 return true;
569 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
570 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
571 isOnlyUse(Op) && isOnlyUse(Op1)) {
572 Constant *C1 = cast<Constant>(Op->getOperand(1));
573 Constant *C2 = cast<Constant>(Op1->getOperand(1));
574
575 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000576 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000577 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000578 Op1->getOperand(0),
579 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000580 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581 I.setOperand(0, New);
582 I.setOperand(1, Folded);
583 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000584 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000585 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000586 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000587}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000588
Reid Spencere4d87aa2006-12-23 06:05:41 +0000589/// SimplifyCompare - For a CmpInst this function just orders the operands
590/// so that theyare listed from right (least complex) to left (most complex).
591/// This puts constants before unary operators before binary operators.
592bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000593 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000594 return false;
595 I.swapOperands();
596 // Compare instructions are not associative so there's nothing else we can do.
597 return true;
598}
599
Chris Lattner8d969642003-03-10 23:06:50 +0000600// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
601// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000602//
Dan Gohman186a6362009-08-12 16:04:34 +0000603static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000604 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000605 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000606
Chris Lattner0ce85802004-12-14 20:08:06 +0000607 // Constants can be considered to be negated values if they can be folded.
608 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000609 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000610
611 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
612 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000613 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000614
Chris Lattner8d969642003-03-10 23:06:50 +0000615 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000616}
617
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000618// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
619// instruction if the LHS is a constant negative zero (which is the 'negate'
620// form).
621//
Dan Gohman186a6362009-08-12 16:04:34 +0000622static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000623 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000624 return BinaryOperator::getFNegArgument(V);
625
626 // Constants can be considered to be negated values if they can be folded.
627 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000628 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000629
630 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
631 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000632 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000633
634 return 0;
635}
636
Chris Lattner48b59ec2009-10-26 15:40:07 +0000637/// isFreeToInvert - Return true if the specified value is free to invert (apply
638/// ~ to). This happens in cases where the ~ can be eliminated.
639static inline bool isFreeToInvert(Value *V) {
640 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000641 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000642 return true;
643
644 // Constants can be considered to be not'ed values.
645 if (isa<ConstantInt>(V))
646 return true;
647
648 // Compares can be inverted if they have a single use.
649 if (CmpInst *CI = dyn_cast<CmpInst>(V))
650 return CI->hasOneUse();
651
652 return false;
653}
654
655static inline Value *dyn_castNotVal(Value *V) {
656 // If this is not(not(x)) don't return that this is a not: we want the two
657 // not's to be folded first.
658 if (BinaryOperator::isNot(V)) {
659 Value *Operand = BinaryOperator::getNotArgument(V);
660 if (!isFreeToInvert(Operand))
661 return Operand;
662 }
Chris Lattner8d969642003-03-10 23:06:50 +0000663
664 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000665 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000666 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000667 return 0;
668}
669
Chris Lattner48b59ec2009-10-26 15:40:07 +0000670
671
Chris Lattnerc8802d22003-03-11 00:12:48 +0000672// dyn_castFoldableMul - If this value is a multiply that can be folded into
673// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000674// non-constant operand of the multiply, and set CST to point to the multiplier.
675// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000676//
Dan Gohman186a6362009-08-12 16:04:34 +0000677static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000678 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000679 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000680 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000681 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000682 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000683 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000684 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000685 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000686 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000687 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000688 CST = ConstantInt::get(V->getType()->getContext(),
689 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000690 return I->getOperand(0);
691 }
692 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000693 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000694}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000695
Reid Spencer7177c3a2007-03-25 05:33:51 +0000696/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000697static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000698 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000699 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000700}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000701/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000702static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000703 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000704 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000705}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000706/// MultiplyOverflows - True if the multiply can not be expressed in an int
707/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000708static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000709 uint32_t W = C1->getBitWidth();
710 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
711 if (sign) {
712 LHSExt.sext(W * 2);
713 RHSExt.sext(W * 2);
714 } else {
715 LHSExt.zext(W * 2);
716 RHSExt.zext(W * 2);
717 }
718
719 APInt MulExt = LHSExt * RHSExt;
720
721 if (sign) {
722 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
723 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
724 return MulExt.slt(Min) || MulExt.sgt(Max);
725 } else
726 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
727}
Chris Lattner955f3312004-09-28 21:48:02 +0000728
Reid Spencere7816b52007-03-08 01:52:58 +0000729
Chris Lattner255d8912006-02-11 09:31:47 +0000730/// ShrinkDemandedConstant - Check to see if the specified operand of the
731/// specified instruction is a constant integer. If so, check to see if there
732/// are any bits set in the constant that are not demanded. If so, shrink the
733/// constant and return true.
734static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000735 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000736 assert(I && "No instruction?");
737 assert(OpNo < I->getNumOperands() && "Operand index too large");
738
739 // If the operand is not a constant integer, nothing to do.
740 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
741 if (!OpC) return false;
742
743 // If there are no bits set that aren't demanded, nothing to do.
744 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
745 if ((~Demanded & OpC->getValue()) == 0)
746 return false;
747
748 // This instruction is producing bits that are not demanded. Shrink the RHS.
749 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000750 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000751 return true;
752}
753
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000754// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
755// set of known zero and one bits, compute the maximum and minimum values that
756// could have the specified known zero and known one bits, returning them in
757// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000758static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000759 const APInt& KnownOne,
760 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000761 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
762 KnownZero.getBitWidth() == Min.getBitWidth() &&
763 KnownZero.getBitWidth() == Max.getBitWidth() &&
764 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000765 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000766
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000767 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
768 // bit if it is unknown.
769 Min = KnownOne;
770 Max = KnownOne|UnknownBits;
771
Dan Gohman1c8491e2009-04-25 17:12:48 +0000772 if (UnknownBits.isNegative()) { // Sign bit is unknown
773 Min.set(Min.getBitWidth()-1);
774 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000775 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000776}
777
778// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
779// a set of known zero and one bits, compute the maximum and minimum values that
780// could have the specified known zero and known one bits, returning them in
781// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000782static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000783 const APInt &KnownOne,
784 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000785 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
786 KnownZero.getBitWidth() == Min.getBitWidth() &&
787 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000788 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000789 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000790
791 // The minimum value is when the unknown bits are all zeros.
792 Min = KnownOne;
793 // The maximum value is when the unknown bits are all ones.
794 Max = KnownOne|UnknownBits;
795}
Chris Lattner255d8912006-02-11 09:31:47 +0000796
Chris Lattner886ab6c2009-01-31 08:15:18 +0000797/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
798/// SimplifyDemandedBits knows about. See if the instruction has any
799/// properties that allow us to simplify its operands.
800bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000801 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000802 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
803 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
804
805 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
806 KnownZero, KnownOne, 0);
807 if (V == 0) return false;
808 if (V == &Inst) return true;
809 ReplaceInstUsesWith(Inst, V);
810 return true;
811}
812
813/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
814/// specified instruction operand if possible, updating it in place. It returns
815/// true if it made any change and false otherwise.
816bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
817 APInt &KnownZero, APInt &KnownOne,
818 unsigned Depth) {
819 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
820 KnownZero, KnownOne, Depth);
821 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000822 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000823 return true;
824}
825
826
827/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
828/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000829/// that only the bits set in DemandedMask of the result of V are ever used
830/// downstream. Consequently, depending on the mask and V, it may be possible
831/// to replace V with a constant or one of its operands. In such cases, this
832/// function does the replacement and returns true. In all other cases, it
833/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000834/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000835/// to be zero in the expression. These are provided to potentially allow the
836/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
837/// the expression. KnownOne and KnownZero always follow the invariant that
838/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
839/// the bits in KnownOne and KnownZero may only be accurate for those bits set
840/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
841/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000842///
843/// This returns null if it did not change anything and it permits no
844/// simplification. This returns V itself if it did some simplification of V's
845/// operands based on the information about what bits are demanded. This returns
846/// some other non-null value if it found out that V is equal to another value
847/// in the context where the specified bits are demanded, but not for all users.
848Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
849 APInt &KnownZero, APInt &KnownOne,
850 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000851 assert(V != 0 && "Null pointer of Value???");
852 assert(Depth <= 6 && "Limit Search Depth");
853 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000854 const Type *VTy = V->getType();
855 assert((TD || !isa<PointerType>(VTy)) &&
856 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000857 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
858 (!VTy->isIntOrIntVector() ||
859 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000860 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000861 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000862 "Value *V, DemandedMask, KnownZero and KnownOne "
863 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000864 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
865 // We know all of the bits for a constant!
866 KnownOne = CI->getValue() & DemandedMask;
867 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000868 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000869 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000870 if (isa<ConstantPointerNull>(V)) {
871 // We know all of the bits for a constant!
872 KnownOne.clear();
873 KnownZero = DemandedMask;
874 return 0;
875 }
876
Chris Lattner08d2cc72009-01-31 07:26:06 +0000877 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000878 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000879 if (DemandedMask == 0) { // Not demanding any bits from V.
880 if (isa<UndefValue>(V))
881 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000882 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000883 }
884
Chris Lattner4598c942009-01-31 08:24:16 +0000885 if (Depth == 6) // Limit search depth.
886 return 0;
887
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000888 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
889 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
890
Dan Gohman1c8491e2009-04-25 17:12:48 +0000891 Instruction *I = dyn_cast<Instruction>(V);
892 if (!I) {
893 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
894 return 0; // Only analyze instructions.
895 }
896
Chris Lattner4598c942009-01-31 08:24:16 +0000897 // If there are multiple uses of this value and we aren't at the root, then
898 // we can't do any simplifications of the operands, because DemandedMask
899 // only reflects the bits demanded by *one* of the users.
900 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000901 // Despite the fact that we can't simplify this instruction in all User's
902 // context, we can at least compute the knownzero/knownone bits, and we can
903 // do simplifications that apply to *just* the one user if we know that
904 // this instruction has a simpler value in that context.
905 if (I->getOpcode() == Instruction::And) {
906 // If either the LHS or the RHS are Zero, the result is zero.
907 ComputeMaskedBits(I->getOperand(1), DemandedMask,
908 RHSKnownZero, RHSKnownOne, Depth+1);
909 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
910 LHSKnownZero, LHSKnownOne, Depth+1);
911
912 // If all of the demanded bits are known 1 on one side, return the other.
913 // These bits cannot contribute to the result of the 'and' in this
914 // context.
915 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
916 (DemandedMask & ~LHSKnownZero))
917 return I->getOperand(0);
918 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
919 (DemandedMask & ~RHSKnownZero))
920 return I->getOperand(1);
921
922 // If all of the demanded bits in the inputs are known zeros, return zero.
923 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000924 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000925
926 } else if (I->getOpcode() == Instruction::Or) {
927 // We can simplify (X|Y) -> X or Y in the user's context if we know that
928 // only bits from X or Y are demanded.
929
930 // If either the LHS or the RHS are One, the result is One.
931 ComputeMaskedBits(I->getOperand(1), DemandedMask,
932 RHSKnownZero, RHSKnownOne, Depth+1);
933 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
934 LHSKnownZero, LHSKnownOne, Depth+1);
935
936 // If all of the demanded bits are known zero on one side, return the
937 // other. These bits cannot contribute to the result of the 'or' in this
938 // context.
939 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
940 (DemandedMask & ~LHSKnownOne))
941 return I->getOperand(0);
942 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
943 (DemandedMask & ~RHSKnownOne))
944 return I->getOperand(1);
945
946 // If all of the potentially set bits on one side are known to be set on
947 // the other side, just use the 'other' side.
948 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
949 (DemandedMask & (~RHSKnownZero)))
950 return I->getOperand(0);
951 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
952 (DemandedMask & (~LHSKnownZero)))
953 return I->getOperand(1);
954 }
955
Chris Lattner4598c942009-01-31 08:24:16 +0000956 // Compute the KnownZero/KnownOne bits to simplify things downstream.
957 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
958 return 0;
959 }
960
961 // If this is the root being simplified, allow it to have multiple uses,
962 // just set the DemandedMask to all bits so that we can try to simplify the
963 // operands. This allows visitTruncInst (for example) to simplify the
964 // operand of a trunc without duplicating all the logic below.
965 if (Depth == 0 && !V->hasOneUse())
966 DemandedMask = APInt::getAllOnesValue(BitWidth);
967
Reid Spencer8cb68342007-03-12 17:25:59 +0000968 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000969 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000970 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000971 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000972 case Instruction::And:
973 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
975 RHSKnownZero, RHSKnownOne, Depth+1) ||
976 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000977 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 return I;
979 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
980 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // If all of the demanded bits are known 1 on one side, return the other.
983 // These bits cannot contribute to the result of the 'and'.
984 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
985 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
988 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // If all of the demanded bits in the inputs are known zeros, return zero.
992 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000993 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000996 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000998
999 // Output known-1 bits are only known if set in both the LHS & RHS.
1000 RHSKnownOne &= LHSKnownOne;
1001 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1002 RHSKnownZero |= LHSKnownZero;
1003 break;
1004 case Instruction::Or:
1005 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1007 RHSKnownZero, RHSKnownOne, Depth+1) ||
1008 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001009 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001010 return I;
1011 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1012 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001013
1014 // If all of the demanded bits are known zero on one side, return the other.
1015 // These bits cannot contribute to the result of the 'or'.
1016 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1017 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1020 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001021 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001022
1023 // If all of the potentially set bits on one side are known to be set on
1024 // the other side, just use the 'other' side.
1025 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1026 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1029 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001030 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031
1032 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001033 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001035
1036 // Output known-0 bits are only known if clear in both the LHS & RHS.
1037 RHSKnownZero &= LHSKnownZero;
1038 // Output known-1 are known to be set if set in either the LHS | RHS.
1039 RHSKnownOne |= LHSKnownOne;
1040 break;
1041 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1043 RHSKnownZero, RHSKnownOne, Depth+1) ||
1044 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001045 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001046 return I;
1047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1048 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001049
1050 // If all of the demanded bits are known zero on one side, return the other.
1051 // These bits cannot contribute to the result of the 'xor'.
1052 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001054 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001056
1057 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1058 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1059 (RHSKnownOne & LHSKnownOne);
1060 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1061 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1062 (RHSKnownOne & LHSKnownZero);
1063
1064 // If all of the demanded bits are known to be zero on one side or the
1065 // other, turn this into an *inclusive* or.
1066 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001067 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1068 Instruction *Or =
1069 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1070 I->getName());
1071 return InsertNewInstBefore(Or, *I);
1072 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001073
1074 // If all of the demanded bits on one side are known, and all of the set
1075 // bits on that side are also known to be set on the other side, turn this
1076 // into an AND, as we know the bits will be cleared.
1077 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1078 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1079 // all known
1080 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001081 Constant *AndC = Constant::getIntegerValue(VTy,
1082 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001084 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001085 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 }
1087 }
1088
1089 // If the RHS is a constant, see if we can simplify it.
1090 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001091 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001093
Chris Lattnerd0883142009-10-11 22:22:13 +00001094 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1095 // are flipping are known to be set, then the xor is just resetting those
1096 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1097 // simplifying both of them.
1098 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1099 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1100 isa<ConstantInt>(I->getOperand(1)) &&
1101 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1102 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1103 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1104 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1105 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1106
1107 Constant *AndC =
1108 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1109 Instruction *NewAnd =
1110 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1111 InsertNewInstBefore(NewAnd, *I);
1112
1113 Constant *XorC =
1114 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1115 Instruction *NewXor =
1116 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1117 return InsertNewInstBefore(NewXor, *I);
1118 }
1119
1120
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 RHSKnownZero = KnownZeroOut;
1122 RHSKnownOne = KnownOneOut;
1123 break;
1124 }
1125 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1127 RHSKnownZero, RHSKnownOne, Depth+1) ||
1128 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 return I;
1131 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1132 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001133
1134 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001135 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1136 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001137 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001138
1139 // Only known if known in both the LHS and RHS.
1140 RHSKnownOne &= LHSKnownOne;
1141 RHSKnownZero &= LHSKnownZero;
1142 break;
1143 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001144 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 DemandedMask.zext(truncBf);
1146 RHSKnownZero.zext(truncBf);
1147 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001149 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 DemandedMask.trunc(BitWidth);
1152 RHSKnownZero.trunc(BitWidth);
1153 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 break;
1156 }
1157 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001158 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001159 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001160
1161 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1162 if (const VectorType *SrcVTy =
1163 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1164 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1165 // Don't touch a bitcast between vectors of different element counts.
1166 return false;
1167 } else
1168 // Don't touch a scalar-to-vector bitcast.
1169 return false;
1170 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1171 // Don't touch a vector-to-scalar bitcast.
1172 return false;
1173
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 return I;
1177 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001178 break;
1179 case Instruction::ZExt: {
1180 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001181 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001182
Zhou Shengd48653a2007-03-29 04:45:55 +00001183 DemandedMask.trunc(SrcBitWidth);
1184 RHSKnownZero.trunc(SrcBitWidth);
1185 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001187 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 DemandedMask.zext(BitWidth);
1190 RHSKnownZero.zext(BitWidth);
1191 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001194 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 break;
1196 }
1197 case Instruction::SExt: {
1198 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001199 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001200
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001202 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
Zhou Sheng01542f32007-03-29 02:26:30 +00001204 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 // If any of the sign extended bits are demanded, we know that the sign
1206 // bit is demanded.
1207 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001208 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001209
Zhou Shengd48653a2007-03-29 04:45:55 +00001210 InputDemandedBits.trunc(SrcBitWidth);
1211 RHSKnownZero.trunc(SrcBitWidth);
1212 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 InputDemandedBits.zext(BitWidth);
1217 RHSKnownZero.zext(BitWidth);
1218 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001219 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001220
1221 // If the sign bit of the input is known set or clear, then we know the
1222 // top bits of the result.
1223
1224 // If the input sign bit is known zero, or if the NewBits are not demanded
1225 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1229 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 }
1233 break;
1234 }
1235 case Instruction::Add: {
1236 // Figure out what the input bits are. If the top bits of the and result
1237 // are not demanded, then the add doesn't demand them from its input
1238 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001240
1241 // If there is a constant on the RHS, there are a variety of xformations
1242 // we can do.
1243 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1244 // If null, this should be simplified elsewhere. Some of the xforms here
1245 // won't work if the RHS is zero.
1246 if (RHS->isZero())
1247 break;
1248
1249 // If the top bit of the output is demanded, demand everything from the
1250 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001251 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001252
1253 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001257
1258 // If the RHS of the add has bits set that can't affect the input, reduce
1259 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001260 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001262
1263 // Avoid excess work.
1264 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1265 break;
1266
1267 // Turn it into OR if input bits are zero.
1268 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1269 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001270 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 }
1274
1275 // We can say something about the output known-zero and known-one bits,
1276 // depending on potential carries from the input constant and the
1277 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1278 // bits set and the RHS constant is 0x01001, then we know we have a known
1279 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1280
1281 // To compute this, we first compute the potential carry bits. These are
1282 // the bits which may be modified. I'm not aware of a better way to do
1283 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001285 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001286
1287 // Now that we know which bits have carries, compute the known-1/0 sets.
1288
1289 // Bits are known one if they are known zero in one operand and one in the
1290 // other, and there is no input carry.
1291 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1292 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1293
1294 // Bits are known zero if they are known zero in both operands and there
1295 // is no input carry.
1296 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1297 } else {
1298 // If the high-bits of this ADD are not demanded, then it does not demand
1299 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001300 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 // Right fill the mask of bits for this ADD to demand the most
1302 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001303 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1305 LHSKnownZero, LHSKnownOne, Depth+1) ||
1306 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 }
1310 }
1311 break;
1312 }
1313 case Instruction::Sub:
1314 // If the high-bits of this SUB are not demanded, then it does not demand
1315 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 // Right fill the mask of bits for this SUB to demand the most
1318 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001319 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001320 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1322 LHSKnownZero, LHSKnownOne, Depth+1) ||
1323 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001327 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1328 // the known zeros and ones.
1329 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 break;
1331 case Instruction::Shl:
1332 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001333 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001334 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return I;
1338 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 RHSKnownZero <<= ShiftAmt;
1340 RHSKnownOne <<= ShiftAmt;
1341 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001342 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001343 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 }
1345 break;
1346 case Instruction::LShr:
1347 // For a logical shift right
1348 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001349 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001350
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001352 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001354 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001355 return I;
1356 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001357 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1358 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001359 if (ShiftAmt) {
1360 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001361 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001362 RHSKnownZero |= HighBits; // high bits known zero.
1363 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001364 }
1365 break;
1366 case Instruction::AShr:
1367 // If this is an arithmetic shift right and only the low-bit is set, we can
1368 // always convert this into a logical shr, even if the shift amount is
1369 // variable. The low bit of the shift cannot be an input sign bit unless
1370 // the shift amount is >= the size of the datatype, which is undefined.
1371 if (DemandedMask == 1) {
1372 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001373 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001374 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001375 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001376 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001377
1378 // If the sign bit is the only bit demanded by this ashr, then there is no
1379 // need to do it, the shift doesn't change the high bit.
1380 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001381 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001382
1383 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001384 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001385
Reid Spencer8cb68342007-03-12 17:25:59 +00001386 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001387 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001388 // If any of the "high bits" are demanded, we should set the sign bit as
1389 // demanded.
1390 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1391 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001392 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001393 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001394 return I;
1395 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001396 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001397 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1399 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1400
1401 // Handle the sign bits.
1402 APInt SignBit(APInt::getSignBit(BitWidth));
1403 // Adjust to where it is now in the mask.
1404 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1405
1406 // If the input sign bit is known to be zero, or if none of the top bits
1407 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001408 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001409 (HighBits & ~DemandedMask) == HighBits) {
1410 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001411 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001413 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001414 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1415 RHSKnownOne |= HighBits;
1416 }
1417 }
1418 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001419 case Instruction::SRem:
1420 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001421 APInt RA = Rem->getValue().abs();
1422 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001423 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001424 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001425
Nick Lewycky8e394322008-11-02 02:41:50 +00001426 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001427 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001428 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001429 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001430 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001431
1432 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1433 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001434
1435 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001436
Chris Lattner886ab6c2009-01-31 08:15:18 +00001437 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001438 }
1439 }
1440 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001441 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001442 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1443 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001444 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1445 KnownZero2, KnownOne2, Depth+1) ||
1446 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001447 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001448 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001449
Chris Lattner455e9ab2009-01-21 18:09:24 +00001450 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001451 Leaders = std::max(Leaders,
1452 KnownZero2.countLeadingOnes());
1453 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001454 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001455 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001456 case Instruction::Call:
1457 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1458 switch (II->getIntrinsicID()) {
1459 default: break;
1460 case Intrinsic::bswap: {
1461 // If the only bits demanded come from one byte of the bswap result,
1462 // just shift the input byte into position to eliminate the bswap.
1463 unsigned NLZ = DemandedMask.countLeadingZeros();
1464 unsigned NTZ = DemandedMask.countTrailingZeros();
1465
1466 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1467 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1468 // have 14 leading zeros, round to 8.
1469 NLZ &= ~7;
1470 NTZ &= ~7;
1471 // If we need exactly one byte, we can do this transformation.
1472 if (BitWidth-NLZ-NTZ == 8) {
1473 unsigned ResultBit = NTZ;
1474 unsigned InputBit = BitWidth-NTZ-8;
1475
1476 // Replace this with either a left or right shift to get the byte into
1477 // the right place.
1478 Instruction *NewVal;
1479 if (InputBit > ResultBit)
1480 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001481 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001482 else
1483 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001484 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001485 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001486 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001487 }
1488
1489 // TODO: Could compute known zero/one bits based on the input.
1490 break;
1491 }
1492 }
1493 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001494 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001495 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001496 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001497
1498 // If the client is only demanding bits that we know, return the known
1499 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001500 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1501 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001502 return false;
1503}
1504
Chris Lattner867b99f2006-10-05 06:55:50 +00001505
Mon P Wangaeb06d22008-11-10 04:46:22 +00001506/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001507/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001508/// actually used by the caller. This method analyzes which elements of the
1509/// operand are undef and returns that information in UndefElts.
1510///
1511/// If the information about demanded elements can be used to simplify the
1512/// operation, the operation is simplified, then the resultant value is
1513/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001514Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1515 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001516 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001517 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001518 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001519 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001520
1521 if (isa<UndefValue>(V)) {
1522 // If the entire vector is undefined, just return this info.
1523 UndefElts = EltMask;
1524 return 0;
1525 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1526 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001527 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001528 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001529
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001531 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1532 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001533 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001534
1535 std::vector<Constant*> Elts;
1536 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001537 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001539 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001540 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1541 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001542 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001543 } else { // Otherwise, defined.
1544 Elts.push_back(CP->getOperand(i));
1545 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001546
Chris Lattner867b99f2006-10-05 06:55:50 +00001547 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001548 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001549 return NewCP != CP ? NewCP : 0;
1550 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001551 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001552 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001553
1554 // Check if this is identity. If so, return 0 since we are not simplifying
1555 // anything.
1556 if (DemandedElts == ((1ULL << VWidth) -1))
1557 return 0;
1558
Reid Spencer9d6565a2007-02-15 02:26:10 +00001559 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001560 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001561 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001562 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001563 for (unsigned i = 0; i != VWidth; ++i) {
1564 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1565 Elts.push_back(Elt);
1566 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001567 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001568 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001569 }
1570
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 // Limit search depth.
1572 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001573 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574
1575 // If multiple users are using the root value, procede with
1576 // simplification conservatively assuming that all elements
1577 // are needed.
1578 if (!V->hasOneUse()) {
1579 // Quit if we find multiple users of a non-root value though.
1580 // They'll be handled when it's their turn to be visited by
1581 // the main instcombine process.
1582 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001583 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001584 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585
1586 // Conservatively assume that all elements are needed.
1587 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001588 }
1589
1590 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001591 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001592
1593 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001594 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001595 Value *TmpV;
1596 switch (I->getOpcode()) {
1597 default: break;
1598
1599 case Instruction::InsertElement: {
1600 // If this is a variable index, we don't know which element it overwrites.
1601 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001602 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001603 if (Idx == 0) {
1604 // Note that we can't propagate undef elt info, because we don't know
1605 // which elt is getting updated.
1606 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1607 UndefElts2, Depth+1);
1608 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1609 break;
1610 }
1611
1612 // If this is inserting an element that isn't demanded, remove this
1613 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001614 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001615 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1616 Worklist.Add(I);
1617 return I->getOperand(0);
1618 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001619
1620 // Otherwise, the element inserted overwrites whatever was there, so the
1621 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001622 APInt DemandedElts2 = DemandedElts;
1623 DemandedElts2.clear(IdxNo);
1624 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001625 UndefElts, Depth+1);
1626 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1627
1628 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001629 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001630 break;
1631 }
1632 case Instruction::ShuffleVector: {
1633 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001634 uint64_t LHSVWidth =
1635 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001636 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001637 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001638 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001639 unsigned MaskVal = Shuffle->getMaskValue(i);
1640 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001641 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001642 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001643 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001644 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001645 else
Evan Cheng388df622009-02-03 10:05:09 +00001646 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001647 }
1648 }
1649 }
1650
Nate Begeman7b254672009-02-11 22:36:25 +00001651 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001653 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001654 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1655
Nate Begeman7b254672009-02-11 22:36:25 +00001656 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001657 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1658 UndefElts3, Depth+1);
1659 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1660
1661 bool NewUndefElts = false;
1662 for (unsigned i = 0; i < VWidth; i++) {
1663 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001664 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001665 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001666 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001667 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001668 NewUndefElts = true;
1669 UndefElts.set(i);
1670 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001671 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001672 if (UndefElts3[MaskVal - LHSVWidth]) {
1673 NewUndefElts = true;
1674 UndefElts.set(i);
1675 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001676 }
1677 }
1678
1679 if (NewUndefElts) {
1680 // Add additional discovered undefs.
1681 std::vector<Constant*> Elts;
1682 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001683 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001684 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001685 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001686 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001687 Shuffle->getMaskValue(i)));
1688 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001689 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001690 MadeChange = true;
1691 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001692 break;
1693 }
Chris Lattner69878332007-04-14 22:29:23 +00001694 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001695 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001696 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1697 if (!VTy) break;
1698 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001699 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001700 unsigned Ratio;
1701
1702 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001703 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001704 // elements as are demanded of us.
1705 Ratio = 1;
1706 InputDemandedElts = DemandedElts;
1707 } else if (VWidth > InVWidth) {
1708 // Untested so far.
1709 break;
1710
1711 // If there are more elements in the result than there are in the source,
1712 // then an input element is live if any of the corresponding output
1713 // elements are live.
1714 Ratio = VWidth/InVWidth;
1715 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001716 if (DemandedElts[OutIdx])
1717 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001718 }
1719 } else {
1720 // Untested so far.
1721 break;
1722
1723 // If there are more elements in the source than there are in the result,
1724 // then an input element is live if the corresponding output element is
1725 // live.
1726 Ratio = InVWidth/VWidth;
1727 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001728 if (DemandedElts[InIdx/Ratio])
1729 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001730 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001731
Chris Lattner69878332007-04-14 22:29:23 +00001732 // div/rem demand all inputs, because they don't want divide by zero.
1733 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1734 UndefElts2, Depth+1);
1735 if (TmpV) {
1736 I->setOperand(0, TmpV);
1737 MadeChange = true;
1738 }
1739
1740 UndefElts = UndefElts2;
1741 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001742 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001743 // If there are more elements in the result than there are in the source,
1744 // then an output element is undef if the corresponding input element is
1745 // undef.
1746 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001747 if (UndefElts2[OutIdx/Ratio])
1748 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001749 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001750 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001751 // If there are more elements in the source than there are in the result,
1752 // then a result element is undef if all of the corresponding input
1753 // elements are undef.
1754 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1755 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001756 if (!UndefElts2[InIdx]) // Not undef?
1757 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001758 }
1759 break;
1760 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001761 case Instruction::And:
1762 case Instruction::Or:
1763 case Instruction::Xor:
1764 case Instruction::Add:
1765 case Instruction::Sub:
1766 case Instruction::Mul:
1767 // div/rem demand all inputs, because they don't want divide by zero.
1768 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1769 UndefElts, Depth+1);
1770 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1771 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1772 UndefElts2, Depth+1);
1773 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1774
1775 // Output elements are undefined if both are undefined. Consider things
1776 // like undef&0. The result is known zero, not undef.
1777 UndefElts &= UndefElts2;
1778 break;
1779
1780 case Instruction::Call: {
1781 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1782 if (!II) break;
1783 switch (II->getIntrinsicID()) {
1784 default: break;
1785
1786 // Binary vector operations that work column-wise. A dest element is a
1787 // function of the corresponding input elements from the two inputs.
1788 case Intrinsic::x86_sse_sub_ss:
1789 case Intrinsic::x86_sse_mul_ss:
1790 case Intrinsic::x86_sse_min_ss:
1791 case Intrinsic::x86_sse_max_ss:
1792 case Intrinsic::x86_sse2_sub_sd:
1793 case Intrinsic::x86_sse2_mul_sd:
1794 case Intrinsic::x86_sse2_min_sd:
1795 case Intrinsic::x86_sse2_max_sd:
1796 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1797 UndefElts, Depth+1);
1798 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1799 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1800 UndefElts2, Depth+1);
1801 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1802
1803 // If only the low elt is demanded and this is a scalarizable intrinsic,
1804 // scalarize it now.
1805 if (DemandedElts == 1) {
1806 switch (II->getIntrinsicID()) {
1807 default: break;
1808 case Intrinsic::x86_sse_sub_ss:
1809 case Intrinsic::x86_sse_mul_ss:
1810 case Intrinsic::x86_sse2_sub_sd:
1811 case Intrinsic::x86_sse2_mul_sd:
1812 // TODO: Lower MIN/MAX/ABS/etc
1813 Value *LHS = II->getOperand(1);
1814 Value *RHS = II->getOperand(2);
1815 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001816 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001817 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001818 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001819 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001820
1821 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001822 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001823 case Intrinsic::x86_sse_sub_ss:
1824 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001825 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001826 II->getName()), *II);
1827 break;
1828 case Intrinsic::x86_sse_mul_ss:
1829 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001830 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001831 II->getName()), *II);
1832 break;
1833 }
1834
1835 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001836 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001837 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001838 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001839 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 return New;
1841 }
1842 }
1843
1844 // Output elements are undefined if both are undefined. Consider things
1845 // like undef&0. The result is known zero, not undef.
1846 UndefElts &= UndefElts2;
1847 break;
1848 }
1849 break;
1850 }
1851 }
1852 return MadeChange ? I : 0;
1853}
1854
Dan Gohman45b4e482008-05-19 22:14:15 +00001855
Chris Lattner564a7272003-08-13 19:01:45 +00001856/// AssociativeOpt - Perform an optimization on an associative operator. This
1857/// function is designed to check a chain of associative operators for a
1858/// potential to apply a certain optimization. Since the optimization may be
1859/// applicable if the expression was reassociated, this checks the chain, then
1860/// reassociates the expression as necessary to expose the optimization
1861/// opportunity. This makes use of a special Functor, which must define
1862/// 'shouldApply' and 'apply' methods.
1863///
1864template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001865static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001866 unsigned Opcode = Root.getOpcode();
1867 Value *LHS = Root.getOperand(0);
1868
1869 // Quick check, see if the immediate LHS matches...
1870 if (F.shouldApply(LHS))
1871 return F.apply(Root);
1872
1873 // Otherwise, if the LHS is not of the same opcode as the root, return.
1874 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001875 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001876 // Should we apply this transform to the RHS?
1877 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1878
1879 // If not to the RHS, check to see if we should apply to the LHS...
1880 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1881 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1882 ShouldApply = true;
1883 }
1884
1885 // If the functor wants to apply the optimization to the RHS of LHSI,
1886 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1887 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001888 // Now all of the instructions are in the current basic block, go ahead
1889 // and perform the reassociation.
1890 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1891
1892 // First move the selected RHS to the LHS of the root...
1893 Root.setOperand(0, LHSI->getOperand(1));
1894
1895 // Make what used to be the LHS of the root be the user of the root...
1896 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001897 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001898 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001899 return 0;
1900 }
Chris Lattner65725312004-04-16 18:08:07 +00001901 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001902 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001903 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001904 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001905 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001906
1907 // Now propagate the ExtraOperand down the chain of instructions until we
1908 // get to LHSI.
1909 while (TmpLHSI != LHSI) {
1910 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001911 // Move the instruction to immediately before the chain we are
1912 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001913 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001914 ARI = NextLHSI;
1915
Chris Lattner564a7272003-08-13 19:01:45 +00001916 Value *NextOp = NextLHSI->getOperand(1);
1917 NextLHSI->setOperand(1, ExtraOperand);
1918 TmpLHSI = NextLHSI;
1919 ExtraOperand = NextOp;
1920 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001921
Chris Lattner564a7272003-08-13 19:01:45 +00001922 // Now that the instructions are reassociated, have the functor perform
1923 // the transformation...
1924 return F.apply(Root);
1925 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001926
Chris Lattner564a7272003-08-13 19:01:45 +00001927 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1928 }
1929 return 0;
1930}
1931
Dan Gohman844731a2008-05-13 00:00:25 +00001932namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001933
Nick Lewycky02d639f2008-05-23 04:34:58 +00001934// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001935struct AddRHS {
1936 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001937 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001938 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1939 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001940 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001941 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001942 }
1943};
1944
1945// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1946// iff C1&C2 == 0
1947struct AddMaskingAnd {
1948 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001949 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001950 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001951 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001952 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001953 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001954 }
1955 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001956 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001957 }
1958};
1959
Dan Gohman844731a2008-05-13 00:00:25 +00001960}
1961
Chris Lattner6e7ba452005-01-01 16:22:27 +00001962static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001963 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001964 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001965 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001966
Chris Lattner2eefe512004-04-09 19:05:30 +00001967 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001968 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1969 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001970
Chris Lattner2eefe512004-04-09 19:05:30 +00001971 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1972 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001973 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1974 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001975 }
1976
1977 Value *Op0 = SO, *Op1 = ConstOperand;
1978 if (!ConstIsRHS)
1979 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001980
Chris Lattner6e7ba452005-01-01 16:22:27 +00001981 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001982 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1983 SO->getName()+".op");
1984 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1985 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1986 SO->getName()+".cmp");
1987 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1988 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1989 SO->getName()+".cmp");
1990 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001991}
1992
1993// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1994// constant as the other operand, try to fold the binary operator into the
1995// select arguments. This also works for Cast instructions, which obviously do
1996// not have a second operand.
1997static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1998 InstCombiner *IC) {
1999 // Don't modify shared select instructions
2000 if (!SI->hasOneUse()) return 0;
2001 Value *TV = SI->getOperand(1);
2002 Value *FV = SI->getOperand(2);
2003
2004 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002005 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002006 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002007
Chris Lattner6e7ba452005-01-01 16:22:27 +00002008 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2009 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2010
Gabor Greif051a9502008-04-06 20:25:17 +00002011 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2012 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002013 }
2014 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002015}
2016
Chris Lattner4e998b22004-09-29 05:07:12 +00002017
Chris Lattner5d1704d2009-09-27 19:57:57 +00002018/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2019/// has a PHI node as operand #0, see if we can fold the instruction into the
2020/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002021///
2022/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2023/// that would normally be unprofitable because they strongly encourage jump
2024/// threading.
2025Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2026 bool AllowAggressive) {
2027 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002028 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002029 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002030 if (NumPHIValues == 0 ||
2031 // We normally only transform phis with a single use, unless we're trying
2032 // hard to make jump threading happen.
2033 (!PN->hasOneUse() && !AllowAggressive))
2034 return 0;
2035
2036
Chris Lattner5d1704d2009-09-27 19:57:57 +00002037 // Check to see if all of the operands of the PHI are simple constants
2038 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002039 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2040 // bail out. We don't do arbitrary constant expressions here because moving
2041 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002042 BasicBlock *NonConstBB = 0;
2043 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002044 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2045 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002046 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002047 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002048 NonConstBB = PN->getIncomingBlock(i);
2049
2050 // If the incoming non-constant value is in I's block, we have an infinite
2051 // loop.
2052 if (NonConstBB == I.getParent())
2053 return 0;
2054 }
2055
2056 // If there is exactly one non-constant value, we can insert a copy of the
2057 // operation in that block. However, if this is a critical edge, we would be
2058 // inserting the computation one some other paths (e.g. inside a loop). Only
2059 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002060 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002061 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2062 if (!BI || !BI->isUnconditional()) return 0;
2063 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002064
2065 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002066 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002067 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002068 InsertNewInstBefore(NewPN, *PN);
2069 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002070
2071 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002072 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2073 // We only currently try to fold the condition of a select when it is a phi,
2074 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002075 Value *TrueV = SI->getTrueValue();
2076 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002077 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002078 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002079 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002080 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2081 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002082 Value *InV = 0;
2083 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002084 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002085 } else {
2086 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002087 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2088 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002089 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002090 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002091 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002092 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002093 }
2094 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002095 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002096 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002097 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002098 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002099 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002100 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002101 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002102 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002103 } else {
2104 assert(PN->getIncomingBlock(i) == NonConstBB);
2105 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002106 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002107 PN->getIncomingValue(i), C, "phitmp",
2108 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002109 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002110 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002111 CI->getPredicate(),
2112 PN->getIncomingValue(i), C, "phitmp",
2113 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002114 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002115 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002116
2117 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002118 }
2119 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002120 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002121 } else {
2122 CastInst *CI = cast<CastInst>(&I);
2123 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002124 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002125 Value *InV;
2126 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002127 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002128 } else {
2129 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002130 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002131 I.getType(), "phitmp",
2132 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002133 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002134 }
2135 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002136 }
2137 }
2138 return ReplaceInstUsesWith(I, NewPN);
2139}
2140
Chris Lattner2454a2e2008-01-29 06:52:45 +00002141
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002142/// WillNotOverflowSignedAdd - Return true if we can prove that:
2143/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2144/// This basically requires proving that the add in the original type would not
2145/// overflow to change the sign bit or have a carry out.
2146bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2147 // There are different heuristics we can use for this. Here are some simple
2148 // ones.
2149
2150 // Add has the property that adding any two 2's complement numbers can only
2151 // have one carry bit which can change a sign. As such, if LHS and RHS each
2152 // have at least two sign bits, we know that the addition of the two values will
2153 // sign extend fine.
2154 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2155 return true;
2156
2157
2158 // If one of the operands only has one non-zero bit, and if the other operand
2159 // has a known-zero bit in a more significant place than it (not including the
2160 // sign bit) the ripple may go up to and fill the zero, but won't change the
2161 // sign. For example, (X & ~4) + 1.
2162
2163 // TODO: Implement.
2164
2165 return false;
2166}
2167
Chris Lattner2454a2e2008-01-29 06:52:45 +00002168
Chris Lattner7e708292002-06-25 16:13:24 +00002169Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002170 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002171 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002172
Chris Lattner66331a42004-04-10 22:01:55 +00002173 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002174 // X + undef -> undef
2175 if (isa<UndefValue>(RHS))
2176 return ReplaceInstUsesWith(I, RHS);
2177
Chris Lattner66331a42004-04-10 22:01:55 +00002178 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002179 if (RHSC->isNullValue())
2180 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002181
Chris Lattner66331a42004-04-10 22:01:55 +00002182 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002183 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002184 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002185 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002186 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002187 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002188
2189 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2190 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002191 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002192 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002193
Eli Friedman709b33d2009-07-13 22:27:52 +00002194 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002195 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002196 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002197 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002198 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002199
2200 if (isa<PHINode>(LHS))
2201 if (Instruction *NV = FoldOpIntoPhi(I))
2202 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002203
Chris Lattner4f637d42006-01-06 17:59:59 +00002204 ConstantInt *XorRHS = 0;
2205 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002206 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002207 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002208 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002209 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002210
Zhou Sheng4351c642007-04-02 08:20:41 +00002211 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002212 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2213 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002214 do {
2215 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002216 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2217 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002218 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2219 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002220 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002221 if (!MaskedValueIsZero(XorLHS,
2222 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002223 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002224 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002225 }
2226 }
2227 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002228 C0080Val = APIntOps::lshr(C0080Val, Size);
2229 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2230 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002231
Reid Spencer35c38852007-03-28 01:36:16 +00002232 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002233 // with funny bit widths then this switch statement should be removed. It
2234 // is just here to get the size of the "middle" type back up to something
2235 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002236 const Type *MiddleType = 0;
2237 switch (Size) {
2238 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002239 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2240 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2241 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002242 }
2243 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002244 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002245 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002246 }
2247 }
Chris Lattner66331a42004-04-10 22:01:55 +00002248 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002249
Owen Anderson1d0be152009-08-13 21:58:54 +00002250 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002251 return BinaryOperator::CreateXor(LHS, RHS);
2252
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002253 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002254 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002255 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002256 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002257
2258 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2259 if (RHSI->getOpcode() == Instruction::Sub)
2260 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2261 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2262 }
2263 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2264 if (LHSI->getOpcode() == Instruction::Sub)
2265 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2266 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2267 }
Robert Bocchino71698282004-07-27 21:02:21 +00002268 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002269
Chris Lattner5c4afb92002-05-08 22:46:53 +00002270 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002271 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002272 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002273 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002274 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002275 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002276 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002277 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002278 }
2279
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002280 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002281 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002282
2283 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002284 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002285 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002286 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002287
Misha Brukmanfd939082005-04-21 23:48:37 +00002288
Chris Lattner50af16a2004-11-13 19:50:12 +00002289 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002290 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002291 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002292 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002293
2294 // X*C1 + X*C2 --> X * (C1+C2)
2295 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002296 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002297 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002298 }
2299
2300 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002301 if (dyn_castFoldableMul(RHS, C2) == LHS)
2302 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002303
Chris Lattnere617c9e2007-01-05 02:17:46 +00002304 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002305 if (dyn_castNotVal(LHS) == RHS ||
2306 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002307 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002308
Chris Lattnerad3448c2003-02-18 19:57:07 +00002309
Chris Lattner564a7272003-08-13 19:01:45 +00002310 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002311 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2312 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002313 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002314
2315 // A+B --> A|B iff A and B have no bits set in common.
2316 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2317 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2318 APInt LHSKnownOne(IT->getBitWidth(), 0);
2319 APInt LHSKnownZero(IT->getBitWidth(), 0);
2320 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2321 if (LHSKnownZero != 0) {
2322 APInt RHSKnownOne(IT->getBitWidth(), 0);
2323 APInt RHSKnownZero(IT->getBitWidth(), 0);
2324 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2325
2326 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002327 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002328 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002329 }
2330 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002331
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002332 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002333 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002334 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002335 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2336 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002337 if (W != Y) {
2338 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002339 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002340 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002341 std::swap(W, X);
2342 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002343 std::swap(Y, Z);
2344 std::swap(W, X);
2345 }
2346 }
2347
2348 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002349 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002350 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002351 }
2352 }
2353 }
2354
Chris Lattner6b032052003-10-02 15:11:26 +00002355 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002356 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002357 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002358 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002359
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002360 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002361 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002362 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002363 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002364 if (Anded == CRHS) {
2365 // See if all bits from the first bit set in the Add RHS up are included
2366 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002367 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002368
2369 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002370 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002371
2372 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002373 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002374
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002375 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2376 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002377 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002378 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002379 }
2380 }
2381 }
2382
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002383 // Try to fold constant add into select arguments.
2384 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002385 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002386 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002387 }
2388
Chris Lattner42790482007-12-20 01:56:58 +00002389 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002390 {
2391 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002392 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002393 if (!SI) {
2394 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002395 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002396 }
Chris Lattner42790482007-12-20 01:56:58 +00002397 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002398 Value *TV = SI->getTrueValue();
2399 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002400 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002401
2402 // Can we fold the add into the argument of the select?
2403 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002404 if (match(FV, m_Zero()) &&
2405 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002406 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002407 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002408 if (match(TV, m_Zero()) &&
2409 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002410 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002411 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002412 }
2413 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002414
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002415 // Check for (add (sext x), y), see if we can merge this into an
2416 // integer add followed by a sext.
2417 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2418 // (add (sext x), cst) --> (sext (add x, cst'))
2419 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2420 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002421 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002422 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002423 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002424 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2425 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002426 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2427 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002428 return new SExtInst(NewAdd, I.getType());
2429 }
2430 }
2431
2432 // (add (sext x), (sext y)) --> (sext (add int x, y))
2433 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2434 // Only do this if x/y have the same type, if at last one of them has a
2435 // single use (so we don't increase the number of sexts), and if the
2436 // integer add will not overflow.
2437 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2438 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2439 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0))) {
2441 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002442 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2443 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002444 return new SExtInst(NewAdd, I.getType());
2445 }
2446 }
2447 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002448
2449 return Changed ? &I : 0;
2450}
2451
2452Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2453 bool Changed = SimplifyCommutative(I);
2454 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2455
2456 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2457 // X + 0 --> X
2458 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002459 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002460 (I.getType())->getValueAPF()))
2461 return ReplaceInstUsesWith(I, LHS);
2462 }
2463
2464 if (isa<PHINode>(LHS))
2465 if (Instruction *NV = FoldOpIntoPhi(I))
2466 return NV;
2467 }
2468
2469 // -A + B --> B - A
2470 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002471 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002472 return BinaryOperator::CreateFSub(RHS, LHSV);
2473
2474 // A + -B --> A - B
2475 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002476 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002477 return BinaryOperator::CreateFSub(LHS, V);
2478
2479 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2480 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2481 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2482 return ReplaceInstUsesWith(I, LHS);
2483
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002484 // Check for (add double (sitofp x), y), see if we can merge this into an
2485 // integer add followed by a promotion.
2486 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2487 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2488 // ... if the constant fits in the integer value. This is useful for things
2489 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2490 // requires a constant pool load, and generally allows the add to be better
2491 // instcombined.
2492 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2493 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002494 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002495 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002496 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002497 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2498 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002499 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2500 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002501 return new SIToFPInst(NewAdd, I.getType());
2502 }
2503 }
2504
2505 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2506 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2507 // Only do this if x/y have the same type, if at last one of them has a
2508 // single use (so we don't increase the number of int->fp conversions),
2509 // and if the integer add will not overflow.
2510 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2511 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2512 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2513 RHSConv->getOperand(0))) {
2514 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002515 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002516 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002517 return new SIToFPInst(NewAdd, I.getType());
2518 }
2519 }
2520 }
2521
Chris Lattner7e708292002-06-25 16:13:24 +00002522 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002523}
2524
Chris Lattner092543c2009-11-04 08:05:20 +00002525
2526/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2527/// code necessary to compute the offset from the base pointer (without adding
2528/// in the base pointer). Return the result as a signed integer of intptr size.
2529static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2530 TargetData &TD = *IC.getTargetData();
2531 gep_type_iterator GTI = gep_type_begin(GEP);
2532 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2533 Value *Result = Constant::getNullValue(IntPtrTy);
2534
2535 // Build a mask for high order bits.
2536 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2537 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2538
2539 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2540 ++i, ++GTI) {
2541 Value *Op = *i;
2542 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2543 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2544 if (OpC->isZero()) continue;
2545
2546 // Handle a struct index, which adds its field offset to the pointer.
2547 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2548 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2549
2550 Result = IC.Builder->CreateAdd(Result,
2551 ConstantInt::get(IntPtrTy, Size),
2552 GEP->getName()+".offs");
2553 continue;
2554 }
2555
2556 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2557 Constant *OC =
2558 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2559 Scale = ConstantExpr::getMul(OC, Scale);
2560 // Emit an add instruction.
2561 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2562 continue;
2563 }
2564 // Convert to correct type.
2565 if (Op->getType() != IntPtrTy)
2566 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2567 if (Size != 1) {
2568 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2569 // We'll let instcombine(mul) convert this to a shl if possible.
2570 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2571 }
2572
2573 // Emit an add instruction.
2574 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2575 }
2576 return Result;
2577}
2578
2579
2580/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2581/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2582/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2583/// be complex, and scales are involved. The above expression would also be
2584/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2585/// This later form is less amenable to optimization though, and we are allowed
2586/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2587///
2588/// If we can't emit an optimized form for this expression, this returns null.
2589///
2590static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2591 InstCombiner &IC) {
2592 TargetData &TD = *IC.getTargetData();
2593 gep_type_iterator GTI = gep_type_begin(GEP);
2594
2595 // Check to see if this gep only has a single variable index. If so, and if
2596 // any constant indices are a multiple of its scale, then we can compute this
2597 // in terms of the scale of the variable index. For example, if the GEP
2598 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2599 // because the expression will cross zero at the same point.
2600 unsigned i, e = GEP->getNumOperands();
2601 int64_t Offset = 0;
2602 for (i = 1; i != e; ++i, ++GTI) {
2603 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2604 // Compute the aggregate offset of constant indices.
2605 if (CI->isZero()) continue;
2606
2607 // Handle a struct index, which adds its field offset to the pointer.
2608 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2609 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2610 } else {
2611 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2612 Offset += Size*CI->getSExtValue();
2613 }
2614 } else {
2615 // Found our variable index.
2616 break;
2617 }
2618 }
2619
2620 // If there are no variable indices, we must have a constant offset, just
2621 // evaluate it the general way.
2622 if (i == e) return 0;
2623
2624 Value *VariableIdx = GEP->getOperand(i);
2625 // Determine the scale factor of the variable element. For example, this is
2626 // 4 if the variable index is into an array of i32.
2627 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2628
2629 // Verify that there are no other variable indices. If so, emit the hard way.
2630 for (++i, ++GTI; i != e; ++i, ++GTI) {
2631 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2632 if (!CI) return 0;
2633
2634 // Compute the aggregate offset of constant indices.
2635 if (CI->isZero()) continue;
2636
2637 // Handle a struct index, which adds its field offset to the pointer.
2638 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2639 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2640 } else {
2641 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2642 Offset += Size*CI->getSExtValue();
2643 }
2644 }
2645
2646 // Okay, we know we have a single variable index, which must be a
2647 // pointer/array/vector index. If there is no offset, life is simple, return
2648 // the index.
2649 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2650 if (Offset == 0) {
2651 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2652 // we don't need to bother extending: the extension won't affect where the
2653 // computation crosses zero.
2654 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2655 VariableIdx = new TruncInst(VariableIdx,
2656 TD.getIntPtrType(VariableIdx->getContext()),
2657 VariableIdx->getName(), &I);
2658 return VariableIdx;
2659 }
2660
2661 // Otherwise, there is an index. The computation we will do will be modulo
2662 // the pointer size, so get it.
2663 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2664
2665 Offset &= PtrSizeMask;
2666 VariableScale &= PtrSizeMask;
2667
2668 // To do this transformation, any constant index must be a multiple of the
2669 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2670 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2671 // multiple of the variable scale.
2672 int64_t NewOffs = Offset / (int64_t)VariableScale;
2673 if (Offset != NewOffs*(int64_t)VariableScale)
2674 return 0;
2675
2676 // Okay, we can do this evaluation. Start by converting the index to intptr.
2677 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2678 if (VariableIdx->getType() != IntPtrTy)
2679 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2680 true /*SExt*/,
2681 VariableIdx->getName(), &I);
2682 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2683 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2684}
2685
2686
2687/// Optimize pointer differences into the same array into a size. Consider:
2688/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2689/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2690///
2691Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2692 const Type *Ty) {
2693 assert(TD && "Must have target data info for this");
2694
2695 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2696 // this.
2697 bool Swapped;
2698 GetElementPtrInst *GEP;
2699
2700 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2701 GEP->getOperand(0) == RHS)
2702 Swapped = false;
2703 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2704 GEP->getOperand(0) == LHS)
2705 Swapped = true;
2706 else
2707 return 0;
2708
2709 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2710
2711 // Emit the offset of the GEP and an intptr_t.
2712 Value *Result = EmitGEPOffset(GEP, *this);
2713
2714 // If we have p - gep(p, ...) then we have to negate the result.
2715 if (Swapped)
2716 Result = Builder->CreateNeg(Result, "diff.neg");
2717
2718 return Builder->CreateIntCast(Result, Ty, true);
2719}
2720
2721
Chris Lattner7e708292002-06-25 16:13:24 +00002722Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002723 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002724
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002725 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002726 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002727
Chris Lattner092543c2009-11-04 08:05:20 +00002728 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohman186a6362009-08-12 16:04:34 +00002729 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002730 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002731
Chris Lattnere87597f2004-10-16 18:11:37 +00002732 if (isa<UndefValue>(Op0))
2733 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2734 if (isa<UndefValue>(Op1))
2735 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002736 if (I.getType() == Type::getInt1Ty(*Context))
2737 return BinaryOperator::CreateXor(Op0, Op1);
2738
Chris Lattnerd65460f2003-11-05 01:06:05 +00002739 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002740 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002741 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002742 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002743
Chris Lattnerd65460f2003-11-05 01:06:05 +00002744 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002745 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002746 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002747 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002748
Chris Lattner76b7a062007-01-15 07:02:54 +00002749 // -(X >>u 31) -> (X >>s 31)
2750 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002751 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002752 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002753 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002754 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002755 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002756 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002757 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002758 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002759 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002760 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002761 }
2762 }
Chris Lattner092543c2009-11-04 08:05:20 +00002763 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002764 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2765 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002766 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002767 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002768 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002769 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002770 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002771 }
2772 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002773 }
2774 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002775 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002776
2777 // Try to fold constant sub into select arguments.
2778 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002779 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002780 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002781
2782 // C - zext(bool) -> bool ? C - 1 : C
2783 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002784 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002785 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002786 }
2787
Chris Lattner43d84d62005-04-07 16:15:25 +00002788 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002789 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002790 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002791 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002792 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002793 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002794 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002795 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002796 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2797 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2798 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002799 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002800 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002801 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002802 }
2803
Chris Lattnerfd059242003-10-15 16:48:29 +00002804 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002805 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2806 // is not used by anyone else...
2807 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002808 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002809 // Swap the two operands of the subexpr...
2810 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2811 Op1I->setOperand(0, IIOp1);
2812 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002813
Chris Lattnera2881962003-02-18 19:28:33 +00002814 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002815 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002816 }
2817
2818 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2819 //
2820 if (Op1I->getOpcode() == Instruction::And &&
2821 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2822 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2823
Chris Lattner74381062009-08-30 07:44:24 +00002824 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002825 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002826 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002827
Reid Spencerac5209e2006-10-16 23:08:08 +00002828 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002829 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002830 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002831 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002832 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002833 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002834 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002835
Chris Lattnerad3448c2003-02-18 19:57:07 +00002836 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002837 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002838 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002839 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002840 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002841 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002842 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002843 }
Chris Lattner40371712002-05-09 01:29:19 +00002844 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002845 }
Chris Lattnera2881962003-02-18 19:28:33 +00002846
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002847 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2848 if (Op0I->getOpcode() == Instruction::Add) {
2849 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2850 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2851 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2852 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2853 } else if (Op0I->getOpcode() == Instruction::Sub) {
2854 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002855 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002856 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002857 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002858 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002859
Chris Lattner50af16a2004-11-13 19:50:12 +00002860 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002861 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002862 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002863 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002864
Chris Lattner50af16a2004-11-13 19:50:12 +00002865 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002866 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002867 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002868 }
Chris Lattner092543c2009-11-04 08:05:20 +00002869
2870 // Optimize pointer differences into the same array into a size. Consider:
2871 // &A[10] - &A[0]: we should compile this to "10".
2872 if (TD) {
2873 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2874 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2875 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2876 RHS->getOperand(0),
2877 I.getType()))
2878 return ReplaceInstUsesWith(I, Res);
2879
2880 // trunc(p)-trunc(q) -> trunc(p-q)
2881 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2882 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2883 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2884 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2885 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2886 RHS->getOperand(0),
2887 I.getType()))
2888 return ReplaceInstUsesWith(I, Res);
2889 }
2890
Chris Lattner3f5b8772002-05-06 16:14:14 +00002891 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002892}
2893
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002894Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2895 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2896
2897 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002898 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002899 return BinaryOperator::CreateFAdd(Op0, V);
2900
2901 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2902 if (Op1I->getOpcode() == Instruction::FAdd) {
2903 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002904 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002905 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002906 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002907 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002908 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002909 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002910 }
2911
2912 return 0;
2913}
2914
Chris Lattnera0141b92007-07-15 20:42:37 +00002915/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2916/// comparison only checks the sign bit. If it only checks the sign bit, set
2917/// TrueIfSigned if the result of the comparison is true when the input value is
2918/// signed.
2919static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2920 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002921 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002922 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2923 TrueIfSigned = true;
2924 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002925 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2926 TrueIfSigned = true;
2927 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002928 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2929 TrueIfSigned = false;
2930 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002931 case ICmpInst::ICMP_UGT:
2932 // True if LHS u> RHS and RHS == high-bit-mask - 1
2933 TrueIfSigned = true;
2934 return RHS->getValue() ==
2935 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2936 case ICmpInst::ICMP_UGE:
2937 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2938 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002939 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002940 default:
2941 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002942 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002943}
2944
Chris Lattner7e708292002-06-25 16:13:24 +00002945Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002946 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002947 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002948
Chris Lattnera2498472009-10-11 21:36:10 +00002949 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002950 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002951
Chris Lattner8af304a2009-10-11 07:53:15 +00002952 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002953 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2954 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002955
2956 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002957 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002958 if (SI->getOpcode() == Instruction::Shl)
2959 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002960 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002961 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002962
Zhou Sheng843f07672007-04-19 05:39:12 +00002963 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002964 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002965 if (CI->equalsInt(1)) // X * 1 == X
2966 return ReplaceInstUsesWith(I, Op0);
2967 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002968 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002969
Zhou Sheng97b52c22007-03-29 01:57:21 +00002970 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002971 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002972 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002973 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002974 }
Chris Lattnera2498472009-10-11 21:36:10 +00002975 } else if (isa<VectorType>(Op1C->getType())) {
2976 if (Op1C->isNullValue())
2977 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002978
Chris Lattnera2498472009-10-11 21:36:10 +00002979 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002980 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002981 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002982
2983 // As above, vector X*splat(1.0) -> X in all defined cases.
2984 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002985 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2986 if (CI->equalsInt(1))
2987 return ReplaceInstUsesWith(I, Op0);
2988 }
2989 }
Chris Lattnera2881962003-02-18 19:28:33 +00002990 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002991
2992 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2993 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002994 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002995 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002996 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2997 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002998 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002999
3000 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003001
3002 // Try to fold constant mul into select arguments.
3003 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003004 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003005 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003006
3007 if (isa<PHINode>(Op0))
3008 if (Instruction *NV = FoldOpIntoPhi(I))
3009 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003010 }
3011
Dan Gohman186a6362009-08-12 16:04:34 +00003012 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003013 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003014 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003015
Nick Lewycky0c730792008-11-21 07:33:58 +00003016 // (X / Y) * Y = X - (X % Y)
3017 // (X / Y) * -Y = (X % Y) - X
3018 {
Chris Lattnera2498472009-10-11 21:36:10 +00003019 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003020 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3021 if (!BO ||
3022 (BO->getOpcode() != Instruction::UDiv &&
3023 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003024 Op1C = Op0;
3025 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003026 }
Chris Lattnera2498472009-10-11 21:36:10 +00003027 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003028 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003029 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003030 (BO->getOpcode() == Instruction::UDiv ||
3031 BO->getOpcode() == Instruction::SDiv)) {
3032 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3033
Dan Gohmanfa94b942009-08-12 16:33:09 +00003034 // If the division is exact, X % Y is zero.
3035 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3036 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003037 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003038 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003039 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003040 }
3041
Chris Lattner74381062009-08-30 07:44:24 +00003042 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003043 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003044 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003045 else
Chris Lattner74381062009-08-30 07:44:24 +00003046 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003047 Rem->takeName(BO);
3048
Chris Lattnera2498472009-10-11 21:36:10 +00003049 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003050 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003051 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003052 }
3053 }
3054
Chris Lattner8af304a2009-10-11 07:53:15 +00003055 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003056 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003057 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003058
Chris Lattner8af304a2009-10-11 07:53:15 +00003059 // X*(1 << Y) --> X << Y
3060 // (1 << Y)*X --> X << Y
3061 {
3062 Value *Y;
3063 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003064 return BinaryOperator::CreateShl(Op1, Y);
3065 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003066 return BinaryOperator::CreateShl(Op0, Y);
3067 }
3068
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003069 // If one of the operands of the multiply is a cast from a boolean value, then
3070 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003071 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3072 if (!isa<VectorType>(I.getType())) {
3073 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003074 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003075
Chris Lattnerd2c58362009-10-11 21:29:45 +00003076 Value *BoolCast = 0, *OtherOp = 0;
3077 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003078 BoolCast = Op0, OtherOp = Op1;
3079 else if (MaskedValueIsZero(Op1, Negative2))
3080 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003081
Chris Lattner0036e3a2009-10-11 21:22:21 +00003082 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003083 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3084 BoolCast, "tmp");
3085 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003086 }
3087 }
3088
Chris Lattner7e708292002-06-25 16:13:24 +00003089 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003090}
3091
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003092Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3093 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003094 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003095
3096 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003097 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3098 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003099 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3100 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3101 if (Op1F->isExactlyValue(1.0))
3102 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003103 } else if (isa<VectorType>(Op1C->getType())) {
3104 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003105 // As above, vector X*splat(1.0) -> X in all defined cases.
3106 if (Constant *Splat = Op1V->getSplatValue()) {
3107 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3108 if (F->isExactlyValue(1.0))
3109 return ReplaceInstUsesWith(I, Op0);
3110 }
3111 }
3112 }
3113
3114 // Try to fold constant mul into select arguments.
3115 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3116 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3117 return R;
3118
3119 if (isa<PHINode>(Op0))
3120 if (Instruction *NV = FoldOpIntoPhi(I))
3121 return NV;
3122 }
3123
Dan Gohman186a6362009-08-12 16:04:34 +00003124 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003125 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003126 return BinaryOperator::CreateFMul(Op0v, Op1v);
3127
3128 return Changed ? &I : 0;
3129}
3130
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003131/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3132/// instruction.
3133bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3134 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3135
3136 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3137 int NonNullOperand = -1;
3138 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3139 if (ST->isNullValue())
3140 NonNullOperand = 2;
3141 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3142 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3143 if (ST->isNullValue())
3144 NonNullOperand = 1;
3145
3146 if (NonNullOperand == -1)
3147 return false;
3148
3149 Value *SelectCond = SI->getOperand(0);
3150
3151 // Change the div/rem to use 'Y' instead of the select.
3152 I.setOperand(1, SI->getOperand(NonNullOperand));
3153
3154 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3155 // problem. However, the select, or the condition of the select may have
3156 // multiple uses. Based on our knowledge that the operand must be non-zero,
3157 // propagate the known value for the select into other uses of it, and
3158 // propagate a known value of the condition into its other users.
3159
3160 // If the select and condition only have a single use, don't bother with this,
3161 // early exit.
3162 if (SI->use_empty() && SelectCond->hasOneUse())
3163 return true;
3164
3165 // Scan the current block backward, looking for other uses of SI.
3166 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3167
3168 while (BBI != BBFront) {
3169 --BBI;
3170 // If we found a call to a function, we can't assume it will return, so
3171 // information from below it cannot be propagated above it.
3172 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3173 break;
3174
3175 // Replace uses of the select or its condition with the known values.
3176 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3177 I != E; ++I) {
3178 if (*I == SI) {
3179 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003180 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003181 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003182 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3183 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003184 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003185 }
3186 }
3187
3188 // If we past the instruction, quit looking for it.
3189 if (&*BBI == SI)
3190 SI = 0;
3191 if (&*BBI == SelectCond)
3192 SelectCond = 0;
3193
3194 // If we ran out of things to eliminate, break out of the loop.
3195 if (SelectCond == 0 && SI == 0)
3196 break;
3197
3198 }
3199 return true;
3200}
3201
3202
Reid Spencer1628cec2006-10-26 06:15:43 +00003203/// This function implements the transforms on div instructions that work
3204/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3205/// used by the visitors to those instructions.
3206/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003207Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003208 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003209
Chris Lattner50b2ca42008-02-19 06:12:18 +00003210 // undef / X -> 0 for integer.
3211 // undef / X -> undef for FP (the undef could be a snan).
3212 if (isa<UndefValue>(Op0)) {
3213 if (Op0->getType()->isFPOrFPVector())
3214 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003215 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003216 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003217
3218 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003219 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003220 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003221
Reid Spencer1628cec2006-10-26 06:15:43 +00003222 return 0;
3223}
Misha Brukmanfd939082005-04-21 23:48:37 +00003224
Reid Spencer1628cec2006-10-26 06:15:43 +00003225/// This function implements the transforms common to both integer division
3226/// instructions (udiv and sdiv). It is called by the visitors to those integer
3227/// division instructions.
3228/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003229Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003230 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3231
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003232 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003233 if (Op0 == Op1) {
3234 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003235 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003236 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003237 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003238 }
3239
Owen Andersoneed707b2009-07-24 23:12:02 +00003240 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003241 return ReplaceInstUsesWith(I, CI);
3242 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003243
Reid Spencer1628cec2006-10-26 06:15:43 +00003244 if (Instruction *Common = commonDivTransforms(I))
3245 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003246
3247 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3248 // This does not apply for fdiv.
3249 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3250 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003251
3252 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3253 // div X, 1 == X
3254 if (RHS->equalsInt(1))
3255 return ReplaceInstUsesWith(I, Op0);
3256
3257 // (X / C1) / C2 -> X / (C1*C2)
3258 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3259 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3260 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003261 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003262 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003263 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003264 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003265 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003266 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003267 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003268
Reid Spencerbca0e382007-03-23 20:05:17 +00003269 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003270 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3271 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3272 return R;
3273 if (isa<PHINode>(Op0))
3274 if (Instruction *NV = FoldOpIntoPhi(I))
3275 return NV;
3276 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003277 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003278
Chris Lattnera2881962003-02-18 19:28:33 +00003279 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003280 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003281 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003282 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003283
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003284 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003285 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003286 return ReplaceInstUsesWith(I, Op0);
3287
Nick Lewycky895f0852008-11-27 20:21:08 +00003288 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3289 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3290 // div X, 1 == X
3291 if (X->isOne())
3292 return ReplaceInstUsesWith(I, Op0);
3293 }
3294
Reid Spencer1628cec2006-10-26 06:15:43 +00003295 return 0;
3296}
3297
3298Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3299 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3300
3301 // Handle the integer div common cases
3302 if (Instruction *Common = commonIDivTransforms(I))
3303 return Common;
3304
Reid Spencer1628cec2006-10-26 06:15:43 +00003305 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003306 // X udiv C^2 -> X >> C
3307 // Check to see if this is an unsigned division with an exact power of 2,
3308 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003309 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003310 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003311 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003312
3313 // X udiv C, where C >= signbit
3314 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003315 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003316 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003317 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003318 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003319 }
3320
3321 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003322 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003323 if (RHSI->getOpcode() == Instruction::Shl &&
3324 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003325 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003326 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003327 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003328 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003329 if (uint32_t C2 = C1.logBase2())
3330 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003331 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003332 }
3333 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003334 }
3335
Reid Spencer1628cec2006-10-26 06:15:43 +00003336 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3337 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003338 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003339 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003340 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003341 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003342 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003343 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003344 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003345 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003346 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003347 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003348
3349 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003350 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003351 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003352
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003353 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003354 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003355 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003356 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003357 return 0;
3358}
3359
Reid Spencer1628cec2006-10-26 06:15:43 +00003360Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3361 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3362
3363 // Handle the integer div common cases
3364 if (Instruction *Common = commonIDivTransforms(I))
3365 return Common;
3366
3367 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3368 // sdiv X, -1 == -X
3369 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003370 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003371
Dan Gohmanfa94b942009-08-12 16:33:09 +00003372 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003373 if (cast<SDivOperator>(&I)->isExact() &&
3374 RHS->getValue().isNonNegative() &&
3375 RHS->getValue().isPowerOf2()) {
3376 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3377 RHS->getValue().exactLogBase2());
3378 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3379 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003380
3381 // -X/C --> X/-C provided the negation doesn't overflow.
3382 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3383 if (isa<Constant>(Sub->getOperand(0)) &&
3384 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003385 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003386 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3387 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003388 }
3389
3390 // If the sign bits of both operands are zero (i.e. we can prove they are
3391 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003392 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003393 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003394 if (MaskedValueIsZero(Op0, Mask)) {
3395 if (MaskedValueIsZero(Op1, Mask)) {
3396 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3397 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3398 }
3399 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003400 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003401 ShiftedInt->getValue().isPowerOf2()) {
3402 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3403 // Safe because the only negative value (1 << Y) can take on is
3404 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3405 // the sign bit set.
3406 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3407 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003408 }
Eli Friedman8be17392009-07-18 09:53:21 +00003409 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003410
3411 return 0;
3412}
3413
3414Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3415 return commonDivTransforms(I);
3416}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003417
Reid Spencer0a783f72006-11-02 01:53:59 +00003418/// This function implements the transforms on rem instructions that work
3419/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3420/// is used by the visitors to those instructions.
3421/// @brief Transforms common to all three rem instructions
3422Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003424
Chris Lattner50b2ca42008-02-19 06:12:18 +00003425 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3426 if (I.getType()->isFPOrFPVector())
3427 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003428 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003429 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003430 if (isa<UndefValue>(Op1))
3431 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003432
3433 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003434 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3435 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003436
Reid Spencer0a783f72006-11-02 01:53:59 +00003437 return 0;
3438}
3439
3440/// This function implements the transforms common to both integer remainder
3441/// instructions (urem and srem). It is called by the visitors to those integer
3442/// remainder instructions.
3443/// @brief Common integer remainder transforms
3444Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3445 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3446
3447 if (Instruction *common = commonRemTransforms(I))
3448 return common;
3449
Dale Johannesened6af242009-01-21 00:35:19 +00003450 // 0 % X == 0 for integer, we don't need to preserve faults!
3451 if (Constant *LHS = dyn_cast<Constant>(Op0))
3452 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003453 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003454
Chris Lattner857e8cd2004-12-12 21:48:58 +00003455 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003456 // X % 0 == undef, we don't need to preserve faults!
3457 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003458 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003459
Chris Lattnera2881962003-02-18 19:28:33 +00003460 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003461 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003462
Chris Lattner97943922006-02-28 05:49:21 +00003463 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3464 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3465 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3466 return R;
3467 } else if (isa<PHINode>(Op0I)) {
3468 if (Instruction *NV = FoldOpIntoPhi(I))
3469 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003470 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003471
3472 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003473 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003474 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003475 }
Chris Lattnera2881962003-02-18 19:28:33 +00003476 }
3477
Reid Spencer0a783f72006-11-02 01:53:59 +00003478 return 0;
3479}
3480
3481Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3483
3484 if (Instruction *common = commonIRemTransforms(I))
3485 return common;
3486
3487 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3488 // X urem C^2 -> X and C
3489 // Check to see if this is an unsigned remainder with an exact power of 2,
3490 // if so, convert to a bitwise and.
3491 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003492 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003493 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003494 }
3495
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003496 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003497 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3498 if (RHSI->getOpcode() == Instruction::Shl &&
3499 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003500 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003501 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003502 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003503 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003504 }
3505 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003506 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003507
Reid Spencer0a783f72006-11-02 01:53:59 +00003508 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3509 // where C1&C2 are powers of two.
3510 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3511 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3512 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3513 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003514 if ((STO->getValue().isPowerOf2()) &&
3515 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003516 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3517 SI->getName()+".t");
3518 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3519 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003520 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003521 }
3522 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003523 }
3524
Chris Lattner3f5b8772002-05-06 16:14:14 +00003525 return 0;
3526}
3527
Reid Spencer0a783f72006-11-02 01:53:59 +00003528Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3530
Dan Gohmancff55092007-11-05 23:16:33 +00003531 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003532 if (Instruction *Common = commonIRemTransforms(I))
3533 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003534
Dan Gohman186a6362009-08-12 16:04:34 +00003535 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003536 if (!isa<Constant>(RHSNeg) ||
3537 (isa<ConstantInt>(RHSNeg) &&
3538 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003539 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003540 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003541 I.setOperand(1, RHSNeg);
3542 return &I;
3543 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003544
Dan Gohmancff55092007-11-05 23:16:33 +00003545 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003546 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003547 if (I.getType()->isInteger()) {
3548 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3549 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3550 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003551 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003552 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003553 }
3554
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003555 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003556 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3557 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003558
Nick Lewycky9dce8732008-12-20 16:48:00 +00003559 bool hasNegative = false;
3560 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3561 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3562 if (RHS->getValue().isNegative())
3563 hasNegative = true;
3564
3565 if (hasNegative) {
3566 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003567 for (unsigned i = 0; i != VWidth; ++i) {
3568 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3569 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003570 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003571 else
3572 Elts[i] = RHS;
3573 }
3574 }
3575
Owen Andersonaf7ec972009-07-28 21:19:26 +00003576 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003577 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003578 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003579 I.setOperand(1, NewRHSV);
3580 return &I;
3581 }
3582 }
3583 }
3584
Reid Spencer0a783f72006-11-02 01:53:59 +00003585 return 0;
3586}
3587
3588Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003589 return commonRemTransforms(I);
3590}
3591
Chris Lattner457dd822004-06-09 07:59:58 +00003592// isOneBitSet - Return true if there is exactly one bit set in the specified
3593// constant.
3594static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003595 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003596}
3597
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003598// isHighOnes - Return true if the constant is of the form 1+0+.
3599// This is the same as lowones(~X).
3600static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003601 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003602}
3603
Reid Spencere4d87aa2006-12-23 06:05:41 +00003604/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003605/// are carefully arranged to allow folding of expressions such as:
3606///
3607/// (A < B) | (A > B) --> (A != B)
3608///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003609/// Note that this is only valid if the first and second predicates have the
3610/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003611///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003612/// Three bits are used to represent the condition, as follows:
3613/// 0 A > B
3614/// 1 A == B
3615/// 2 A < B
3616///
3617/// <=> Value Definition
3618/// 000 0 Always false
3619/// 001 1 A > B
3620/// 010 2 A == B
3621/// 011 3 A >= B
3622/// 100 4 A < B
3623/// 101 5 A != B
3624/// 110 6 A <= B
3625/// 111 7 Always true
3626///
3627static unsigned getICmpCode(const ICmpInst *ICI) {
3628 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003629 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003630 case ICmpInst::ICMP_UGT: return 1; // 001
3631 case ICmpInst::ICMP_SGT: return 1; // 001
3632 case ICmpInst::ICMP_EQ: return 2; // 010
3633 case ICmpInst::ICMP_UGE: return 3; // 011
3634 case ICmpInst::ICMP_SGE: return 3; // 011
3635 case ICmpInst::ICMP_ULT: return 4; // 100
3636 case ICmpInst::ICMP_SLT: return 4; // 100
3637 case ICmpInst::ICMP_NE: return 5; // 101
3638 case ICmpInst::ICMP_ULE: return 6; // 110
3639 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003640 // True -> 7
3641 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003642 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003643 return 0;
3644 }
3645}
3646
Evan Cheng8db90722008-10-14 17:15:11 +00003647/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3648/// predicate into a three bit mask. It also returns whether it is an ordered
3649/// predicate by reference.
3650static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3651 isOrdered = false;
3652 switch (CC) {
3653 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3654 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003655 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3656 case FCmpInst::FCMP_UGT: return 1; // 001
3657 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3658 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003659 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3660 case FCmpInst::FCMP_UGE: return 3; // 011
3661 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3662 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003663 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3664 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003665 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3666 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003667 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003668 default:
3669 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003670 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003671 return 0;
3672 }
3673}
3674
Reid Spencere4d87aa2006-12-23 06:05:41 +00003675/// getICmpValue - This is the complement of getICmpCode, which turns an
3676/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003677/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003678/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003679static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003680 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003682 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003683 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 case 1:
3685 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003686 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003688 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3689 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690 case 3:
3691 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003692 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003694 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 case 4:
3696 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003697 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003699 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3700 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701 case 6:
3702 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003703 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003705 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003706 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003707 }
3708}
3709
Evan Cheng8db90722008-10-14 17:15:11 +00003710/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3711/// opcode and two operands into either a FCmp instruction. isordered is passed
3712/// in to determine which kind of predicate to use in the new fcmp instruction.
3713static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003714 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003715 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003716 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003717 case 0:
3718 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003719 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003720 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003721 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003722 case 1:
3723 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003724 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003725 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003726 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003727 case 2:
3728 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003729 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003730 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003731 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003732 case 3:
3733 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003734 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003735 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003736 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003737 case 4:
3738 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003739 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003740 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003741 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003742 case 5:
3743 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003744 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003745 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003746 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003747 case 6:
3748 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003749 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003750 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003751 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003752 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003753 }
3754}
3755
Chris Lattnerb9553d62008-11-16 04:55:20 +00003756/// PredicatesFoldable - Return true if both predicates match sign or if at
3757/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003758static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003759 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3760 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3761 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003762}
3763
3764namespace {
3765// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3766struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003767 InstCombiner &IC;
3768 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003769 ICmpInst::Predicate pred;
3770 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3771 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3772 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003773 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003774 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3775 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003776 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3777 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003778 return false;
3779 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003780 Instruction *apply(Instruction &Log) const {
3781 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3782 if (ICI->getOperand(0) != LHS) {
3783 assert(ICI->getOperand(1) == LHS);
3784 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003785 }
3786
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003787 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003789 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003790 unsigned Code;
3791 switch (Log.getOpcode()) {
3792 case Instruction::And: Code = LHSCode & RHSCode; break;
3793 case Instruction::Or: Code = LHSCode | RHSCode; break;
3794 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003795 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003796 }
3797
Nick Lewycky4a134af2009-10-25 05:20:17 +00003798 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003799 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003800 if (Instruction *I = dyn_cast<Instruction>(RV))
3801 return I;
3802 // Otherwise, it's a constant boolean value...
3803 return IC.ReplaceInstUsesWith(Log, RV);
3804 }
3805};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003806} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003807
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003808// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3809// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003810// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003811Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003812 ConstantInt *OpRHS,
3813 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003814 BinaryOperator &TheAnd) {
3815 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003816 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003817 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003818 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003819
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003820 switch (Op->getOpcode()) {
3821 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003822 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003823 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003824 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003825 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003826 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003827 }
3828 break;
3829 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003830 if (Together == AndRHS) // (X | C) & C --> C
3831 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003832
Chris Lattner6e7ba452005-01-01 16:22:27 +00003833 if (Op->hasOneUse() && Together != OpRHS) {
3834 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003835 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003836 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003837 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003838 }
3839 break;
3840 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003841 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003842 // Adding a one to a single bit bit-field should be turned into an XOR
3843 // of the bit. First thing to check is to see if this AND is with a
3844 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003845 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003846
3847 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003848 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003849 // Ok, at this point, we know that we are masking the result of the
3850 // ADD down to exactly one bit. If the constant we are adding has
3851 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003852 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003853
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003854 // Check to see if any bits below the one bit set in AndRHSV are set.
3855 if ((AddRHS & (AndRHSV-1)) == 0) {
3856 // If not, the only thing that can effect the output of the AND is
3857 // the bit specified by AndRHSV. If that bit is set, the effect of
3858 // the XOR is to toggle the bit. If it is clear, then the ADD has
3859 // no effect.
3860 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3861 TheAnd.setOperand(0, X);
3862 return &TheAnd;
3863 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003864 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003865 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003866 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003867 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003868 }
3869 }
3870 }
3871 }
3872 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003873
3874 case Instruction::Shl: {
3875 // We know that the AND will not produce any of the bits shifted in, so if
3876 // the anded constant includes them, clear them now!
3877 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003878 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003879 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003880 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003881 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003882
Zhou Sheng290bec52007-03-29 08:15:12 +00003883 if (CI->getValue() == ShlMask) {
3884 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003885 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3886 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003887 TheAnd.setOperand(1, CI);
3888 return &TheAnd;
3889 }
3890 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003891 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003892 case Instruction::LShr:
3893 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003894 // We know that the AND will not produce any of the bits shifted in, so if
3895 // the anded constant includes them, clear them now! This only applies to
3896 // unsigned shifts, because a signed shr may bring in set bits!
3897 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003898 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003899 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003900 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003901 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003902
Zhou Sheng290bec52007-03-29 08:15:12 +00003903 if (CI->getValue() == ShrMask) {
3904 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003905 return ReplaceInstUsesWith(TheAnd, Op);
3906 } else if (CI != AndRHS) {
3907 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3908 return &TheAnd;
3909 }
3910 break;
3911 }
3912 case Instruction::AShr:
3913 // Signed shr.
3914 // See if this is shifting in some sign extension, then masking it out
3915 // with an and.
3916 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003917 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003918 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003919 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003920 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003921 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003922 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003923 // Make the argument unsigned.
3924 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003925 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003926 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003927 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003928 }
3929 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003930 }
3931 return 0;
3932}
3933
Chris Lattner8b170942002-08-09 23:47:40 +00003934
Chris Lattnera96879a2004-09-29 17:40:11 +00003935/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3936/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003937/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3938/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003939/// insert new instructions.
3940Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003941 bool isSigned, bool Inside,
3942 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003943 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003944 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003945 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003946
Chris Lattnera96879a2004-09-29 17:40:11 +00003947 if (Inside) {
3948 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003949 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003950
Reid Spencere4d87aa2006-12-23 06:05:41 +00003951 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003952 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003953 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003954 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003955 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003956 }
3957
3958 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003959 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003960 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003961 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003962 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003963 }
3964
3965 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003966 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003967
Reid Spencere4e40032007-03-21 23:19:50 +00003968 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003969 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003970 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003971 ICmpInst::Predicate pred = (isSigned ?
3972 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003973 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003974 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003975
Reid Spencere4e40032007-03-21 23:19:50 +00003976 // Emit V-Lo >u Hi-1-Lo
3977 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003978 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003979 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003980 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003981 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003982}
3983
Chris Lattner7203e152005-09-18 07:22:02 +00003984// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3985// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3986// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3987// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003988static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003989 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003990 uint32_t BitWidth = Val->getType()->getBitWidth();
3991 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003992
3993 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003994 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003995 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003996 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003997 return true;
3998}
3999
Chris Lattner7203e152005-09-18 07:22:02 +00004000/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4001/// where isSub determines whether the operator is a sub. If we can fold one of
4002/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004003///
4004/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4005/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4006/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4007///
4008/// return (A +/- B).
4009///
4010Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004011 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004012 Instruction &I) {
4013 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4014 if (!LHSI || LHSI->getNumOperands() != 2 ||
4015 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4016
4017 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4018
4019 switch (LHSI->getOpcode()) {
4020 default: return 0;
4021 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004022 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004023 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004024 if ((Mask->getValue().countLeadingZeros() +
4025 Mask->getValue().countPopulation()) ==
4026 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004027 break;
4028
4029 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4030 // part, we don't need any explicit masks to take them out of A. If that
4031 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004032 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004033 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004034 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004035 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004036 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004037 break;
4038 }
4039 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004040 return 0;
4041 case Instruction::Or:
4042 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004043 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004044 if ((Mask->getValue().countLeadingZeros() +
4045 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004046 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004047 break;
4048 return 0;
4049 }
4050
Chris Lattnerc8e77562005-09-18 04:24:45 +00004051 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004052 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4053 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004054}
4055
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004056/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4057Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4058 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004059 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004060 ConstantInt *LHSCst, *RHSCst;
4061 ICmpInst::Predicate LHSCC, RHSCC;
4062
Chris Lattnerea065fb2008-11-16 05:10:52 +00004063 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004064 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004065 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004066 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004067 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004068 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004069
4070 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4071 // where C is a power of 2
4072 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4073 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00004074 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004075 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00004076 }
4077
4078 // From here on, we only handle:
4079 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4080 if (Val != Val2) return 0;
4081
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004082 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4083 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4084 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4085 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4086 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4087 return 0;
4088
4089 // We can't fold (ugt x, C) & (sgt x, C2).
4090 if (!PredicatesFoldable(LHSCC, RHSCC))
4091 return 0;
4092
4093 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004094 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004095 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004096 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004097 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004098 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004099 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004100 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4101
4102 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004103 std::swap(LHS, RHS);
4104 std::swap(LHSCst, RHSCst);
4105 std::swap(LHSCC, RHSCC);
4106 }
4107
4108 // At this point, we know we have have two icmp instructions
4109 // comparing a value against two constants and and'ing the result
4110 // together. Because of the above check, we know that we only have
4111 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4112 // (from the FoldICmpLogical check above), that the two constants
4113 // are not equal and that the larger constant is on the RHS
4114 assert(LHSCst != RHSCst && "Compares not folded above?");
4115
4116 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004117 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004118 case ICmpInst::ICMP_EQ:
4119 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004120 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004121 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4122 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4123 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004124 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004125 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4126 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4127 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4128 return ReplaceInstUsesWith(I, LHS);
4129 }
4130 case ICmpInst::ICMP_NE:
4131 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004132 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004133 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004134 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004135 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004136 break; // (X != 13 & X u< 15) -> no change
4137 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004138 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004139 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004140 break; // (X != 13 & X s< 15) -> no change
4141 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4142 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4143 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4144 return ReplaceInstUsesWith(I, RHS);
4145 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004146 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004147 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004148 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004149 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004150 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004151 }
4152 break; // (X != 13 & X != 15) -> no change
4153 }
4154 break;
4155 case ICmpInst::ICMP_ULT:
4156 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004157 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004158 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4159 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004161 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4162 break;
4163 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4164 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4165 return ReplaceInstUsesWith(I, LHS);
4166 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4167 break;
4168 }
4169 break;
4170 case ICmpInst::ICMP_SLT:
4171 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004172 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004173 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4174 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004175 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004176 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4177 break;
4178 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4179 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4180 return ReplaceInstUsesWith(I, LHS);
4181 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4182 break;
4183 }
4184 break;
4185 case ICmpInst::ICMP_UGT:
4186 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004187 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004188 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4189 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4190 return ReplaceInstUsesWith(I, RHS);
4191 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4192 break;
4193 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004194 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004195 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004196 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004197 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004198 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004199 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004200 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4201 break;
4202 }
4203 break;
4204 case ICmpInst::ICMP_SGT:
4205 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004206 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004207 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4208 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4209 return ReplaceInstUsesWith(I, RHS);
4210 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4211 break;
4212 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004213 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004214 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004215 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004216 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004217 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004218 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004219 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4220 break;
4221 }
4222 break;
4223 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004224
4225 return 0;
4226}
4227
Chris Lattner42d1be02009-07-23 05:14:02 +00004228Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4229 FCmpInst *RHS) {
4230
4231 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4232 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4233 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4234 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4235 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4236 // If either of the constants are nans, then the whole thing returns
4237 // false.
4238 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004239 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004240 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004241 LHS->getOperand(0), RHS->getOperand(0));
4242 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004243
4244 // Handle vector zeros. This occurs because the canonical form of
4245 // "fcmp ord x,x" is "fcmp ord x, 0".
4246 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4247 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004248 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004249 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004250 return 0;
4251 }
4252
4253 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4254 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4255 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4256
4257
4258 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4259 // Swap RHS operands to match LHS.
4260 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4261 std::swap(Op1LHS, Op1RHS);
4262 }
4263
4264 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4265 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4266 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004267 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004268
4269 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004270 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004271 if (Op0CC == FCmpInst::FCMP_TRUE)
4272 return ReplaceInstUsesWith(I, RHS);
4273 if (Op1CC == FCmpInst::FCMP_TRUE)
4274 return ReplaceInstUsesWith(I, LHS);
4275
4276 bool Op0Ordered;
4277 bool Op1Ordered;
4278 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4279 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4280 if (Op1Pred == 0) {
4281 std::swap(LHS, RHS);
4282 std::swap(Op0Pred, Op1Pred);
4283 std::swap(Op0Ordered, Op1Ordered);
4284 }
4285 if (Op0Pred == 0) {
4286 // uno && ueq -> uno && (uno || eq) -> ueq
4287 // ord && olt -> ord && (ord && lt) -> olt
4288 if (Op0Ordered == Op1Ordered)
4289 return ReplaceInstUsesWith(I, RHS);
4290
4291 // uno && oeq -> uno && (ord && eq) -> false
4292 // uno && ord -> false
4293 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004294 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004295 // ord && ueq -> ord && (uno || eq) -> oeq
4296 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4297 Op0LHS, Op0RHS, Context));
4298 }
4299 }
4300
4301 return 0;
4302}
4303
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004304
Chris Lattner7e708292002-06-25 16:13:24 +00004305Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004306 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004307 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004308
Chris Lattnere87597f2004-10-16 18:11:37 +00004309 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004310 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004311
Chris Lattner6e7ba452005-01-01 16:22:27 +00004312 // and X, X = X
4313 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004314 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004315
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004316 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004317 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004318 if (SimplifyDemandedInstructionBits(I))
4319 return &I;
4320 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004321 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004322 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004323 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004324 } else if (isa<ConstantAggregateZero>(Op1)) {
4325 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004326 }
4327 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004328
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004329 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004330 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004331 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004332
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004333 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004334 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004335 Value *Op0LHS = Op0I->getOperand(0);
4336 Value *Op0RHS = Op0I->getOperand(1);
4337 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004338 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004339 case Instruction::Xor:
4340 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004341 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004342 if (!Op0I->hasOneUse()) break;
4343
4344 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4345 // Not masking anything out for the LHS, move to RHS.
4346 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4347 Op0RHS->getName()+".masked");
4348 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4349 }
4350 if (!isa<Constant>(Op0RHS) &&
4351 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4352 // Not masking anything out for the RHS, move to LHS.
4353 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4354 Op0LHS->getName()+".masked");
4355 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004356 }
4357
Chris Lattner6e7ba452005-01-01 16:22:27 +00004358 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004359 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004360 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4361 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4362 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4363 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004364 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004365 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004366 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004367 break;
4368
4369 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004370 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4371 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4372 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4373 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004374 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004375
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004376 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4377 // has 1's for all bits that the subtraction with A might affect.
4378 if (Op0I->hasOneUse()) {
4379 uint32_t BitWidth = AndRHSMask.getBitWidth();
4380 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4381 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4382
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004383 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004384 if (!(A && A->isZero()) && // avoid infinite recursion.
4385 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004386 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004387 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4388 }
4389 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004390 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004391
4392 case Instruction::Shl:
4393 case Instruction::LShr:
4394 // (1 << x) & 1 --> zext(x == 0)
4395 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004396 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004397 Value *NewICmp =
4398 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004399 return new ZExtInst(NewICmp, I.getType());
4400 }
4401 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004402 }
4403
Chris Lattner58403262003-07-23 19:25:52 +00004404 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004405 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004406 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004407 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004408 // If this is an integer truncation or change from signed-to-unsigned, and
4409 // if the source is an and/or with immediate, transform it. This
4410 // frequently occurs for bitfield accesses.
4411 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004412 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004413 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004414 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004415 if (CastOp->getOpcode() == Instruction::And) {
4416 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004417 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4418 // This will fold the two constants together, which may allow
4419 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004420 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004421 CastOp->getOperand(0), I.getType(),
4422 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004423 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004424 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004425 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004426 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004427 } else if (CastOp->getOpcode() == Instruction::Or) {
4428 // Change: and (cast (or X, C1) to T), C2
4429 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004430 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004431 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004432 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004433 return ReplaceInstUsesWith(I, AndRHS);
4434 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004435 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004436 }
Chris Lattner06782f82003-07-23 19:36:21 +00004437 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004438
4439 // Try to fold constant and into select arguments.
4440 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004441 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004442 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004443 if (isa<PHINode>(Op0))
4444 if (Instruction *NV = FoldOpIntoPhi(I))
4445 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004446 }
4447
Dan Gohman186a6362009-08-12 16:04:34 +00004448 Value *Op0NotVal = dyn_castNotVal(Op0);
4449 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004450
Chris Lattner5b62aa72004-06-18 06:07:51 +00004451 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004452 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004453
Misha Brukmancb6267b2004-07-30 12:50:08 +00004454 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004455 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004456 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4457 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004458 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004459 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004460
4461 {
Chris Lattner003b6202007-06-15 05:58:24 +00004462 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004463 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004464 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4465 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004466
4467 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004468 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004469 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004470 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004471 }
4472 }
4473
Dan Gohman4ae51262009-08-12 16:23:25 +00004474 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004475 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4476 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004477
4478 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004479 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004480 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004481 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004482 }
4483 }
Chris Lattner64daab52006-04-01 08:03:55 +00004484
4485 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004486 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004487 if (A == Op1) { // (A^B)&A -> A&(A^B)
4488 I.swapOperands(); // Simplify below
4489 std::swap(Op0, Op1);
4490 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4491 cast<BinaryOperator>(Op0)->swapOperands();
4492 I.swapOperands(); // Simplify below
4493 std::swap(Op0, Op1);
4494 }
4495 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004496
Chris Lattner64daab52006-04-01 08:03:55 +00004497 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004498 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004499 if (B == Op0) { // B&(A^B) -> B&(B^A)
4500 cast<BinaryOperator>(Op1)->swapOperands();
4501 std::swap(A, B);
4502 }
Chris Lattner74381062009-08-30 07:44:24 +00004503 if (A == Op0) // A&(A^B) -> A & ~B
4504 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004505 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004506
4507 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004508 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4509 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004510 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004511 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4512 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004513 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004514 }
4515
Reid Spencere4d87aa2006-12-23 06:05:41 +00004516 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4517 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004518 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004519 return R;
4520
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004521 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4522 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4523 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004524 }
4525
Chris Lattner6fc205f2006-05-05 06:39:07 +00004526 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004527 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4528 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4529 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4530 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004531 if (SrcTy == Op1C->getOperand(0)->getType() &&
4532 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004533 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004534 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4535 I.getType(), TD) &&
4536 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4537 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004538 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4539 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004540 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004541 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004542 }
Chris Lattnere511b742006-11-14 07:46:50 +00004543
4544 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004545 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4546 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4547 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004548 SI0->getOperand(1) == SI1->getOperand(1) &&
4549 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004550 Value *NewOp =
4551 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4552 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004553 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004554 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004555 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004556 }
4557
Evan Cheng8db90722008-10-14 17:15:11 +00004558 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004559 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004560 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4561 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4562 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004563 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004564
Chris Lattner7e708292002-06-25 16:13:24 +00004565 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004566}
4567
Chris Lattner8c34cd22008-10-05 02:13:19 +00004568/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4569/// capable of providing pieces of a bswap. The subexpression provides pieces
4570/// of a bswap if it is proven that each of the non-zero bytes in the output of
4571/// the expression came from the corresponding "byte swapped" byte in some other
4572/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4573/// we know that the expression deposits the low byte of %X into the high byte
4574/// of the bswap result and that all other bytes are zero. This expression is
4575/// accepted, the high byte of ByteValues is set to X to indicate a correct
4576/// match.
4577///
4578/// This function returns true if the match was unsuccessful and false if so.
4579/// On entry to the function the "OverallLeftShift" is a signed integer value
4580/// indicating the number of bytes that the subexpression is later shifted. For
4581/// example, if the expression is later right shifted by 16 bits, the
4582/// OverallLeftShift value would be -2 on entry. This is used to specify which
4583/// byte of ByteValues is actually being set.
4584///
4585/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4586/// byte is masked to zero by a user. For example, in (X & 255), X will be
4587/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4588/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4589/// always in the local (OverallLeftShift) coordinate space.
4590///
4591static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4592 SmallVector<Value*, 8> &ByteValues) {
4593 if (Instruction *I = dyn_cast<Instruction>(V)) {
4594 // If this is an or instruction, it may be an inner node of the bswap.
4595 if (I->getOpcode() == Instruction::Or) {
4596 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4597 ByteValues) ||
4598 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4599 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004600 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004601
4602 // If this is a logical shift by a constant multiple of 8, recurse with
4603 // OverallLeftShift and ByteMask adjusted.
4604 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4605 unsigned ShAmt =
4606 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4607 // Ensure the shift amount is defined and of a byte value.
4608 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4609 return true;
4610
4611 unsigned ByteShift = ShAmt >> 3;
4612 if (I->getOpcode() == Instruction::Shl) {
4613 // X << 2 -> collect(X, +2)
4614 OverallLeftShift += ByteShift;
4615 ByteMask >>= ByteShift;
4616 } else {
4617 // X >>u 2 -> collect(X, -2)
4618 OverallLeftShift -= ByteShift;
4619 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004620 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004621 }
4622
4623 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4624 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4625
4626 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4627 ByteValues);
4628 }
4629
4630 // If this is a logical 'and' with a mask that clears bytes, clear the
4631 // corresponding bytes in ByteMask.
4632 if (I->getOpcode() == Instruction::And &&
4633 isa<ConstantInt>(I->getOperand(1))) {
4634 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4635 unsigned NumBytes = ByteValues.size();
4636 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4637 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4638
4639 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4640 // If this byte is masked out by a later operation, we don't care what
4641 // the and mask is.
4642 if ((ByteMask & (1 << i)) == 0)
4643 continue;
4644
4645 // If the AndMask is all zeros for this byte, clear the bit.
4646 APInt MaskB = AndMask & Byte;
4647 if (MaskB == 0) {
4648 ByteMask &= ~(1U << i);
4649 continue;
4650 }
4651
4652 // If the AndMask is not all ones for this byte, it's not a bytezap.
4653 if (MaskB != Byte)
4654 return true;
4655
4656 // Otherwise, this byte is kept.
4657 }
4658
4659 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4660 ByteValues);
4661 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004662 }
4663
Chris Lattner8c34cd22008-10-05 02:13:19 +00004664 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4665 // the input value to the bswap. Some observations: 1) if more than one byte
4666 // is demanded from this input, then it could not be successfully assembled
4667 // into a byteswap. At least one of the two bytes would not be aligned with
4668 // their ultimate destination.
4669 if (!isPowerOf2_32(ByteMask)) return true;
4670 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004671
Chris Lattner8c34cd22008-10-05 02:13:19 +00004672 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4673 // is demanded, it needs to go into byte 0 of the result. This means that the
4674 // byte needs to be shifted until it lands in the right byte bucket. The
4675 // shift amount depends on the position: if the byte is coming from the high
4676 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4677 // low part, it must be shifted left.
4678 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4679 if (InputByteNo < ByteValues.size()/2) {
4680 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4681 return true;
4682 } else {
4683 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4684 return true;
4685 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004686
4687 // If the destination byte value is already defined, the values are or'd
4688 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004689 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004690 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004691 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004692 return false;
4693}
4694
4695/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4696/// If so, insert the new bswap intrinsic and return it.
4697Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004698 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004699 if (!ITy || ITy->getBitWidth() % 16 ||
4700 // ByteMask only allows up to 32-byte values.
4701 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004702 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004703
4704 /// ByteValues - For each byte of the result, we keep track of which value
4705 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004706 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004707 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004708
4709 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004710 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4711 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004712 return 0;
4713
4714 // Check to see if all of the bytes come from the same value.
4715 Value *V = ByteValues[0];
4716 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4717
4718 // Check to make sure that all of the bytes come from the same value.
4719 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4720 if (ByteValues[i] != V)
4721 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004722 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004723 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004724 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004725 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004726}
4727
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004728/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4729/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4730/// we can simplify this expression to "cond ? C : D or B".
4731static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004732 Value *C, Value *D,
4733 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004734 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004735 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004736 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004737 return 0;
4738
Chris Lattnera6a474d2008-11-16 04:26:55 +00004739 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004740 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004741 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004742 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004743 return SelectInst::Create(Cond, C, B);
4744 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004745 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004746 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004747 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004748 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004749 return 0;
4750}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004751
Chris Lattner69d4ced2008-11-16 05:20:07 +00004752/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4753Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4754 ICmpInst *LHS, ICmpInst *RHS) {
4755 Value *Val, *Val2;
4756 ConstantInt *LHSCst, *RHSCst;
4757 ICmpInst::Predicate LHSCC, RHSCC;
4758
4759 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004760 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004761 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004762 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004763 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004764 return 0;
4765
4766 // From here on, we only handle:
4767 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4768 if (Val != Val2) return 0;
4769
4770 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4771 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4772 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4773 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4774 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4775 return 0;
4776
4777 // We can't fold (ugt x, C) | (sgt x, C2).
4778 if (!PredicatesFoldable(LHSCC, RHSCC))
4779 return 0;
4780
4781 // Ensure that the larger constant is on the RHS.
4782 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004783 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004784 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004785 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004786 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4787 else
4788 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4789
4790 if (ShouldSwap) {
4791 std::swap(LHS, RHS);
4792 std::swap(LHSCst, RHSCst);
4793 std::swap(LHSCC, RHSCC);
4794 }
4795
4796 // At this point, we know we have have two icmp instructions
4797 // comparing a value against two constants and or'ing the result
4798 // together. Because of the above check, we know that we only have
4799 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4800 // FoldICmpLogical check above), that the two constants are not
4801 // equal.
4802 assert(LHSCst != RHSCst && "Compares not folded above?");
4803
4804 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004805 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004806 case ICmpInst::ICMP_EQ:
4807 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004808 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004809 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004810 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004811 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004812 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004813 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004814 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004815 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004816 }
4817 break; // (X == 13 | X == 15) -> no change
4818 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4819 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4820 break;
4821 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4822 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4823 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4824 return ReplaceInstUsesWith(I, RHS);
4825 }
4826 break;
4827 case ICmpInst::ICMP_NE:
4828 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004829 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004830 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4831 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4832 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4833 return ReplaceInstUsesWith(I, LHS);
4834 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4835 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4836 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004837 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004838 }
4839 break;
4840 case ICmpInst::ICMP_ULT:
4841 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004842 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004843 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4844 break;
4845 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4846 // If RHSCst is [us]MAXINT, it is always false. Not handling
4847 // this can cause overflow.
4848 if (RHSCst->isMaxValue(false))
4849 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004850 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004851 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004852 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4853 break;
4854 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4855 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4856 return ReplaceInstUsesWith(I, RHS);
4857 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4858 break;
4859 }
4860 break;
4861 case ICmpInst::ICMP_SLT:
4862 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004863 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004864 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4865 break;
4866 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4867 // If RHSCst is [us]MAXINT, it is always false. Not handling
4868 // this can cause overflow.
4869 if (RHSCst->isMaxValue(true))
4870 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004871 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004872 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004873 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4874 break;
4875 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4876 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4877 return ReplaceInstUsesWith(I, RHS);
4878 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4879 break;
4880 }
4881 break;
4882 case ICmpInst::ICMP_UGT:
4883 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004884 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004885 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4886 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4887 return ReplaceInstUsesWith(I, LHS);
4888 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4889 break;
4890 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4891 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004892 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004893 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4894 break;
4895 }
4896 break;
4897 case ICmpInst::ICMP_SGT:
4898 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004899 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004900 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4901 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4902 return ReplaceInstUsesWith(I, LHS);
4903 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4904 break;
4905 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4906 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004907 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004908 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4909 break;
4910 }
4911 break;
4912 }
4913 return 0;
4914}
4915
Chris Lattner5414cc52009-07-23 05:46:22 +00004916Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4917 FCmpInst *RHS) {
4918 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4919 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4920 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4921 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4922 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4923 // If either of the constants are nans, then the whole thing returns
4924 // true.
4925 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004926 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004927
4928 // Otherwise, no need to compare the two constants, compare the
4929 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004930 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004931 LHS->getOperand(0), RHS->getOperand(0));
4932 }
4933
4934 // Handle vector zeros. This occurs because the canonical form of
4935 // "fcmp uno x,x" is "fcmp uno x, 0".
4936 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4937 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004938 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004939 LHS->getOperand(0), RHS->getOperand(0));
4940
4941 return 0;
4942 }
4943
4944 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4945 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4946 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4947
4948 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4949 // Swap RHS operands to match LHS.
4950 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4951 std::swap(Op1LHS, Op1RHS);
4952 }
4953 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4954 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4955 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004956 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004957 Op0LHS, Op0RHS);
4958 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004959 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004960 if (Op0CC == FCmpInst::FCMP_FALSE)
4961 return ReplaceInstUsesWith(I, RHS);
4962 if (Op1CC == FCmpInst::FCMP_FALSE)
4963 return ReplaceInstUsesWith(I, LHS);
4964 bool Op0Ordered;
4965 bool Op1Ordered;
4966 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4967 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4968 if (Op0Ordered == Op1Ordered) {
4969 // If both are ordered or unordered, return a new fcmp with
4970 // or'ed predicates.
4971 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4972 Op0LHS, Op0RHS, Context);
4973 if (Instruction *I = dyn_cast<Instruction>(RV))
4974 return I;
4975 // Otherwise, it's a constant boolean value...
4976 return ReplaceInstUsesWith(I, RV);
4977 }
4978 }
4979 return 0;
4980}
4981
Bill Wendlinga698a472008-12-01 08:23:25 +00004982/// FoldOrWithConstants - This helper function folds:
4983///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004984/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004985///
4986/// into:
4987///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004988/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004989///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004990/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004991Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004992 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004993 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4994 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004995
Bill Wendling286a0542008-12-02 06:24:20 +00004996 Value *V1 = 0;
4997 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004998 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004999
Bill Wendling29976b92008-12-02 06:18:11 +00005000 APInt Xor = CI1->getValue() ^ CI2->getValue();
5001 if (!Xor.isAllOnesValue()) return 0;
5002
Bill Wendling286a0542008-12-02 06:24:20 +00005003 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005004 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005005 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005006 }
5007
5008 return 0;
5009}
5010
Chris Lattner7e708292002-06-25 16:13:24 +00005011Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005012 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005014
Chris Lattner42593e62007-03-24 23:56:43 +00005015 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00005016 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005017
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005018 // or X, X = X
5019 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00005020 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005021
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005022 // See if we can simplify any instructions used by the instruction whose sole
5023 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005024 if (SimplifyDemandedInstructionBits(I))
5025 return &I;
5026 if (isa<VectorType>(I.getType())) {
5027 if (isa<ConstantAggregateZero>(Op1)) {
5028 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
5029 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
5030 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
5031 return ReplaceInstUsesWith(I, I.getOperand(1));
5032 }
Chris Lattner42593e62007-03-24 23:56:43 +00005033 }
Chris Lattner041a6c92007-06-15 05:26:55 +00005034
Chris Lattner3f5b8772002-05-06 16:14:14 +00005035 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005036 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005037 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005038 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005039 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005040 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005041 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005042 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005043 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005044 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005045 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005046
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005047 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005048 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005049 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005050 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005051 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005052 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005053 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005054 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005055
5056 // Try to fold constant and into select arguments.
5057 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005058 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005059 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005060 if (isa<PHINode>(Op0))
5061 if (Instruction *NV = FoldOpIntoPhi(I))
5062 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005063 }
5064
Chris Lattner4f637d42006-01-06 17:59:59 +00005065 Value *A = 0, *B = 0;
5066 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005067
Dan Gohman4ae51262009-08-12 16:23:25 +00005068 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005069 if (A == Op1 || B == Op1) // (A & ?) | A --> A
5070 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00005071 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005072 if (A == Op0 || B == Op0) // A | (A & ?) --> A
5073 return ReplaceInstUsesWith(I, Op0);
5074
Chris Lattner6423d4c2006-07-10 20:25:24 +00005075 // (A | B) | C and A | (B | C) -> bswap if possible.
5076 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005077 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5078 match(Op1, m_Or(m_Value(), m_Value())) ||
5079 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5080 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005081 if (Instruction *BSwap = MatchBSwap(I))
5082 return BSwap;
5083 }
5084
Chris Lattner6e4c6492005-05-09 04:58:36 +00005085 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005086 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005087 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005088 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005089 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005090 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005091 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005092 }
5093
5094 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005095 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005096 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005097 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005098 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005099 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005100 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005101 }
5102
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005103 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005104 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005105 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5106 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005107 Value *V1 = 0, *V2 = 0, *V3 = 0;
5108 C1 = dyn_cast<ConstantInt>(C);
5109 C2 = dyn_cast<ConstantInt>(D);
5110 if (C1 && C2) { // (A & C1)|(B & C2)
5111 // If we have: ((V + N) & C1) | (V & C2)
5112 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5113 // replace with V+N.
5114 if (C1->getValue() == ~C2->getValue()) {
5115 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005116 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005117 // Add commutes, try both ways.
5118 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5119 return ReplaceInstUsesWith(I, A);
5120 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5121 return ReplaceInstUsesWith(I, A);
5122 }
5123 // Or commutes, try both ways.
5124 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005125 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005126 // Add commutes, try both ways.
5127 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5128 return ReplaceInstUsesWith(I, B);
5129 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5130 return ReplaceInstUsesWith(I, B);
5131 }
5132 }
Chris Lattner044e5332007-04-08 08:01:49 +00005133 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005134 }
5135
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005136 // Check to see if we have any common things being and'ed. If so, find the
5137 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005138 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5139 if (A == B) // (A & C)|(A & D) == A & (C|D)
5140 V1 = A, V2 = C, V3 = D;
5141 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5142 V1 = A, V2 = B, V3 = C;
5143 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5144 V1 = C, V2 = A, V3 = D;
5145 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5146 V1 = C, V2 = A, V3 = B;
5147
5148 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005149 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005150 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005151 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005152 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005153
Dan Gohman1975d032008-10-30 20:40:10 +00005154 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005155 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005156 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005157 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005158 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005159 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005160 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005161 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005162 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005163
Bill Wendlingb01865c2008-11-30 13:52:49 +00005164 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005165 if ((match(C, m_Not(m_Specific(D))) &&
5166 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005167 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005168 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005169 if ((match(A, m_Not(m_Specific(D))) &&
5170 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005171 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005172 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005173 if ((match(C, m_Not(m_Specific(B))) &&
5174 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005175 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005176 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005177 if ((match(A, m_Not(m_Specific(B))) &&
5178 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005179 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005180 }
Chris Lattnere511b742006-11-14 07:46:50 +00005181
5182 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005183 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5184 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5185 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005186 SI0->getOperand(1) == SI1->getOperand(1) &&
5187 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005188 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5189 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005190 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005191 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005192 }
5193 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005194
Bill Wendlingb3833d12008-12-01 01:07:11 +00005195 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005196 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5197 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005198 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005199 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005200 }
5201 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005202 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5203 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005204 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005205 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005206 }
5207
Chris Lattner48b59ec2009-10-26 15:40:07 +00005208 if ((A = dyn_castNotVal(Op0))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005209 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00005210 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005211 } else {
5212 A = 0;
5213 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005214 // Note, A is still live here!
Chris Lattner48b59ec2009-10-26 15:40:07 +00005215 if ((B = dyn_castNotVal(Op1))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005216 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00005217 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00005218
Misha Brukmancb6267b2004-07-30 12:50:08 +00005219 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005220 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00005221 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00005222 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005223 }
Chris Lattnera27231a2003-03-10 23:13:59 +00005224 }
Chris Lattnera2881962003-02-18 19:28:33 +00005225
Reid Spencere4d87aa2006-12-23 06:05:41 +00005226 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5227 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005228 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005229 return R;
5230
Chris Lattner69d4ced2008-11-16 05:20:07 +00005231 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5232 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5233 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005234 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005235
5236 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005237 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005238 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005239 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005240 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5241 !isa<ICmpInst>(Op1C->getOperand(0))) {
5242 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005243 if (SrcTy == Op1C->getOperand(0)->getType() &&
5244 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005245 // Only do this if the casts both really cause code to be
5246 // generated.
5247 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5248 I.getType(), TD) &&
5249 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5250 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005251 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5252 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005253 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005254 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005255 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005256 }
Chris Lattner99c65742007-10-24 05:38:08 +00005257 }
5258
5259
5260 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5261 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005262 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5263 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5264 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005265 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005266
Chris Lattner7e708292002-06-25 16:13:24 +00005267 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005268}
5269
Dan Gohman844731a2008-05-13 00:00:25 +00005270namespace {
5271
Chris Lattnerc317d392004-02-16 01:20:27 +00005272// XorSelf - Implements: X ^ X --> 0
5273struct XorSelf {
5274 Value *RHS;
5275 XorSelf(Value *rhs) : RHS(rhs) {}
5276 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5277 Instruction *apply(BinaryOperator &Xor) const {
5278 return &Xor;
5279 }
5280};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005281
Dan Gohman844731a2008-05-13 00:00:25 +00005282}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005283
Chris Lattner7e708292002-06-25 16:13:24 +00005284Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005285 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005287
Evan Chengd34af782008-03-25 20:07:13 +00005288 if (isa<UndefValue>(Op1)) {
5289 if (isa<UndefValue>(Op0))
5290 // Handle undef ^ undef -> 0 special case. This is a common
5291 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005292 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005293 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005294 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005295
Chris Lattnerc317d392004-02-16 01:20:27 +00005296 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005297 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005298 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005299 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005300 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005301
5302 // See if we can simplify any instructions used by the instruction whose sole
5303 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005304 if (SimplifyDemandedInstructionBits(I))
5305 return &I;
5306 if (isa<VectorType>(I.getType()))
5307 if (isa<ConstantAggregateZero>(Op1))
5308 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005309
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005310 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005311 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005312 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5313 if (Op0I->getOpcode() == Instruction::And ||
5314 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005315 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5316 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5317 if (dyn_castNotVal(Op0I->getOperand(1)))
5318 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005319 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005320 Value *NotY =
5321 Builder->CreateNot(Op0I->getOperand(1),
5322 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005323 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005324 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005325 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005326 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005327
5328 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5329 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5330 if (isFreeToInvert(Op0I->getOperand(0)) &&
5331 isFreeToInvert(Op0I->getOperand(1))) {
5332 Value *NotX =
5333 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5334 Value *NotY =
5335 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5336 if (Op0I->getOpcode() == Instruction::And)
5337 return BinaryOperator::CreateOr(NotX, NotY);
5338 return BinaryOperator::CreateAnd(NotX, NotY);
5339 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005340 }
5341 }
5342 }
5343
5344
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005345 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005346 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005347 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005348 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005349 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005351
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005352 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005353 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005354 FCI->getOperand(0), FCI->getOperand(1));
5355 }
5356
Nick Lewycky517e1f52008-05-31 19:01:33 +00005357 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5358 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5359 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5360 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5361 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005362 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5363 (RHS == ConstantExpr::getCast(Opcode,
5364 ConstantInt::getTrue(*Context),
5365 Op0C->getDestTy()))) {
5366 CI->setPredicate(CI->getInversePredicate());
5367 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005368 }
5369 }
5370 }
5371 }
5372
Reid Spencere4d87aa2006-12-23 06:05:41 +00005373 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005374 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005375 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5376 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005377 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5378 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005379 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005380 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005381 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005382
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005383 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005384 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005385 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005386 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005387 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005388 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005389 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005390 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005391 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005392 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005393 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005394 Constant *C = ConstantInt::get(*Context,
5395 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005396 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005397
Chris Lattner7c4049c2004-01-12 19:35:11 +00005398 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005399 } else if (Op0I->getOpcode() == Instruction::Or) {
5400 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005401 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005402 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005403 // Anything in both C1 and C2 is known to be zero, remove it from
5404 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005405 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5406 NewRHS = ConstantExpr::getAnd(NewRHS,
5407 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005408 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005409 I.setOperand(0, Op0I->getOperand(0));
5410 I.setOperand(1, NewRHS);
5411 return &I;
5412 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005413 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005414 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005415 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005416
5417 // Try to fold constant and into select arguments.
5418 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005419 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005420 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005421 if (isa<PHINode>(Op0))
5422 if (Instruction *NV = FoldOpIntoPhi(I))
5423 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005424 }
5425
Dan Gohman186a6362009-08-12 16:04:34 +00005426 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005427 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005428 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005429
Dan Gohman186a6362009-08-12 16:04:34 +00005430 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005431 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005432 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005433
Chris Lattner318bf792007-03-18 22:51:34 +00005434
5435 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5436 if (Op1I) {
5437 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005438 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005439 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005440 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005441 I.swapOperands();
5442 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005443 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005444 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005445 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005446 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005447 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005448 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005449 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005450 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005451 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005452 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005453 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005454 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005455 std::swap(A, B);
5456 }
Chris Lattner318bf792007-03-18 22:51:34 +00005457 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005458 I.swapOperands(); // Simplified below.
5459 std::swap(Op0, Op1);
5460 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005461 }
Chris Lattner318bf792007-03-18 22:51:34 +00005462 }
5463
5464 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5465 if (Op0I) {
5466 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005467 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005468 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005469 if (A == Op1) // (B|A)^B == (A|B)^B
5470 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005471 if (B == Op1) // (A|B)^B == A & ~B
5472 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005473 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005474 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005475 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005476 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005477 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005478 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005479 if (A == Op1) // (A&B)^A -> (B&A)^A
5480 std::swap(A, B);
5481 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005482 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005483 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005484 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005485 }
Chris Lattner318bf792007-03-18 22:51:34 +00005486 }
5487
5488 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5489 if (Op0I && Op1I && Op0I->isShift() &&
5490 Op0I->getOpcode() == Op1I->getOpcode() &&
5491 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5492 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005493 Value *NewOp =
5494 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5495 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005496 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005497 Op1I->getOperand(1));
5498 }
5499
5500 if (Op0I && Op1I) {
5501 Value *A, *B, *C, *D;
5502 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005503 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5504 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005505 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005506 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005507 }
5508 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005509 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5510 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005511 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005512 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005513 }
5514
5515 // (A & B)^(C & D)
5516 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005517 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5518 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005519 // (X & Y)^(X & Y) -> (Y^Z) & X
5520 Value *X = 0, *Y = 0, *Z = 0;
5521 if (A == C)
5522 X = A, Y = B, Z = D;
5523 else if (A == D)
5524 X = A, Y = B, Z = C;
5525 else if (B == C)
5526 X = B, Y = A, Z = D;
5527 else if (B == D)
5528 X = B, Y = A, Z = C;
5529
5530 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005531 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005532 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005533 }
5534 }
5535 }
5536
Reid Spencere4d87aa2006-12-23 06:05:41 +00005537 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5538 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005539 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005540 return R;
5541
Chris Lattner6fc205f2006-05-05 06:39:07 +00005542 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005543 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005544 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005545 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5546 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005547 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005548 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005549 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5550 I.getType(), TD) &&
5551 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5552 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005553 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5554 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005555 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005556 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005557 }
Chris Lattner99c65742007-10-24 05:38:08 +00005558 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005559
Chris Lattner7e708292002-06-25 16:13:24 +00005560 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005561}
5562
Owen Andersond672ecb2009-07-03 00:17:18 +00005563static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005564 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005565 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005566}
Chris Lattnera96879a2004-09-29 17:40:11 +00005567
Dan Gohman6de29f82009-06-15 22:12:54 +00005568static bool HasAddOverflow(ConstantInt *Result,
5569 ConstantInt *In1, ConstantInt *In2,
5570 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005571 if (IsSigned)
5572 if (In2->getValue().isNegative())
5573 return Result->getValue().sgt(In1->getValue());
5574 else
5575 return Result->getValue().slt(In1->getValue());
5576 else
5577 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005578}
5579
Dan Gohman6de29f82009-06-15 22:12:54 +00005580/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005581/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005582static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005583 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005584 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005585 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005586
Dan Gohman6de29f82009-06-15 22:12:54 +00005587 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5588 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005589 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005590 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5591 ExtractElement(In1, Idx, Context),
5592 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005593 IsSigned))
5594 return true;
5595 }
5596 return false;
5597 }
5598
5599 return HasAddOverflow(cast<ConstantInt>(Result),
5600 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5601 IsSigned);
5602}
5603
5604static bool HasSubOverflow(ConstantInt *Result,
5605 ConstantInt *In1, ConstantInt *In2,
5606 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005607 if (IsSigned)
5608 if (In2->getValue().isNegative())
5609 return Result->getValue().slt(In1->getValue());
5610 else
5611 return Result->getValue().sgt(In1->getValue());
5612 else
5613 return Result->getValue().ugt(In1->getValue());
5614}
5615
Dan Gohman6de29f82009-06-15 22:12:54 +00005616/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5617/// overflowed for this type.
5618static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005619 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005620 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005621 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005622
5623 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5624 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005625 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005626 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5627 ExtractElement(In1, Idx, Context),
5628 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005629 IsSigned))
5630 return true;
5631 }
5632 return false;
5633 }
5634
5635 return HasSubOverflow(cast<ConstantInt>(Result),
5636 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5637 IsSigned);
5638}
5639
Chris Lattner10c0d912008-04-22 02:53:33 +00005640
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005642/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005643Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005644 ICmpInst::Predicate Cond,
5645 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005646 // Look through bitcasts.
5647 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5648 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005649
Chris Lattner574da9b2005-01-13 20:14:25 +00005650 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005651 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005652 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005653 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005654 // know pointers can't overflow since the gep is inbounds. See if we can
5655 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005656 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5657
5658 // If not, synthesize the offset the hard way.
5659 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005660 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005661 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005662 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005663 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005664 // If the base pointers are different, but the indices are the same, just
5665 // compare the base pointer.
5666 if (PtrBase != GEPRHS->getOperand(0)) {
5667 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005668 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005669 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005670 if (IndicesTheSame)
5671 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5672 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5673 IndicesTheSame = false;
5674 break;
5675 }
5676
5677 // If all indices are the same, just compare the base pointers.
5678 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005679 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005680 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005681
5682 // Otherwise, the base pointers are different and the indices are
5683 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005684 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005685 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005686
Chris Lattnere9d782b2005-01-13 22:25:21 +00005687 // If one of the GEPs has all zero indices, recurse.
5688 bool AllZeros = true;
5689 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5690 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5691 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5692 AllZeros = false;
5693 break;
5694 }
5695 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005696 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5697 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005698
5699 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005700 AllZeros = true;
5701 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5702 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5703 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5704 AllZeros = false;
5705 break;
5706 }
5707 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005708 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005709
Chris Lattner4401c9c2005-01-14 00:20:05 +00005710 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5711 // If the GEPs only differ by one index, compare it.
5712 unsigned NumDifferences = 0; // Keep track of # differences.
5713 unsigned DiffOperand = 0; // The operand that differs.
5714 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5715 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005716 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5717 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005718 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005719 NumDifferences = 2;
5720 break;
5721 } else {
5722 if (NumDifferences++) break;
5723 DiffOperand = i;
5724 }
5725 }
5726
5727 if (NumDifferences == 0) // SAME GEP?
5728 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005729 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005730 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005731
Chris Lattner4401c9c2005-01-14 00:20:05 +00005732 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005733 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5734 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005735 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005736 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005737 }
5738 }
5739
Reid Spencere4d87aa2006-12-23 06:05:41 +00005740 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005741 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005742 if (TD &&
5743 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005744 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5745 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005746 Value *L = EmitGEPOffset(GEPLHS, *this);
5747 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005748 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005749 }
5750 }
5751 return 0;
5752}
5753
Chris Lattnera5406232008-05-19 20:18:56 +00005754/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5755///
5756Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5757 Instruction *LHSI,
5758 Constant *RHSC) {
5759 if (!isa<ConstantFP>(RHSC)) return 0;
5760 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5761
5762 // Get the width of the mantissa. We don't want to hack on conversions that
5763 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005764 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005765 if (MantissaWidth == -1) return 0; // Unknown.
5766
5767 // Check to see that the input is converted from an integer type that is small
5768 // enough that preserves all bits. TODO: check here for "known" sign bits.
5769 // 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 +00005770 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005771
5772 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005773 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5774 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005775 ++InputSize;
5776
5777 // If the conversion would lose info, don't hack on this.
5778 if ((int)InputSize > MantissaWidth)
5779 return 0;
5780
5781 // Otherwise, we can potentially simplify the comparison. We know that it
5782 // will always come through as an integer value and we know the constant is
5783 // not a NAN (it would have been previously simplified).
5784 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5785
5786 ICmpInst::Predicate Pred;
5787 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005788 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005789 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005790 case FCmpInst::FCMP_OEQ:
5791 Pred = ICmpInst::ICMP_EQ;
5792 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005793 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005794 case FCmpInst::FCMP_OGT:
5795 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5796 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005797 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005798 case FCmpInst::FCMP_OGE:
5799 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5800 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005801 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005802 case FCmpInst::FCMP_OLT:
5803 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5804 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005805 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005806 case FCmpInst::FCMP_OLE:
5807 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5808 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005809 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005810 case FCmpInst::FCMP_ONE:
5811 Pred = ICmpInst::ICMP_NE;
5812 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005813 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005814 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005815 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005816 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005817 }
5818
5819 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5820
5821 // Now we know that the APFloat is a normal number, zero or inf.
5822
Chris Lattner85162782008-05-20 03:50:52 +00005823 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005824 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005825 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005826
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005827 if (!LHSUnsigned) {
5828 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5829 // and large values.
5830 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5831 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5832 APFloat::rmNearestTiesToEven);
5833 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5834 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5835 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005836 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5837 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005838 }
5839 } else {
5840 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5841 // +INF and large values.
5842 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5843 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5844 APFloat::rmNearestTiesToEven);
5845 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5846 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5847 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005848 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5849 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005850 }
Chris Lattnera5406232008-05-19 20:18:56 +00005851 }
5852
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005853 if (!LHSUnsigned) {
5854 // See if the RHS value is < SignedMin.
5855 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5856 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5857 APFloat::rmNearestTiesToEven);
5858 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5859 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5860 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005861 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5862 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005863 }
Chris Lattnera5406232008-05-19 20:18:56 +00005864 }
5865
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005866 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5867 // [0, UMAX], but it may still be fractional. See if it is fractional by
5868 // casting the FP value to the integer value and back, checking for equality.
5869 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005870 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005871 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5872 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005873 if (!RHS.isZero()) {
5874 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005875 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5876 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005877 if (!Equal) {
5878 // If we had a comparison against a fractional value, we have to adjust
5879 // the compare predicate and sometimes the value. RHSC is rounded towards
5880 // zero at this point.
5881 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005882 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005883 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005885 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005887 case ICmpInst::ICMP_ULE:
5888 // (float)int <= 4.4 --> int <= 4
5889 // (float)int <= -4.4 --> false
5890 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005891 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005892 break;
5893 case ICmpInst::ICMP_SLE:
5894 // (float)int <= 4.4 --> int <= 4
5895 // (float)int <= -4.4 --> int < -4
5896 if (RHS.isNegative())
5897 Pred = ICmpInst::ICMP_SLT;
5898 break;
5899 case ICmpInst::ICMP_ULT:
5900 // (float)int < -4.4 --> false
5901 // (float)int < 4.4 --> int <= 4
5902 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005903 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005904 Pred = ICmpInst::ICMP_ULE;
5905 break;
5906 case ICmpInst::ICMP_SLT:
5907 // (float)int < -4.4 --> int < -4
5908 // (float)int < 4.4 --> int <= 4
5909 if (!RHS.isNegative())
5910 Pred = ICmpInst::ICMP_SLE;
5911 break;
5912 case ICmpInst::ICMP_UGT:
5913 // (float)int > 4.4 --> int > 4
5914 // (float)int > -4.4 --> true
5915 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005916 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005917 break;
5918 case ICmpInst::ICMP_SGT:
5919 // (float)int > 4.4 --> int > 4
5920 // (float)int > -4.4 --> int >= -4
5921 if (RHS.isNegative())
5922 Pred = ICmpInst::ICMP_SGE;
5923 break;
5924 case ICmpInst::ICMP_UGE:
5925 // (float)int >= -4.4 --> true
5926 // (float)int >= 4.4 --> int > 4
5927 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005928 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005929 Pred = ICmpInst::ICMP_UGT;
5930 break;
5931 case ICmpInst::ICMP_SGE:
5932 // (float)int >= -4.4 --> int >= -4
5933 // (float)int >= 4.4 --> int > 4
5934 if (!RHS.isNegative())
5935 Pred = ICmpInst::ICMP_SGT;
5936 break;
5937 }
Chris Lattnera5406232008-05-19 20:18:56 +00005938 }
5939 }
5940
5941 // Lower this FP comparison into an appropriate integer version of the
5942 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005943 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005944}
5945
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5947 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005948 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005949
Chris Lattner58e97462007-01-14 19:42:17 +00005950 // Fold trivial predicates.
5951 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005952 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005953 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005954 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005955
5956 // Simplify 'fcmp pred X, X'
5957 if (Op0 == Op1) {
5958 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005959 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005960 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5961 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5962 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005963 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005964 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5965 case FCmpInst::FCMP_OLT: // True if ordered and less than
5966 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005967 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005968
5969 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5970 case FCmpInst::FCMP_ULT: // True if unordered or less than
5971 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5972 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5973 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5974 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005975 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005976 return &I;
5977
5978 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5979 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5980 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5981 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5982 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5983 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005984 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005985 return &I;
5986 }
5987 }
5988
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005990 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005991
Reid Spencere4d87aa2006-12-23 06:05:41 +00005992 // Handle fcmp with constant RHS
5993 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005994 // If the constant is a nan, see if we can fold the comparison based on it.
5995 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5996 if (CFP->getValueAPF().isNaN()) {
5997 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005998 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005999 assert(FCmpInst::isUnordered(I.getPredicate()) &&
6000 "Comparison must be either ordered or unordered!");
6001 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00006002 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00006003 }
6004 }
6005
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6007 switch (LHSI->getOpcode()) {
6008 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006009 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6010 // block. If in the same block, we're encouraging jump threading. If
6011 // not, we are just pessimizing the code by making an i1 phi.
6012 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006013 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006014 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006015 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006016 case Instruction::SIToFP:
6017 case Instruction::UIToFP:
6018 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6019 return NV;
6020 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006021 case Instruction::Select:
6022 // If either operand of the select is a constant, we can fold the
6023 // comparison into the select arms, which will cause one to be
6024 // constant folded and the select turned into a bitwise or.
6025 Value *Op1 = 0, *Op2 = 0;
6026 if (LHSI->hasOneUse()) {
6027 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6028 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006029 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006030 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006031 Op2 = Builder->CreateFCmp(I.getPredicate(),
6032 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006033 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6034 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006035 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006036 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006037 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6038 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006039 }
6040 }
6041
6042 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006043 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006044 break;
6045 }
6046 }
6047
6048 return Changed ? &I : 0;
6049}
6050
6051Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6052 bool Changed = SimplifyCompare(I);
6053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6054 const Type *Ty = Op0->getType();
6055
6056 // icmp X, X
6057 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00006058 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006059 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006060
6061 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00006062 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006063
Reid Spencere4d87aa2006-12-23 06:05:41 +00006064 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006065 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00006066 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00006067 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00006068 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006069 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006070 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006071 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006072
Reid Spencere4d87aa2006-12-23 06:05:41 +00006073 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006074 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006075 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006076 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006077 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006078 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006079 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006080 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006081 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006082 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006083
Reid Spencere4d87aa2006-12-23 06:05:41 +00006084 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006085 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006086 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006087 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006088 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006089 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006090 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006091 case ICmpInst::ICMP_SGT:
6092 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006093 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006094 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006095 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006096 return BinaryOperator::CreateAnd(Not, Op0);
6097 }
6098 case ICmpInst::ICMP_UGE:
6099 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6100 // FALL THROUGH
6101 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006102 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006103 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006104 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006105 case ICmpInst::ICMP_SGE:
6106 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6107 // FALL THROUGH
6108 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006109 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006110 return BinaryOperator::CreateOr(Not, Op0);
6111 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006112 }
Chris Lattner8b170942002-08-09 23:47:40 +00006113 }
6114
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 unsigned BitWidth = 0;
6116 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006117 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6118 else if (Ty->isIntOrIntVector())
6119 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120
6121 bool isSignBit = false;
6122
Dan Gohman81b28ce2008-09-16 18:46:06 +00006123 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006124 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006125 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006126
Chris Lattnerb6566012008-01-05 01:18:20 +00006127 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6128 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006129 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006130 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006131 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006132 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006133
Dan Gohman81b28ce2008-09-16 18:46:06 +00006134 // If we have an icmp le or icmp ge instruction, turn it into the
6135 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6136 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006137 switch (I.getPredicate()) {
6138 default: break;
6139 case ICmpInst::ICMP_ULE:
6140 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006141 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006142 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006143 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006144 case ICmpInst::ICMP_SLE:
6145 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006147 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006148 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006149 case ICmpInst::ICMP_UGE:
6150 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006151 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006152 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006153 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006154 case ICmpInst::ICMP_SGE:
6155 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006156 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006157 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006158 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006159 }
6160
Chris Lattner183661e2008-07-11 05:40:05 +00006161 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006162 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006163 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6165 }
6166
6167 // See if we can fold the comparison based on range information we can get
6168 // by checking whether bits are known to be zero or one in the input.
6169 if (BitWidth != 0) {
6170 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6171 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6172
6173 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006174 isSignBit ? APInt::getSignBit(BitWidth)
6175 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006177 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 if (SimplifyDemandedBits(I.getOperandUse(1),
6179 APInt::getAllOnesValue(BitWidth),
6180 Op1KnownZero, Op1KnownOne, 0))
6181 return &I;
6182
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006183 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006184 // in. Compute the Min, Max and RHS values based on the known bits. For the
6185 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6187 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006188 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006189 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6190 Op0Min, Op0Max);
6191 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6192 Op1Min, Op1Max);
6193 } else {
6194 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6195 Op0Min, Op0Max);
6196 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6197 Op1Min, Op1Max);
6198 }
6199
Chris Lattner183661e2008-07-11 05:40:05 +00006200 // If Min and Max are known to be the same, then SimplifyDemandedBits
6201 // figured out that the LHS is a constant. Just constant fold this now so
6202 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006204 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006205 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006207 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006208 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209
Chris Lattner183661e2008-07-11 05:40:05 +00006210 // Based on the range information we know about the LHS, see if we can
6211 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006213 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006214 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006216 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006217 break;
6218 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006220 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006221 break;
6222 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006224 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006225 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006226 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006227 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006228 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6230 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006231 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006232 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233
6234 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6235 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006236 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006237 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 }
Chris Lattner84dff672008-07-11 05:08:55 +00006239 break;
6240 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006242 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006243 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006244 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245
6246 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006247 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006248 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6249 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006250 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006251 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006252
6253 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6254 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006255 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006256 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006257 }
Chris Lattner84dff672008-07-11 05:08:55 +00006258 break;
6259 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006260 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006261 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006262 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006263 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006264 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006265 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006266 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6267 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006268 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006269 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006270 }
Chris Lattner84dff672008-07-11 05:08:55 +00006271 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006272 case ICmpInst::ICMP_SGT:
6273 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006274 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006275 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006276 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006277
6278 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006279 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006280 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6281 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006282 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006283 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006284 }
6285 break;
6286 case ICmpInst::ICMP_SGE:
6287 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6288 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006289 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006290 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006291 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006292 break;
6293 case ICmpInst::ICMP_SLE:
6294 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6295 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006296 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006297 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006298 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006299 break;
6300 case ICmpInst::ICMP_UGE:
6301 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6302 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006303 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006304 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006305 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006306 break;
6307 case ICmpInst::ICMP_ULE:
6308 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6309 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006310 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006311 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006312 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006313 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006314 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006315
6316 // Turn a signed comparison into an unsigned one if both operands
6317 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006318 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006319 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6320 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006321 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006322 }
6323
6324 // Test if the ICmpInst instruction is used exclusively by a select as
6325 // part of a minimum or maximum operation. If so, refrain from doing
6326 // any other folding. This helps out other analyses which understand
6327 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6328 // and CodeGen. And in this case, at least one of the comparison
6329 // operands has at least one user besides the compare (the select),
6330 // which would often largely negate the benefit of folding anyway.
6331 if (I.hasOneUse())
6332 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6333 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6334 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6335 return 0;
6336
6337 // See if we are doing a comparison between a constant and an instruction that
6338 // can be folded into the comparison.
6339 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006340 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006341 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006342 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006343 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006344 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6345 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006346 }
6347
Chris Lattner01deb9d2007-04-03 17:43:25 +00006348 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006349 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6350 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6351 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006352 case Instruction::GetElementPtr:
6353 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006354 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006355 bool isAllZeros = true;
6356 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6357 if (!isa<Constant>(LHSI->getOperand(i)) ||
6358 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6359 isAllZeros = false;
6360 break;
6361 }
6362 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006363 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006364 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006365 }
6366 break;
6367
Chris Lattner6970b662005-04-23 15:31:55 +00006368 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006369 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006370 // block. If in the same block, we're encouraging jump threading. If
6371 // not, we are just pessimizing the code by making an i1 phi.
6372 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006373 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006374 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006375 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006376 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006377 // If either operand of the select is a constant, we can fold the
6378 // comparison into the select arms, which will cause one to be
6379 // constant folded and the select turned into a bitwise or.
6380 Value *Op1 = 0, *Op2 = 0;
6381 if (LHSI->hasOneUse()) {
6382 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6383 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006384 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006385 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006386 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6387 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006388 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6389 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006390 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006392 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6393 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006394 }
6395 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006396
Chris Lattner6970b662005-04-23 15:31:55 +00006397 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006398 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006399 break;
6400 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006401 case Instruction::Call:
6402 // If we have (malloc != null), and if the malloc has a single use, we
6403 // can assume it is successful and remove the malloc.
6404 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6405 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006406 // Need to explicitly erase malloc call here, instead of adding it to
6407 // Worklist, because it won't get DCE'd from the Worklist since
6408 // isInstructionTriviallyDead() returns false for function calls.
6409 // It is OK to replace LHSI/MallocCall with Undef because the
6410 // instruction that uses it will be erased via Worklist.
6411 if (extractMallocCall(LHSI)) {
6412 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6413 EraseInstFromFunction(*LHSI);
6414 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006415 ConstantInt::get(Type::getInt1Ty(*Context),
6416 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006417 }
6418 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6419 if (MallocCall->hasOneUse()) {
6420 MallocCall->replaceAllUsesWith(
6421 UndefValue::get(MallocCall->getType()));
6422 EraseInstFromFunction(*MallocCall);
6423 Worklist.Add(LHSI); // The malloc's bitcast use.
6424 return ReplaceInstUsesWith(I,
6425 ConstantInt::get(Type::getInt1Ty(*Context),
6426 !I.isTrueWhenEqual()));
6427 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006428 }
6429 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006430 }
Chris Lattner6970b662005-04-23 15:31:55 +00006431 }
6432
Reid Spencere4d87aa2006-12-23 06:05:41 +00006433 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006434 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006435 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006436 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006437 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006438 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6439 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006440 return NI;
6441
Reid Spencere4d87aa2006-12-23 06:05:41 +00006442 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006443 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6444 // now.
6445 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6446 if (isa<PointerType>(Op0->getType()) &&
6447 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006448 // We keep moving the cast from the left operand over to the right
6449 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006450 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006451
Chris Lattner57d86372007-01-06 01:45:59 +00006452 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6453 // so eliminate it as well.
6454 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6455 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006456
Chris Lattnerde90b762003-11-03 04:25:02 +00006457 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006458 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006459 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006460 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006461 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006462 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006463 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006464 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006465 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006466 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006467 }
Chris Lattner57d86372007-01-06 01:45:59 +00006468 }
6469
6470 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006471 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006472 // This comes up when you have code like
6473 // int X = A < B;
6474 // if (X) ...
6475 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006476 // with a constant or another cast from the same type.
6477 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006478 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006479 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006480 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006481
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006482 // See if it's the same type of instruction on the left and right.
6483 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6484 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006485 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006486 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006487 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006488 default: break;
6489 case Instruction::Add:
6490 case Instruction::Sub:
6491 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006492 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006493 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006494 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006495 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6496 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6497 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006498 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006499 ? I.getUnsignedPredicate()
6500 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006501 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006502 Op1I->getOperand(0));
6503 }
6504
6505 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006506 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006507 ? I.getUnsignedPredicate()
6508 : I.getSignedPredicate();
6509 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006510 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006511 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006512 }
6513 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006514 break;
6515 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006516 if (!I.isEquality())
6517 break;
6518
Nick Lewycky5d52c452008-08-21 05:56:10 +00006519 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6520 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6521 // Mask = -1 >> count-trailing-zeros(Cst).
6522 if (!CI->isZero() && !CI->isOne()) {
6523 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006524 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006525 APInt::getLowBitsSet(AP.getBitWidth(),
6526 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006527 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006528 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6529 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006530 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006531 }
6532 }
6533 break;
6534 }
6535 }
6536 }
6537 }
6538
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006539 // ~x < ~y --> y < x
6540 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006541 if (match(Op0, m_Not(m_Value(A))) &&
6542 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006543 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006544 }
6545
Chris Lattner65b72ba2006-09-18 04:22:48 +00006546 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006547 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006548
6549 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006550 if (match(Op0, m_Neg(m_Value(A))) &&
6551 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006552 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006553
Dan Gohman4ae51262009-08-12 16:23:25 +00006554 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006555 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6556 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006557 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006558 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006559 }
6560
Dan Gohman4ae51262009-08-12 16:23:25 +00006561 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006562 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006563 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006564 if (match(B, m_ConstantInt(C1)) &&
6565 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006566 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006567 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006568 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6569 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006570 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006571
6572 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006573 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6574 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6575 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6576 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006577 }
6578 }
6579
Dan Gohman4ae51262009-08-12 16:23:25 +00006580 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006581 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006582 // A == (A^B) -> B == 0
6583 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006584 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006585 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006586 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006587
6588 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006589 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006590 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006591 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006592
6593 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006594 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006595 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006596 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006597
Chris Lattner9c2328e2006-11-14 06:06:06 +00006598 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6599 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006600 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6601 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006602 Value *X = 0, *Y = 0, *Z = 0;
6603
6604 if (A == C) {
6605 X = B; Y = D; Z = A;
6606 } else if (A == D) {
6607 X = B; Y = C; Z = A;
6608 } else if (B == C) {
6609 X = A; Y = D; Z = B;
6610 } else if (B == D) {
6611 X = A; Y = C; Z = B;
6612 }
6613
6614 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006615 Op1 = Builder->CreateXor(X, Y, "tmp");
6616 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006617 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006618 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006619 return &I;
6620 }
6621 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006622 }
Chris Lattner7e708292002-06-25 16:13:24 +00006623 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006624}
6625
Chris Lattner562ef782007-06-20 23:46:26 +00006626
6627/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6628/// and CmpRHS are both known to be integer constants.
6629Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6630 ConstantInt *DivRHS) {
6631 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6632 const APInt &CmpRHSV = CmpRHS->getValue();
6633
6634 // FIXME: If the operand types don't match the type of the divide
6635 // then don't attempt this transform. The code below doesn't have the
6636 // logic to deal with a signed divide and an unsigned compare (and
6637 // vice versa). This is because (x /s C1) <s C2 produces different
6638 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6639 // (x /u C1) <u C2. Simply casting the operands and result won't
6640 // work. :( The if statement below tests that condition and bails
6641 // if it finds it.
6642 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006643 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006644 return 0;
6645 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006647 if (DivIsSigned && DivRHS->isAllOnesValue())
6648 return 0; // The overflow computation also screws up here
6649 if (DivRHS->isOne())
6650 return 0; // Not worth bothering, and eliminates some funny cases
6651 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006652
6653 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6654 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6655 // C2 (CI). By solving for X we can turn this into a range check
6656 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006657 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006658
6659 // Determine if the product overflows by seeing if the product is
6660 // not equal to the divide. Make sure we do the same kind of divide
6661 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006662 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6663 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006664
6665 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006667
Chris Lattner1dbfd482007-06-21 18:11:19 +00006668 // Figure out the interval that is being checked. For example, a comparison
6669 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6670 // Compute this interval based on the constants involved and the signedness of
6671 // the compare/divide. This computes a half-open interval, keeping track of
6672 // whether either value in the interval overflows. After analysis each
6673 // overflow variable is set to 0 if it's corresponding bound variable is valid
6674 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6675 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006676 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006677
Chris Lattner562ef782007-06-20 23:46:26 +00006678 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006679 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006680 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006681 HiOverflow = LoOverflow = ProdOV;
6682 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006683 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006684 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006685 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006686 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006687 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006688 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006689 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006690 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6691 HiOverflow = LoOverflow = ProdOV;
6692 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006693 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006694 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006695 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006696 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006697 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6698 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006699 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006700 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006701 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006702 true) ? -1 : 0;
6703 }
Chris Lattner562ef782007-06-20 23:46:26 +00006704 }
Dan Gohman76491272008-02-13 22:09:18 +00006705 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006706 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006707 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006708 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006709 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006710 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6711 HiOverflow = 1; // [INTMIN+1, overflow)
6712 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6713 }
Dan Gohman76491272008-02-13 22:09:18 +00006714 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006715 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006716 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006717 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006718 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006719 LoOverflow = AddWithOverflow(LoBound, HiBound,
6720 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006721 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006722 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6723 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006724 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006725 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006726 }
6727
Chris Lattner1dbfd482007-06-21 18:11:19 +00006728 // Dividing by a negative swaps the condition. LT <-> GT
6729 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006730 }
6731
6732 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006733 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006734 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006735 case ICmpInst::ICMP_EQ:
6736 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006737 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006738 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006739 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006740 ICmpInst::ICMP_UGE, X, LoBound);
6741 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006742 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006743 ICmpInst::ICMP_ULT, X, HiBound);
6744 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006745 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006746 case ICmpInst::ICMP_NE:
6747 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006748 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006749 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006750 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006751 ICmpInst::ICMP_ULT, X, LoBound);
6752 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006753 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006754 ICmpInst::ICMP_UGE, X, HiBound);
6755 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006756 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006757 case ICmpInst::ICMP_ULT:
6758 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006759 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006760 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006761 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006762 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006763 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006764 case ICmpInst::ICMP_UGT:
6765 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006766 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006767 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006768 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006769 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006770 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006771 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006772 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006773 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006774 }
6775}
6776
6777
Chris Lattner01deb9d2007-04-03 17:43:25 +00006778/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6779///
6780Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6781 Instruction *LHSI,
6782 ConstantInt *RHS) {
6783 const APInt &RHSV = RHS->getValue();
6784
6785 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006786 case Instruction::Trunc:
6787 if (ICI.isEquality() && LHSI->hasOneUse()) {
6788 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6789 // of the high bits truncated out of x are known.
6790 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6791 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6792 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6793 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6794 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6795
6796 // If all the high bits are known, we can do this xform.
6797 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6798 // Pull in the high bits from known-ones set.
6799 APInt NewRHS(RHS->getValue());
6800 NewRHS.zext(SrcBits);
6801 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006802 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006803 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006804 }
6805 }
6806 break;
6807
Duncan Sands0091bf22007-04-04 06:42:45 +00006808 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006809 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6810 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6811 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006812 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6813 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006814 Value *CompareVal = LHSI->getOperand(0);
6815
6816 // If the sign bit of the XorCST is not set, there is no change to
6817 // the operation, just stop using the Xor.
6818 if (!XorCST->getValue().isNegative()) {
6819 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006820 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006821 return &ICI;
6822 }
6823
6824 // Was the old condition true if the operand is positive?
6825 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6826
6827 // If so, the new one isn't.
6828 isTrueIfPositive ^= true;
6829
6830 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006831 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006832 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006833 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006834 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006835 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006836 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006837
6838 if (LHSI->hasOneUse()) {
6839 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6840 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6841 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006842 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006843 ? ICI.getUnsignedPredicate()
6844 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006845 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006846 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006847 }
6848
6849 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006850 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006851 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006852 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006853 ? ICI.getUnsignedPredicate()
6854 : ICI.getSignedPredicate();
6855 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006856 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006857 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006858 }
6859 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006860 }
6861 break;
6862 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6863 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6864 LHSI->getOperand(0)->hasOneUse()) {
6865 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6866
6867 // If the LHS is an AND of a truncating cast, we can widen the
6868 // and/compare to be the input width without changing the value
6869 // produced, eliminating a cast.
6870 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6871 // We can do this transformation if either the AND constant does not
6872 // have its sign bit set or if it is an equality comparison.
6873 // Extending a relational comparison when we're checking the sign
6874 // bit would not work.
6875 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006876 (ICI.isEquality() ||
6877 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006878 uint32_t BitWidth =
6879 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6880 APInt NewCST = AndCST->getValue();
6881 NewCST.zext(BitWidth);
6882 APInt NewCI = RHSV;
6883 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006884 Value *NewAnd =
6885 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006886 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006887 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006888 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006889 }
6890 }
6891
6892 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6893 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6894 // happens a LOT in code produced by the C front-end, for bitfield
6895 // access.
6896 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6897 if (Shift && !Shift->isShift())
6898 Shift = 0;
6899
6900 ConstantInt *ShAmt;
6901 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6902 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6903 const Type *AndTy = AndCST->getType(); // Type of the and.
6904
6905 // We can fold this as long as we can't shift unknown bits
6906 // into the mask. This can only happen with signed shift
6907 // rights, as they sign-extend.
6908 if (ShAmt) {
6909 bool CanFold = Shift->isLogicalShift();
6910 if (!CanFold) {
6911 // To test for the bad case of the signed shr, see if any
6912 // of the bits shifted in could be tested after the mask.
6913 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6914 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6915
6916 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6917 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6918 AndCST->getValue()) == 0)
6919 CanFold = true;
6920 }
6921
6922 if (CanFold) {
6923 Constant *NewCst;
6924 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006925 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006926 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006927 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006928
6929 // Check to see if we are shifting out any of the bits being
6930 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006931 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006932 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006933 // If we shifted bits out, the fold is not going to work out.
6934 // As a special case, check to see if this means that the
6935 // result is always true or false now.
6936 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006937 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006938 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006939 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006940 } else {
6941 ICI.setOperand(1, NewCst);
6942 Constant *NewAndCST;
6943 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006944 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006945 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006946 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006947 LHSI->setOperand(1, NewAndCST);
6948 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006949 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006950 return &ICI;
6951 }
6952 }
6953 }
6954
6955 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6956 // preferable because it allows the C<<Y expression to be hoisted out
6957 // of a loop if Y is invariant and X is not.
6958 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006959 ICI.isEquality() && !Shift->isArithmeticShift() &&
6960 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006961 // Compute C << Y.
6962 Value *NS;
6963 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006964 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006965 } else {
6966 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006967 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006968 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006969
6970 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006971 Value *NewAnd =
6972 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006973
6974 ICI.setOperand(0, NewAnd);
6975 return &ICI;
6976 }
6977 }
6978 break;
6979
Chris Lattnera0141b92007-07-15 20:42:37 +00006980 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6981 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6982 if (!ShAmt) break;
6983
6984 uint32_t TypeBits = RHSV.getBitWidth();
6985
6986 // Check that the shift amount is in range. If not, don't perform
6987 // undefined shifts. When the shift is visited it will be
6988 // simplified.
6989 if (ShAmt->uge(TypeBits))
6990 break;
6991
6992 if (ICI.isEquality()) {
6993 // If we are comparing against bits always shifted out, the
6994 // comparison cannot succeed.
6995 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006996 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006997 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006998 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6999 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007000 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007001 return ReplaceInstUsesWith(ICI, Cst);
7002 }
7003
7004 if (LHSI->hasOneUse()) {
7005 // Otherwise strength reduce the shift into an and.
7006 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7007 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007008 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007009 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007010
Chris Lattner74381062009-08-30 07:44:24 +00007011 Value *And =
7012 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007013 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007014 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007015 }
7016 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007017
7018 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7019 bool TrueIfSigned = false;
7020 if (LHSI->hasOneUse() &&
7021 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7022 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007023 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007024 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007025 Value *And =
7026 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007027 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007028 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007029 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007030 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007031 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007032
7033 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007034 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007035 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007036 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007037 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007038
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007039 // Check that the shift amount is in range. If not, don't perform
7040 // undefined shifts. When the shift is visited it will be
7041 // simplified.
7042 uint32_t TypeBits = RHSV.getBitWidth();
7043 if (ShAmt->uge(TypeBits))
7044 break;
7045
7046 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007047
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007048 // If we are comparing against bits always shifted out, the
7049 // comparison cannot succeed.
7050 APInt Comp = RHSV << ShAmtVal;
7051 if (LHSI->getOpcode() == Instruction::LShr)
7052 Comp = Comp.lshr(ShAmtVal);
7053 else
7054 Comp = Comp.ashr(ShAmtVal);
7055
7056 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7057 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007058 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007059 return ReplaceInstUsesWith(ICI, Cst);
7060 }
7061
7062 // Otherwise, check to see if the bits shifted out are known to be zero.
7063 // If so, we can compare against the unshifted value:
7064 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007065 if (LHSI->hasOneUse() &&
7066 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007067 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007068 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007069 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007070 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007071
Evan Chengf30752c2008-04-23 00:38:06 +00007072 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007073 // Otherwise strength reduce the shift into an and.
7074 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007075 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007076
Chris Lattner74381062009-08-30 07:44:24 +00007077 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7078 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007079 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007080 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081 }
7082 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007083 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007084
7085 case Instruction::SDiv:
7086 case Instruction::UDiv:
7087 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7088 // Fold this div into the comparison, producing a range check.
7089 // Determine, based on the divide type, what the range is being
7090 // checked. If there is an overflow on the low or high side, remember
7091 // it, otherwise compute the range [low, hi) bounding the new value.
7092 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007093 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7094 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7095 DivRHS))
7096 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007098
7099 case Instruction::Add:
7100 // Fold: icmp pred (add, X, C1), C2
7101
7102 if (!ICI.isEquality()) {
7103 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7104 if (!LHSC) break;
7105 const APInt &LHSV = LHSC->getValue();
7106
7107 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7108 .subtract(LHSV);
7109
Nick Lewycky4a134af2009-10-25 05:20:17 +00007110 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007111 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007112 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007113 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007114 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007115 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007116 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007117 }
7118 } else {
7119 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007120 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007121 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007122 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007123 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007124 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007125 }
7126 }
7127 }
7128 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007129 }
7130
7131 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7132 if (ICI.isEquality()) {
7133 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7134
7135 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7136 // the second operand is a constant, simplify a bit.
7137 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7138 switch (BO->getOpcode()) {
7139 case Instruction::SRem:
7140 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7141 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7142 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7143 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007144 Value *NewRem =
7145 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7146 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007147 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007148 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149 }
7150 }
7151 break;
7152 case Instruction::Add:
7153 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7154 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7155 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007156 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007157 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 } else if (RHSV == 0) {
7159 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7160 // efficiently invertible, or if the add has just this one use.
7161 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7162
Dan Gohman186a6362009-08-12 16:04:34 +00007163 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007164 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007165 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007166 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007167 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007168 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007170 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007171 }
7172 }
7173 break;
7174 case Instruction::Xor:
7175 // For the xor case, we can xor two constants together, eliminating
7176 // the explicit xor.
7177 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007178 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007179 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007180
7181 // FALLTHROUGH
7182 case Instruction::Sub:
7183 // Replace (([sub|xor] A, B) != 0) with (A != B)
7184 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007185 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007186 BO->getOperand(1));
7187 break;
7188
7189 case Instruction::Or:
7190 // If bits are being or'd in that are not present in the constant we
7191 // are comparing against, then the comparison could never succeed!
7192 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007193 Constant *NotCI = ConstantExpr::getNot(RHS);
7194 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007195 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007196 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007197 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007198 }
7199 break;
7200
7201 case Instruction::And:
7202 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7203 // If bits are being compared against that are and'd out, then the
7204 // comparison can never succeed!
7205 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007206 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007207 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007208 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007209
7210 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7211 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007212 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007213 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007214 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007215
7216 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007217 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007218 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007219 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007220 ICmpInst::Predicate pred = isICMP_NE ?
7221 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007222 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007223 }
7224
7225 // ((X & ~7) == 0) --> X < 8
7226 if (RHSV == 0 && isHighOnes(BOC)) {
7227 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007228 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007229 ICmpInst::Predicate pred = isICMP_NE ?
7230 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007231 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007232 }
7233 }
7234 default: break;
7235 }
7236 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7237 // Handle icmp {eq|ne} <intrinsic>, intcst.
7238 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007239 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007240 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007241 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007242 return &ICI;
7243 }
7244 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007245 }
7246 return 0;
7247}
7248
7249/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7250/// We only handle extending casts so far.
7251///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007252Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7253 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007254 Value *LHSCIOp = LHSCI->getOperand(0);
7255 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007256 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007257 Value *RHSCIOp;
7258
Chris Lattner8c756c12007-05-05 22:41:33 +00007259 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7260 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007261 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7262 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007263 cast<IntegerType>(DestTy)->getBitWidth()) {
7264 Value *RHSOp = 0;
7265 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007266 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007267 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7268 RHSOp = RHSC->getOperand(0);
7269 // If the pointer types don't match, insert a bitcast.
7270 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007271 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007272 }
7273
7274 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007275 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007276 }
7277
7278 // The code below only handles extension cast instructions, so far.
7279 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 if (LHSCI->getOpcode() != Instruction::ZExt &&
7281 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007282 return 0;
7283
Reid Spencere4d87aa2006-12-23 06:05:41 +00007284 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007285 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007286
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007288 // Not an extension from the same type?
7289 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007290 if (RHSCIOp->getType() != LHSCIOp->getType())
7291 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007292
Nick Lewycky4189a532008-01-28 03:48:02 +00007293 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007294 // and the other is a zext), then we can't handle this.
7295 if (CI->getOpcode() != LHSCI->getOpcode())
7296 return 0;
7297
Nick Lewycky4189a532008-01-28 03:48:02 +00007298 // Deal with equality cases early.
7299 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007300 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007301
7302 // A signed comparison of sign extended values simplifies into a
7303 // signed comparison.
7304 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007305 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007306
7307 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007308 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007309 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007310
Reid Spencere4d87aa2006-12-23 06:05:41 +00007311 // If we aren't dealing with a constant on the RHS, exit early
7312 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7313 if (!CI)
7314 return 0;
7315
7316 // Compute the constant that would happen if we truncated to SrcTy then
7317 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007318 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7319 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007320 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007321
7322 // If the re-extended constant didn't change...
7323 if (Res2 == CI) {
7324 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7325 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007326 // %A = sext i16 %X to i32
7327 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007328 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007329 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007330 // because %A may have negative value.
7331 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007332 // However, we allow this when the compare is EQ/NE, because they are
7333 // signless.
7334 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007335 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007336 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007337 }
7338
7339 // The re-extended constant changed so the constant cannot be represented
7340 // in the shorter type. Consequently, we cannot emit a simple comparison.
7341
7342 // First, handle some easy cases. We know the result cannot be equal at this
7343 // point so handle the ICI.isEquality() cases
7344 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007345 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007346 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007347 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007348
7349 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7350 // should have been folded away previously and not enter in here.
7351 Value *Result;
7352 if (isSignedCmp) {
7353 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007354 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007355 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007356 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007357 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007358 } else {
7359 // We're performing an unsigned comparison.
7360 if (isSignedExt) {
7361 // We're performing an unsigned comp with a sign extended value.
7362 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007363 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007364 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007365 } else {
7366 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007367 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007368 }
7369 }
7370
7371 // Finally, return the value computed.
7372 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007373 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007374 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007375
7376 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7377 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7378 "ICmp should be folded!");
7379 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007380 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007381 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007382}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007383
Reid Spencer832254e2007-02-02 02:16:23 +00007384Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7385 return commonShiftTransforms(I);
7386}
7387
7388Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7389 return commonShiftTransforms(I);
7390}
7391
7392Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007393 if (Instruction *R = commonShiftTransforms(I))
7394 return R;
7395
7396 Value *Op0 = I.getOperand(0);
7397
7398 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7399 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7400 if (CSI->isAllOnesValue())
7401 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007402
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007403 // See if we can turn a signed shr into an unsigned shr.
7404 if (MaskedValueIsZero(Op0,
7405 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7406 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7407
7408 // Arithmetic shifting an all-sign-bit value is a no-op.
7409 unsigned NumSignBits = ComputeNumSignBits(Op0);
7410 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7411 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007412
Chris Lattner348f6652007-12-06 01:59:46 +00007413 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007414}
7415
7416Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7417 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007418 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007419
7420 // shl X, 0 == X and shr X, 0 == X
7421 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007422 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7423 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007424 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007425
Reid Spencere4d87aa2006-12-23 06:05:41 +00007426 if (isa<UndefValue>(Op0)) {
7427 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007428 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007429 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007430 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007431 }
7432 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007433 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7434 return ReplaceInstUsesWith(I, Op0);
7435 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007436 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007437 }
7438
Dan Gohman9004c8a2009-05-21 02:28:33 +00007439 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007440 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007441 return &I;
7442
Chris Lattner2eefe512004-04-09 19:05:30 +00007443 // Try to fold constant and into select arguments.
7444 if (isa<Constant>(Op0))
7445 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007446 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007447 return R;
7448
Reid Spencerb83eb642006-10-20 07:07:24 +00007449 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007450 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7451 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007452 return 0;
7453}
7454
Reid Spencerb83eb642006-10-20 07:07:24 +00007455Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007456 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007457 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007458
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007459 // See if we can simplify any instructions used by the instruction whose sole
7460 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007461 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007462
Dan Gohmana119de82009-06-14 23:30:43 +00007463 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7464 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007465 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007466 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007467 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007468 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007469 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007470 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007471 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007472 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473 }
7474
7475 // ((X*C1) << C2) == (X * (C1 << C2))
7476 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7477 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7478 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007479 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007480 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007481
7482 // Try to fold constant and into select arguments.
7483 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7484 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7485 return R;
7486 if (isa<PHINode>(Op0))
7487 if (Instruction *NV = FoldOpIntoPhi(I))
7488 return NV;
7489
Chris Lattner8999dd32007-12-22 09:07:47 +00007490 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7491 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7492 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7493 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7494 // place. Don't try to do this transformation in this case. Also, we
7495 // require that the input operand is a shift-by-constant so that we have
7496 // confidence that the shifts will get folded together. We could do this
7497 // xform in more cases, but it is unlikely to be profitable.
7498 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7499 isa<ConstantInt>(TrOp->getOperand(1))) {
7500 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007501 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007502 // (shift2 (shift1 & 0x00FF), c2)
7503 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007504
7505 // For logical shifts, the truncation has the effect of making the high
7506 // part of the register be zeros. Emulate this by inserting an AND to
7507 // clear the top bits as needed. This 'and' will usually be zapped by
7508 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007509 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7510 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007511 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7512
7513 // The mask we constructed says what the trunc would do if occurring
7514 // between the shifts. We want to know the effect *after* the second
7515 // shift. We know that it is a logical shift by a constant, so adjust the
7516 // mask as appropriate.
7517 if (I.getOpcode() == Instruction::Shl)
7518 MaskV <<= Op1->getZExtValue();
7519 else {
7520 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7521 MaskV = MaskV.lshr(Op1->getZExtValue());
7522 }
7523
Chris Lattner74381062009-08-30 07:44:24 +00007524 // shift1 & 0x00FF
7525 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7526 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007527
7528 // Return the value truncated to the interesting size.
7529 return new TruncInst(And, I.getType());
7530 }
7531 }
7532
Chris Lattner4d5542c2006-01-06 07:12:35 +00007533 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007534 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7535 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7536 Value *V1, *V2;
7537 ConstantInt *CC;
7538 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007539 default: break;
7540 case Instruction::Add:
7541 case Instruction::And:
7542 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007543 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007544 // These operators commute.
7545 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007546 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007547 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007548 m_Specific(Op1)))) {
7549 Value *YS = // (Y << C)
7550 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7551 // (X + (Y << C))
7552 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7553 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007554 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007555 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007556 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007557 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007558
Chris Lattner150f12a2005-09-18 06:30:59 +00007559 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007560 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007561 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007562 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007563 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007564 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007565 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007566 Value *YS = // (Y << C)
7567 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7568 Op0BO->getName());
7569 // X & (CC << C)
7570 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7571 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007572 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007573 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007574 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007575
Reid Spencera07cb7d2007-02-02 14:41:37 +00007576 // FALL THROUGH.
7577 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007578 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007579 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007580 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007581 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007582 Value *YS = // (Y << C)
7583 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7584 // (X + (Y << C))
7585 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7586 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007587 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007588 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007589 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007590 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007591
Chris Lattner13d4ab42006-05-31 21:14:00 +00007592 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007593 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7594 match(Op0BO->getOperand(0),
7595 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007596 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007597 cast<BinaryOperator>(Op0BO->getOperand(0))
7598 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007599 Value *YS = // (Y << C)
7600 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7601 // X & (CC << C)
7602 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7603 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007604
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007605 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007606 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007607
Chris Lattner11021cb2005-09-18 05:12:10 +00007608 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007609 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007610 }
7611
7612
7613 // If the operand is an bitwise operator with a constant RHS, and the
7614 // shift is the only use, we can pull it out of the shift.
7615 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7616 bool isValid = true; // Valid only for And, Or, Xor
7617 bool highBitSet = false; // Transform if high bit of constant set?
7618
7619 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007620 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007621 case Instruction::Add:
7622 isValid = isLeftShift;
7623 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007624 case Instruction::Or:
7625 case Instruction::Xor:
7626 highBitSet = false;
7627 break;
7628 case Instruction::And:
7629 highBitSet = true;
7630 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007631 }
7632
7633 // If this is a signed shift right, and the high bit is modified
7634 // by the logical operation, do not perform the transformation.
7635 // The highBitSet boolean indicates the value of the high bit of
7636 // the constant which would cause it to be modified for this
7637 // operation.
7638 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007639 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007640 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007641
7642 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007643 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007644
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007645 Value *NewShift =
7646 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007647 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007648
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007649 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007650 NewRHS);
7651 }
7652 }
7653 }
7654 }
7655
Chris Lattnerad0124c2006-01-06 07:52:12 +00007656 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007657 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7658 if (ShiftOp && !ShiftOp->isShift())
7659 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007660
Reid Spencerb83eb642006-10-20 07:07:24 +00007661 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007662 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007663 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7664 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007665 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7666 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7667 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007668
Zhou Sheng4351c642007-04-02 08:20:41 +00007669 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007670
7671 const IntegerType *Ty = cast<IntegerType>(I.getType());
7672
7673 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007674 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007675 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7676 // saturates.
7677 if (AmtSum >= TypeBits) {
7678 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007679 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007680 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7681 }
7682
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007683 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007684 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007685 }
7686
7687 if (ShiftOp->getOpcode() == Instruction::LShr &&
7688 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007689 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007691
Chris Lattnerb87056f2007-02-05 00:57:54 +00007692 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007693 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007694 }
7695
7696 if (ShiftOp->getOpcode() == Instruction::AShr &&
7697 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007698 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007699 if (AmtSum >= TypeBits)
7700 AmtSum = TypeBits-1;
7701
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007702 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703
Zhou Shenge9e03f62007-03-28 15:02:20 +00007704 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007705 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007706 }
7707
Chris Lattnerb87056f2007-02-05 00:57:54 +00007708 // Okay, if we get here, one shift must be left, and the other shift must be
7709 // right. See if the amounts are equal.
7710 if (ShiftAmt1 == ShiftAmt2) {
7711 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7712 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007713 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007714 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007715 }
7716 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7717 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007718 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007719 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007720 }
7721 // We can simplify ((X << C) >>s C) into a trunc + sext.
7722 // NOTE: we could do this for any C, but that would make 'unusual' integer
7723 // types. For now, just stick to ones well-supported by the code
7724 // generators.
7725 const Type *SExtType = 0;
7726 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007727 case 1 :
7728 case 8 :
7729 case 16 :
7730 case 32 :
7731 case 64 :
7732 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007733 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007734 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007735 default: break;
7736 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007737 if (SExtType)
7738 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007739 // Otherwise, we can't handle it yet.
7740 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007741 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007742
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007743 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007744 if (I.getOpcode() == Instruction::Shl) {
7745 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7746 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007747 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007748
Reid Spencer55702aa2007-03-25 21:11:44 +00007749 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007750 return BinaryOperator::CreateAnd(Shift,
7751 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007752 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007753
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007754 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007755 if (I.getOpcode() == Instruction::LShr) {
7756 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007757 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007758
Reid Spencerd5e30f02007-03-26 17:18:58 +00007759 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007760 return BinaryOperator::CreateAnd(Shift,
7761 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007762 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007763
7764 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7765 } else {
7766 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007767 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007768
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007769 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007770 if (I.getOpcode() == Instruction::Shl) {
7771 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7772 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007773 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7774 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007775
Reid Spencer55702aa2007-03-25 21:11:44 +00007776 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007777 return BinaryOperator::CreateAnd(Shift,
7778 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007779 }
7780
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007781 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007782 if (I.getOpcode() == Instruction::LShr) {
7783 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007784 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007785
Reid Spencer68d27cf2007-03-26 23:45:51 +00007786 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007787 return BinaryOperator::CreateAnd(Shift,
7788 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007789 }
7790
7791 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007792 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007793 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007794 return 0;
7795}
7796
Chris Lattnera1be5662002-05-02 17:06:02 +00007797
Chris Lattnercfd65102005-10-29 04:36:15 +00007798/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7799/// expression. If so, decompose it, returning some value X, such that Val is
7800/// X*Scale+Offset.
7801///
7802static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007803 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007804 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7805 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007806 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007807 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007808 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007809 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007810 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7811 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7812 if (I->getOpcode() == Instruction::Shl) {
7813 // This is a value scaled by '1 << the shift amt'.
7814 Scale = 1U << RHS->getZExtValue();
7815 Offset = 0;
7816 return I->getOperand(0);
7817 } else if (I->getOpcode() == Instruction::Mul) {
7818 // This value is scaled by 'RHS'.
7819 Scale = RHS->getZExtValue();
7820 Offset = 0;
7821 return I->getOperand(0);
7822 } else if (I->getOpcode() == Instruction::Add) {
7823 // We have X+C. Check to see if we really have (X*C2)+C1,
7824 // where C1 is divisible by C2.
7825 unsigned SubScale;
7826 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007827 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7828 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007829 Offset += RHS->getZExtValue();
7830 Scale = SubScale;
7831 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007832 }
7833 }
7834 }
7835
7836 // Otherwise, we can't look past this.
7837 Scale = 1;
7838 Offset = 0;
7839 return Val;
7840}
7841
7842
Chris Lattnerb3f83972005-10-24 06:03:58 +00007843/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7844/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007845Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007846 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007847 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007848
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007849 BuilderTy AllocaBuilder(*Builder);
7850 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7851
Chris Lattnerb53c2382005-10-24 06:22:12 +00007852 // Remove any uses of AI that are dead.
7853 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007854
Chris Lattnerb53c2382005-10-24 06:22:12 +00007855 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7856 Instruction *User = cast<Instruction>(*UI++);
7857 if (isInstructionTriviallyDead(User)) {
7858 while (UI != E && *UI == User)
7859 ++UI; // If this instruction uses AI more than once, don't break UI.
7860
Chris Lattnerb53c2382005-10-24 06:22:12 +00007861 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007862 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007863 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007864 }
7865 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007866
7867 // This requires TargetData to get the alloca alignment and size information.
7868 if (!TD) return 0;
7869
Chris Lattnerb3f83972005-10-24 06:03:58 +00007870 // Get the type really allocated and the type casted to.
7871 const Type *AllocElTy = AI.getAllocatedType();
7872 const Type *CastElTy = PTy->getElementType();
7873 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007874
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007875 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7876 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007877 if (CastElTyAlign < AllocElTyAlign) return 0;
7878
Chris Lattner39387a52005-10-24 06:35:18 +00007879 // If the allocation has multiple uses, only promote it if we are strictly
7880 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007881 // same, we open the door to infinite loops of various kinds. (A reference
7882 // from a dbg.declare doesn't count as a use for this purpose.)
7883 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7884 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007885
Duncan Sands777d2302009-05-09 07:06:46 +00007886 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7887 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007888 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007889
Chris Lattner455fcc82005-10-29 03:19:53 +00007890 // See if we can satisfy the modulus by pulling a scale out of the array
7891 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007892 unsigned ArraySizeScale;
7893 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007894 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007895 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7896 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007897
Chris Lattner455fcc82005-10-29 03:19:53 +00007898 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7899 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007900 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7901 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007902
Chris Lattner455fcc82005-10-29 03:19:53 +00007903 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7904 Value *Amt = 0;
7905 if (Scale == 1) {
7906 Amt = NumElements;
7907 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007908 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007909 // Insert before the alloca, not before the cast.
7910 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007911 }
7912
Jeff Cohen86796be2007-04-04 16:58:57 +00007913 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007914 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007915 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007916 }
7917
Victor Hernandez7b929da2009-10-23 21:09:37 +00007918 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007919 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007920 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007921
Dale Johannesena0a66372009-03-05 00:39:02 +00007922 // If the allocation has one real use plus a dbg.declare, just remove the
7923 // declare.
7924 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7925 EraseInstFromFunction(*DI);
7926 }
7927 // If the allocation has multiple real uses, insert a cast and change all
7928 // things that used it to use the new cast. This will also hack on CI, but it
7929 // will die soon.
7930 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007931 // New is the allocation instruction, pointer typed. AI is the original
7932 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007933 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007934 AI.replaceAllUsesWith(NewCast);
7935 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007936 return ReplaceInstUsesWith(CI, New);
7937}
7938
Chris Lattner70074e02006-05-13 02:06:03 +00007939/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940/// and return it as type Ty without inserting any new casts and without
7941/// changing the computed value. This is used by code that tries to decide
7942/// whether promoting or shrinking integer operations to wider or smaller types
7943/// will allow us to eliminate a truncate or extend.
7944///
7945/// This is a truncation operation if Ty is smaller than V->getType(), or an
7946/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007947///
7948/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7949/// should return true if trunc(V) can be computed by computing V in the smaller
7950/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7951/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7952/// efficiently truncated.
7953///
7954/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7955/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7956/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007957bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007958 unsigned CastOpc,
7959 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007960 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007961 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007962 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007963
7964 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007965 if (!I) return false;
7966
Dan Gohman6de29f82009-06-15 22:12:54 +00007967 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007968
Chris Lattner951626b2007-08-02 06:11:14 +00007969 // If this is an extension or truncate, we can often eliminate it.
7970 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7971 // If this is a cast from the destination type, we can trivially eliminate
7972 // it, and this will remove a cast overall.
7973 if (I->getOperand(0)->getType() == Ty) {
7974 // If the first operand is itself a cast, and is eliminable, do not count
7975 // this as an eliminable cast. We would prefer to eliminate those two
7976 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007977 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007978 ++NumCastsRemoved;
7979 return true;
7980 }
7981 }
7982
7983 // We can't extend or shrink something that has multiple uses: doing so would
7984 // require duplicating the instruction in general, which isn't profitable.
7985 if (!I->hasOneUse()) return false;
7986
Evan Chengf35fd542009-01-15 17:01:23 +00007987 unsigned Opc = I->getOpcode();
7988 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007989 case Instruction::Add:
7990 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007991 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007992 case Instruction::And:
7993 case Instruction::Or:
7994 case Instruction::Xor:
7995 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007996 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007997 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007998 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007999 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008000
Eli Friedman070a9812009-07-13 22:46:01 +00008001 case Instruction::UDiv:
8002 case Instruction::URem: {
8003 // UDiv and URem can be truncated if all the truncated bits are zero.
8004 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8005 uint32_t BitWidth = Ty->getScalarSizeInBits();
8006 if (BitWidth < OrigBitWidth) {
8007 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8008 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8009 MaskedValueIsZero(I->getOperand(1), Mask)) {
8010 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8011 NumCastsRemoved) &&
8012 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8013 NumCastsRemoved);
8014 }
8015 }
8016 break;
8017 }
Chris Lattner46b96052006-11-29 07:18:39 +00008018 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008019 // If we are truncating the result of this SHL, and if it's a shift of a
8020 // constant amount, we can always perform a SHL in a smaller type.
8021 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008022 uint32_t BitWidth = Ty->getScalarSizeInBits();
8023 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008024 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008025 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008026 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008027 }
8028 break;
8029 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008030 // If this is a truncate of a logical shr, we can truncate it to a smaller
8031 // lshr iff we know that the bits we would otherwise be shifting in are
8032 // already zeros.
8033 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008034 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8035 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008036 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008037 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008038 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8039 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008040 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008041 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008042 }
8043 }
Chris Lattner46b96052006-11-29 07:18:39 +00008044 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008045 case Instruction::ZExt:
8046 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008047 case Instruction::Trunc:
8048 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008049 // can safely replace it. Note that replacing it does not reduce the number
8050 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008051 if (Opc == CastOpc)
8052 return true;
8053
8054 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008055 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008056 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008057 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008058 case Instruction::Select: {
8059 SelectInst *SI = cast<SelectInst>(I);
8060 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008061 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008062 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008063 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008064 }
Chris Lattner8114b712008-06-18 04:00:49 +00008065 case Instruction::PHI: {
8066 // We can change a phi if we can change all operands.
8067 PHINode *PN = cast<PHINode>(I);
8068 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8069 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008070 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008071 return false;
8072 return true;
8073 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008074 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008075 // TODO: Can handle more cases here.
8076 break;
8077 }
8078
8079 return false;
8080}
8081
8082/// EvaluateInDifferentType - Given an expression that
8083/// CanEvaluateInDifferentType returns true for, actually insert the code to
8084/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008085Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008086 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008087 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008088 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008089
8090 // Otherwise, it must be an instruction.
8091 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008092 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008093 unsigned Opc = I->getOpcode();
8094 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008095 case Instruction::Add:
8096 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008097 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008098 case Instruction::And:
8099 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008100 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008101 case Instruction::AShr:
8102 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008103 case Instruction::Shl:
8104 case Instruction::UDiv:
8105 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008106 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008107 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008108 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008109 break;
8110 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008111 case Instruction::Trunc:
8112 case Instruction::ZExt:
8113 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008114 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008115 // just return the source. There's no need to insert it because it is not
8116 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008117 if (I->getOperand(0)->getType() == Ty)
8118 return I->getOperand(0);
8119
Chris Lattner8114b712008-06-18 04:00:49 +00008120 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008121 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008122 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008123 case Instruction::Select: {
8124 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8125 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8126 Res = SelectInst::Create(I->getOperand(0), True, False);
8127 break;
8128 }
Chris Lattner8114b712008-06-18 04:00:49 +00008129 case Instruction::PHI: {
8130 PHINode *OPN = cast<PHINode>(I);
8131 PHINode *NPN = PHINode::Create(Ty);
8132 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8133 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8134 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8135 }
8136 Res = NPN;
8137 break;
8138 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008139 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008140 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008141 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008142 break;
8143 }
8144
Chris Lattner8114b712008-06-18 04:00:49 +00008145 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008146 return InsertNewInstBefore(Res, *I);
8147}
8148
Reid Spencer3da59db2006-11-27 01:05:10 +00008149/// @brief Implement the transforms common to all CastInst visitors.
8150Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008151 Value *Src = CI.getOperand(0);
8152
Dan Gohman23d9d272007-05-11 21:10:54 +00008153 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008155 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008156 if (Instruction::CastOps opc =
8157 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8158 // The first cast (CSrc) is eliminable so we need to fix up or replace
8159 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008160 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008161 }
8162 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008163
Reid Spencer3da59db2006-11-27 01:05:10 +00008164 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008165 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8166 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8167 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008168
8169 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008170 if (isa<PHINode>(Src)) {
8171 // We don't do this if this would create a PHI node with an illegal type if
8172 // it is currently legal.
8173 if (!isa<IntegerType>(Src->getType()) ||
8174 !isa<IntegerType>(CI.getType()) ||
8175 (TD && TD->isLegalInteger(CI.getType()->getPrimitiveSizeInBits())) ||
8176 (TD && !TD->isLegalInteger(Src->getType()->getPrimitiveSizeInBits())))
8177 if (Instruction *NV = FoldOpIntoPhi(CI))
8178 return NV;
8179
8180 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008181
Reid Spencer3da59db2006-11-27 01:05:10 +00008182 return 0;
8183}
8184
Chris Lattner46cd5a12009-01-09 05:44:56 +00008185/// FindElementAtOffset - Given a type and a constant offset, determine whether
8186/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008187/// the specified offset. If so, fill them into NewIndices and return the
8188/// resultant element type, otherwise return null.
8189static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8190 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008191 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008192 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008193 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008194 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008195
8196 // Start with the index over the outer type. Note that the type size
8197 // might be zero (even if the offset isn't zero) if the indexed type
8198 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008199 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008200 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008201 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008202 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008203 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008204
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008205 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008206 if (Offset < 0) {
8207 --FirstIdx;
8208 Offset += TySize;
8209 assert(Offset >= 0);
8210 }
8211 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8212 }
8213
Owen Andersoneed707b2009-07-24 23:12:02 +00008214 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008215
8216 // Index into the types. If we fail, set OrigBase to null.
8217 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008218 // Indexing into tail padding between struct/array elements.
8219 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008220 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008221
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8223 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008224 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8225 "Offset must stay within the indexed type");
8226
Chris Lattner46cd5a12009-01-09 05:44:56 +00008227 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008228 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008229
8230 Offset -= SL->getElementOffset(Elt);
8231 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008232 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008233 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008234 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008235 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008236 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008237 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008238 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008239 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008240 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008241 }
8242 }
8243
Chris Lattner3914f722009-01-24 01:00:13 +00008244 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008245}
8246
Chris Lattnerd3e28342007-04-27 17:44:50 +00008247/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8248Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8249 Value *Src = CI.getOperand(0);
8250
Chris Lattnerd3e28342007-04-27 17:44:50 +00008251 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008252 // If casting the result of a getelementptr instruction with no offset, turn
8253 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008254 if (GEP->hasAllZeroIndices()) {
8255 // Changing the cast operand is usually not a good idea but it is safe
8256 // here because the pointer operand is being replaced with another
8257 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008258 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008259 CI.setOperand(0, GEP->getOperand(0));
8260 return &CI;
8261 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008262
8263 // If the GEP has a single use, and the base pointer is a bitcast, and the
8264 // GEP computes a constant offset, see if we can convert these three
8265 // instructions into fewer. This typically happens with unions and other
8266 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008267 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008268 if (GEP->hasAllConstantIndices()) {
8269 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008270 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008271 int64_t Offset = OffsetV->getSExtValue();
8272
8273 // Get the base pointer input of the bitcast, and the type it points to.
8274 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8275 const Type *GEPIdxTy =
8276 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008277 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008278 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008279 // If we were able to index down into an element, create the GEP
8280 // and bitcast the result. This eliminates one bitcast, potentially
8281 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008282 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8283 Builder->CreateInBoundsGEP(OrigBase,
8284 NewIndices.begin(), NewIndices.end()) :
8285 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008286 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008287
Chris Lattner46cd5a12009-01-09 05:44:56 +00008288 if (isa<BitCastInst>(CI))
8289 return new BitCastInst(NGEP, CI.getType());
8290 assert(isa<PtrToIntInst>(CI));
8291 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008292 }
8293 }
8294 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008295 }
8296
8297 return commonCastTransforms(CI);
8298}
8299
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008300/// commonIntCastTransforms - This function implements the common transforms
8301/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008302Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8303 if (Instruction *Result = commonCastTransforms(CI))
8304 return Result;
8305
8306 Value *Src = CI.getOperand(0);
8307 const Type *SrcTy = Src->getType();
8308 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008309 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8310 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008311
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 // See if we can simplify any instructions used by the LHS whose sole
8313 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008314 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008315 return &CI;
8316
8317 // If the source isn't an instruction or has more than one use then we
8318 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008319 Instruction *SrcI = dyn_cast<Instruction>(Src);
8320 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008321 return 0;
8322
Chris Lattnerc739cd62007-03-03 05:27:34 +00008323 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008324 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008325 // Only do this if the dest type is a simple type, don't convert the
8326 // expression tree to something weird like i93 unless the source is also
8327 // strange.
Chris Lattner918871e2009-11-07 19:11:46 +00008328 if (TD &&
8329 (TD->isLegalInteger(DestTy->getScalarType()->getPrimitiveSizeInBits()) ||
8330 !TD->isLegalInteger((SrcI->getType()->getScalarType()
8331 ->getPrimitiveSizeInBits()))) &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008332 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008333 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008334 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008335 // eliminates the cast, so it is always a win. If this is a zero-extension,
8336 // we need to do an AND to maintain the clear top-part of the computation,
8337 // so we require that the input have eliminated at least one cast. If this
8338 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008339 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008340 bool DoXForm = false;
8341 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008342 switch (CI.getOpcode()) {
8343 default:
8344 // All the others use floating point so we shouldn't actually
8345 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008346 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008347 case Instruction::Trunc:
8348 DoXForm = true;
8349 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008350 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008351 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008352
Chris Lattner39c27ed2009-01-31 19:05:27 +00008353 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008354 // If it's unnecessary to issue an AND to clear the high bits, it's
8355 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008356 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008357 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8358 if (MaskedValueIsZero(TryRes, Mask))
8359 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008360
8361 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008362 if (TryI->use_empty())
8363 EraseInstFromFunction(*TryI);
8364 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008365 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008366 }
Evan Chengf35fd542009-01-15 17:01:23 +00008367 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008368 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008369 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008370 // If we do not have to emit the truncate + sext pair, then it's always
8371 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008372 //
8373 // It's not safe to eliminate the trunc + sext pair if one of the
8374 // eliminated cast is a truncate. e.g.
8375 // t2 = trunc i32 t1 to i16
8376 // t3 = sext i16 t2 to i32
8377 // !=
8378 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008379 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008380 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8381 if (NumSignBits > (DestBitSize - SrcBitSize))
8382 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008383
8384 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008385 if (TryI->use_empty())
8386 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008387 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008388 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008389 }
Evan Chengf35fd542009-01-15 17:01:23 +00008390 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008391
8392 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008393 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8394 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008395 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8396 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008397 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008398 // Just replace this cast with the result.
8399 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008400
Reid Spencer3da59db2006-11-27 01:05:10 +00008401 assert(Res->getType() == DestTy);
8402 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008403 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008404 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008405 // Just replace this cast with the result.
8406 return ReplaceInstUsesWith(CI, Res);
8407 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008408 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008409
8410 // If the high bits are already zero, just replace this cast with the
8411 // result.
8412 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8413 if (MaskedValueIsZero(Res, Mask))
8414 return ReplaceInstUsesWith(CI, Res);
8415
8416 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008417 Constant *C = ConstantInt::get(*Context,
8418 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008419 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008421 case Instruction::SExt: {
8422 // If the high bits are already filled with sign bit, just replace this
8423 // cast with the result.
8424 unsigned NumSignBits = ComputeNumSignBits(Res);
8425 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008426 return ReplaceInstUsesWith(CI, Res);
8427
Reid Spencer3da59db2006-11-27 01:05:10 +00008428 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008429 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008430 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008431 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008432 }
8433 }
8434
8435 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8436 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8437
8438 switch (SrcI->getOpcode()) {
8439 case Instruction::Add:
8440 case Instruction::Mul:
8441 case Instruction::And:
8442 case Instruction::Or:
8443 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008444 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008445 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8446 // Don't insert two casts unless at least one can be eliminated.
8447 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008448 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008449 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8450 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008451 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008452 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008453 }
8454 }
8455
8456 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8457 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8458 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008459 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008460 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008461 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008462 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008463 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008464 }
8465 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008466
Eli Friedman65445c52009-07-13 21:45:57 +00008467 case Instruction::Shl: {
8468 // Canonicalize trunc inside shl, if we can.
8469 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8470 if (CI && DestBitSize < SrcBitSize &&
8471 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008472 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8473 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008474 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008475 }
8476 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008477 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008478 }
8479 return 0;
8480}
8481
Chris Lattner8a9f5712007-04-11 06:57:46 +00008482Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008483 if (Instruction *Result = commonIntCastTransforms(CI))
8484 return Result;
8485
8486 Value *Src = CI.getOperand(0);
8487 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008488 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8489 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008490
8491 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008492 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008493 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008494 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008495 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008496 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008497 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008498
Chris Lattner4f9797d2009-03-24 18:15:30 +00008499 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8500 ConstantInt *ShAmtV = 0;
8501 Value *ShiftOp = 0;
8502 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008503 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008504 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8505
8506 // Get a mask for the bits shifting in.
8507 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8508 if (MaskedValueIsZero(ShiftOp, Mask)) {
8509 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008510 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008511
8512 // Okay, we can shrink this. Truncate the input, then return a new
8513 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008514 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008515 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008516 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008517 }
8518 }
Chris Lattner9956c052009-11-08 19:23:30 +00008519
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008520 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008521}
8522
Evan Chengb98a10e2008-03-24 00:21:34 +00008523/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8524/// in order to eliminate the icmp.
8525Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8526 bool DoXform) {
8527 // If we are just checking for a icmp eq of a single bit and zext'ing it
8528 // to an integer, then shift the bit to the appropriate place and then
8529 // cast to integer to avoid the comparison.
8530 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8531 const APInt &Op1CV = Op1C->getValue();
8532
8533 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8534 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8535 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8536 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8537 if (!DoXform) return ICI;
8538
8539 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008540 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008541 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008542 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008543 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008544 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008545
8546 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008547 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008548 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008549 }
8550
8551 return ReplaceInstUsesWith(CI, In);
8552 }
8553
8554
8555
8556 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8557 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8558 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8559 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8560 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8561 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8562 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8563 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8564 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8565 // This only works for EQ and NE
8566 ICI->isEquality()) {
8567 // If Op1C some other power of two, convert:
8568 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8569 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8570 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8571 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8572
8573 APInt KnownZeroMask(~KnownZero);
8574 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8575 if (!DoXform) return ICI;
8576
8577 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8578 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8579 // (X&4) == 2 --> false
8580 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008581 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008582 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008583 return ReplaceInstUsesWith(CI, Res);
8584 }
8585
8586 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8587 Value *In = ICI->getOperand(0);
8588 if (ShiftAmt) {
8589 // Perform a logical shr by shiftamt.
8590 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008591 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8592 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008593 }
8594
8595 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008596 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008597 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008598 }
8599
8600 if (CI.getType() == In->getType())
8601 return ReplaceInstUsesWith(CI, In);
8602 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008603 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008604 }
8605 }
8606 }
8607
8608 return 0;
8609}
8610
Chris Lattner8a9f5712007-04-11 06:57:46 +00008611Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008612 // If one of the common conversion will work ..
8613 if (Instruction *Result = commonIntCastTransforms(CI))
8614 return Result;
8615
8616 Value *Src = CI.getOperand(0);
8617
Chris Lattnera84f47c2009-02-17 20:47:23 +00008618 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8619 // types and if the sizes are just right we can convert this into a logical
8620 // 'and' which will be much cheaper than the pair of casts.
8621 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8622 // Get the sizes of the types involved. We know that the intermediate type
8623 // will be smaller than A or C, but don't know the relation between A and C.
8624 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008625 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8626 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8627 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008628 // If we're actually extending zero bits, then if
8629 // SrcSize < DstSize: zext(a & mask)
8630 // SrcSize == DstSize: a & mask
8631 // SrcSize > DstSize: trunc(a) & mask
8632 if (SrcSize < DstSize) {
8633 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008634 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008635 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008636 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008637 }
8638
8639 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008640 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008641 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008642 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008643 }
8644 if (SrcSize > DstSize) {
8645 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008646 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008647 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008648 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008649 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008650 }
8651 }
8652
Evan Chengb98a10e2008-03-24 00:21:34 +00008653 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8654 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008655
Evan Chengb98a10e2008-03-24 00:21:34 +00008656 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8657 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8658 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8659 // of the (zext icmp) will be transformed.
8660 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8661 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8662 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8663 (transformZExtICmp(LHS, CI, false) ||
8664 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008665 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8666 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008667 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008668 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008669 }
8670
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008671 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008672 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8673 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8674 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8675 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008676 if (TI0->getType() == CI.getType())
8677 return
8678 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008679 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008680 }
8681
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008682 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8683 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8684 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8685 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8686 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8687 And->getOperand(1) == C)
8688 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8689 Value *TI0 = TI->getOperand(0);
8690 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008691 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008692 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008693 return BinaryOperator::CreateXor(NewAnd, ZC);
8694 }
8695 }
8696
Reid Spencer3da59db2006-11-27 01:05:10 +00008697 return 0;
8698}
8699
Chris Lattner8a9f5712007-04-11 06:57:46 +00008700Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008701 if (Instruction *I = commonIntCastTransforms(CI))
8702 return I;
8703
Chris Lattner8a9f5712007-04-11 06:57:46 +00008704 Value *Src = CI.getOperand(0);
8705
Dan Gohman1975d032008-10-30 20:40:10 +00008706 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008707 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008708 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008709 Constant::getAllOnesValue(CI.getType()),
8710 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008711
8712 // See if the value being truncated is already sign extended. If so, just
8713 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008714 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008715 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008716 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8717 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8718 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008719 unsigned NumSignBits = ComputeNumSignBits(Op);
8720
8721 if (OpBits == DestBits) {
8722 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8723 // bits, it is already ready.
8724 if (NumSignBits > DestBits-MidBits)
8725 return ReplaceInstUsesWith(CI, Op);
8726 } else if (OpBits < DestBits) {
8727 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8728 // bits, just sext from i32.
8729 if (NumSignBits > OpBits-MidBits)
8730 return new SExtInst(Op, CI.getType(), "tmp");
8731 } else {
8732 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8733 // bits, just truncate to i32.
8734 if (NumSignBits > OpBits-MidBits)
8735 return new TruncInst(Op, CI.getType(), "tmp");
8736 }
8737 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008738
8739 // If the input is a shl/ashr pair of a same constant, then this is a sign
8740 // extension from a smaller value. If we could trust arbitrary bitwidth
8741 // integers, we could turn this into a truncate to the smaller bit and then
8742 // use a sext for the whole extension. Since we don't, look deeper and check
8743 // for a truncate. If the source and dest are the same type, eliminate the
8744 // trunc and extend and just do shifts. For example, turn:
8745 // %a = trunc i32 %i to i8
8746 // %b = shl i8 %a, 6
8747 // %c = ashr i8 %b, 6
8748 // %d = sext i8 %c to i32
8749 // into:
8750 // %a = shl i32 %i, 30
8751 // %d = ashr i32 %a, 30
8752 Value *A = 0;
8753 ConstantInt *BA = 0, *CA = 0;
8754 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008755 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008756 BA == CA && isa<TruncInst>(A)) {
8757 Value *I = cast<TruncInst>(A)->getOperand(0);
8758 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008759 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8760 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008761 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008762 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008763 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008764 return BinaryOperator::CreateAShr(I, ShAmtV);
8765 }
8766 }
8767
Chris Lattnerba417832007-04-11 06:12:58 +00008768 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008769}
8770
Chris Lattnerb7530652008-01-27 05:29:54 +00008771/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8772/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008773static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008774 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008775 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008776 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008777 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8778 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008779 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008780 return 0;
8781}
8782
8783/// LookThroughFPExtensions - If this is an fp extension instruction, look
8784/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008785static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008786 if (Instruction *I = dyn_cast<Instruction>(V))
8787 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008788 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008789
8790 // If this value is a constant, return the constant in the smallest FP type
8791 // that can accurately represent it. This allows us to turn
8792 // (float)((double)X+2.0) into x+2.0f.
8793 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008794 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008795 return V; // No constant folding of this.
8796 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008797 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008798 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008799 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008800 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008801 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008802 return V;
8803 // Don't try to shrink to various long double types.
8804 }
8805
8806 return V;
8807}
8808
8809Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8810 if (Instruction *I = commonCastTransforms(CI))
8811 return I;
8812
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008813 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008814 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008815 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008816 // many builtins (sqrt, etc).
8817 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8818 if (OpI && OpI->hasOneUse()) {
8819 switch (OpI->getOpcode()) {
8820 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008821 case Instruction::FAdd:
8822 case Instruction::FSub:
8823 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008824 case Instruction::FDiv:
8825 case Instruction::FRem:
8826 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008827 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8828 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008829 if (LHSTrunc->getType() != SrcTy &&
8830 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008831 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008832 // If the source types were both smaller than the destination type of
8833 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008834 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8835 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008836 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8837 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008838 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008839 }
8840 }
8841 break;
8842 }
8843 }
8844 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008845}
8846
8847Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8848 return commonCastTransforms(CI);
8849}
8850
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008851Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008852 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8853 if (OpI == 0)
8854 return commonCastTransforms(FI);
8855
8856 // fptoui(uitofp(X)) --> X
8857 // fptoui(sitofp(X)) --> X
8858 // This is safe if the intermediate type has enough bits in its mantissa to
8859 // accurately represent all values of X. For example, do not do this with
8860 // i64->float->i64. This is also safe for sitofp case, because any negative
8861 // 'X' value would cause an undefined result for the fptoui.
8862 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8863 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008864 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008865 OpI->getType()->getFPMantissaWidth())
8866 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008867
8868 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008869}
8870
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008871Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008872 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8873 if (OpI == 0)
8874 return commonCastTransforms(FI);
8875
8876 // fptosi(sitofp(X)) --> X
8877 // fptosi(uitofp(X)) --> X
8878 // This is safe if the intermediate type has enough bits in its mantissa to
8879 // accurately represent all values of X. For example, do not do this with
8880 // i64->float->i64. This is also safe for sitofp case, because any negative
8881 // 'X' value would cause an undefined result for the fptoui.
8882 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8883 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008884 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008885 OpI->getType()->getFPMantissaWidth())
8886 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008887
8888 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008889}
8890
8891Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8892 return commonCastTransforms(CI);
8893}
8894
8895Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8896 return commonCastTransforms(CI);
8897}
8898
Chris Lattnera0e69692009-03-24 18:35:40 +00008899Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8900 // If the destination integer type is smaller than the intptr_t type for
8901 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8902 // trunc to be exposed to other transforms. Don't do this for extending
8903 // ptrtoint's, because we don't know if the target sign or zero extends its
8904 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008905 if (TD &&
8906 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008907 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8908 TD->getIntPtrType(CI.getContext()),
8909 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008910 return new TruncInst(P, CI.getType());
8911 }
8912
Chris Lattnerd3e28342007-04-27 17:44:50 +00008913 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008914}
8915
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008916Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008917 // If the source integer type is larger than the intptr_t type for
8918 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8919 // allows the trunc to be exposed to other transforms. Don't do this for
8920 // extending inttoptr's, because we don't know if the target sign or zero
8921 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008922 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008923 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008924 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8925 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008926 return new IntToPtrInst(P, CI.getType());
8927 }
8928
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008929 if (Instruction *I = commonCastTransforms(CI))
8930 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008931
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008932 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008933}
8934
Chris Lattnerd3e28342007-04-27 17:44:50 +00008935Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008936 // If the operands are integer typed then apply the integer transforms,
8937 // otherwise just apply the common ones.
8938 Value *Src = CI.getOperand(0);
8939 const Type *SrcTy = Src->getType();
8940 const Type *DestTy = CI.getType();
8941
Eli Friedman7e25d452009-07-13 20:53:00 +00008942 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008943 if (Instruction *I = commonPointerCastTransforms(CI))
8944 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008945 } else {
8946 if (Instruction *Result = commonCastTransforms(CI))
8947 return Result;
8948 }
8949
8950
8951 // Get rid of casts from one type to the same type. These are useless and can
8952 // be replaced by the operand.
8953 if (DestTy == Src->getType())
8954 return ReplaceInstUsesWith(CI, Src);
8955
Reid Spencer3da59db2006-11-27 01:05:10 +00008956 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008957 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8958 const Type *DstElTy = DstPTy->getElementType();
8959 const Type *SrcElTy = SrcPTy->getElementType();
8960
Nate Begeman83ad90a2008-03-31 00:22:16 +00008961 // If the address spaces don't match, don't eliminate the bitcast, which is
8962 // required for changing types.
8963 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8964 return 0;
8965
Victor Hernandez83d63912009-09-18 22:35:49 +00008966 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008967 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008968 // There is no need to modify malloc calls because it is their bitcast that
8969 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008970 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008971 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8972 return V;
8973
Chris Lattnerd717c182007-05-05 22:32:24 +00008974 // If the source and destination are pointers, and this cast is equivalent
8975 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008976 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008977 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008978 unsigned NumZeros = 0;
8979 while (SrcElTy != DstElTy &&
8980 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8981 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8982 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8983 ++NumZeros;
8984 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008985
Chris Lattnerd3e28342007-04-27 17:44:50 +00008986 // If we found a path from the src to dest, create the getelementptr now.
8987 if (SrcElTy == DstElTy) {
8988 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008989 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8990 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008991 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008992 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008993
Eli Friedman2451a642009-07-18 23:06:53 +00008994 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8995 if (DestVTy->getNumElements() == 1) {
8996 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008997 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008998 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008999 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009000 }
9001 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9002 }
9003 }
9004
9005 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9006 if (SrcVTy->getNumElements() == 1) {
9007 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009008 Value *Elem =
9009 Builder->CreateExtractElement(Src,
9010 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009011 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9012 }
9013 }
9014 }
9015
Reid Spencer3da59db2006-11-27 01:05:10 +00009016 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9017 if (SVI->hasOneUse()) {
9018 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9019 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009020 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009021 cast<VectorType>(DestTy)->getNumElements() ==
9022 SVI->getType()->getNumElements() &&
9023 SVI->getType()->getNumElements() ==
9024 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009025 CastInst *Tmp;
9026 // If either of the operands is a cast from CI.getType(), then
9027 // evaluating the shuffle in the casted destination's type will allow
9028 // us to eliminate at least one cast.
9029 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9030 Tmp->getOperand(0)->getType() == DestTy) ||
9031 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9032 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009033 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9034 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009035 // Return a new shuffle vector. Use the same element ID's, as we
9036 // know the vector types match #elts.
9037 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009038 }
9039 }
9040 }
9041 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009042 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009043}
9044
Chris Lattnere576b912004-04-09 23:46:01 +00009045/// GetSelectFoldableOperands - We want to turn code that looks like this:
9046/// %C = or %A, %B
9047/// %D = select %cond, %C, %A
9048/// into:
9049/// %C = select %cond, %B, 0
9050/// %D = or %A, %C
9051///
9052/// Assuming that the specified instruction is an operand to the select, return
9053/// a bitmask indicating which operands of this instruction are foldable if they
9054/// equal the other incoming value of the select.
9055///
9056static unsigned GetSelectFoldableOperands(Instruction *I) {
9057 switch (I->getOpcode()) {
9058 case Instruction::Add:
9059 case Instruction::Mul:
9060 case Instruction::And:
9061 case Instruction::Or:
9062 case Instruction::Xor:
9063 return 3; // Can fold through either operand.
9064 case Instruction::Sub: // Can only fold on the amount subtracted.
9065 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009066 case Instruction::LShr:
9067 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009068 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009069 default:
9070 return 0; // Cannot fold
9071 }
9072}
9073
9074/// GetSelectFoldableConstant - For the same transformation as the previous
9075/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009076static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009077 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009078 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009079 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009080 case Instruction::Add:
9081 case Instruction::Sub:
9082 case Instruction::Or:
9083 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009084 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009085 case Instruction::LShr:
9086 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009087 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009088 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009089 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009090 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009091 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009092 }
9093}
9094
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009095/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9096/// have the same opcode and only one use each. Try to simplify this.
9097Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9098 Instruction *FI) {
9099 if (TI->getNumOperands() == 1) {
9100 // If this is a non-volatile load or a cast from the same type,
9101 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009102 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009103 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9104 return 0;
9105 } else {
9106 return 0; // unknown unary op.
9107 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009108
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009109 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009110 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009111 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009112 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009113 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009114 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009115 }
9116
Reid Spencer832254e2007-02-02 02:16:23 +00009117 // Only handle binary operators here.
9118 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009119 return 0;
9120
9121 // Figure out if the operations have any operands in common.
9122 Value *MatchOp, *OtherOpT, *OtherOpF;
9123 bool MatchIsOpZero;
9124 if (TI->getOperand(0) == FI->getOperand(0)) {
9125 MatchOp = TI->getOperand(0);
9126 OtherOpT = TI->getOperand(1);
9127 OtherOpF = FI->getOperand(1);
9128 MatchIsOpZero = true;
9129 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9130 MatchOp = TI->getOperand(1);
9131 OtherOpT = TI->getOperand(0);
9132 OtherOpF = FI->getOperand(0);
9133 MatchIsOpZero = false;
9134 } else if (!TI->isCommutative()) {
9135 return 0;
9136 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9137 MatchOp = TI->getOperand(0);
9138 OtherOpT = TI->getOperand(1);
9139 OtherOpF = FI->getOperand(0);
9140 MatchIsOpZero = true;
9141 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9142 MatchOp = TI->getOperand(1);
9143 OtherOpT = TI->getOperand(0);
9144 OtherOpF = FI->getOperand(1);
9145 MatchIsOpZero = true;
9146 } else {
9147 return 0;
9148 }
9149
9150 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009151 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9152 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009153 InsertNewInstBefore(NewSI, SI);
9154
9155 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9156 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009157 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009158 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009159 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009160 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009161 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009162 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009163}
9164
Evan Chengde621922009-03-31 20:42:45 +00009165static bool isSelect01(Constant *C1, Constant *C2) {
9166 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9167 if (!C1I)
9168 return false;
9169 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9170 if (!C2I)
9171 return false;
9172 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9173}
9174
9175/// FoldSelectIntoOp - Try fold the select into one of the operands to
9176/// facilitate further optimization.
9177Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9178 Value *FalseVal) {
9179 // See the comment above GetSelectFoldableOperands for a description of the
9180 // transformation we are doing here.
9181 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9182 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9183 !isa<Constant>(FalseVal)) {
9184 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9185 unsigned OpToFold = 0;
9186 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9187 OpToFold = 1;
9188 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9189 OpToFold = 2;
9190 }
9191
9192 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009193 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009194 Value *OOp = TVI->getOperand(2-OpToFold);
9195 // Avoid creating select between 2 constants unless it's selecting
9196 // between 0 and 1.
9197 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9198 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9199 InsertNewInstBefore(NewSel, SI);
9200 NewSel->takeName(TVI);
9201 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9202 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009203 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009204 }
9205 }
9206 }
9207 }
9208 }
9209
9210 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9211 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9212 !isa<Constant>(TrueVal)) {
9213 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9214 unsigned OpToFold = 0;
9215 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9216 OpToFold = 1;
9217 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9218 OpToFold = 2;
9219 }
9220
9221 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009222 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009223 Value *OOp = FVI->getOperand(2-OpToFold);
9224 // Avoid creating select between 2 constants unless it's selecting
9225 // between 0 and 1.
9226 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9227 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9228 InsertNewInstBefore(NewSel, SI);
9229 NewSel->takeName(FVI);
9230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9231 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009232 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009233 }
9234 }
9235 }
9236 }
9237 }
9238
9239 return 0;
9240}
9241
Dan Gohman81b28ce2008-09-16 18:46:06 +00009242/// visitSelectInstWithICmp - Visit a SelectInst that has an
9243/// ICmpInst as its first operand.
9244///
9245Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9246 ICmpInst *ICI) {
9247 bool Changed = false;
9248 ICmpInst::Predicate Pred = ICI->getPredicate();
9249 Value *CmpLHS = ICI->getOperand(0);
9250 Value *CmpRHS = ICI->getOperand(1);
9251 Value *TrueVal = SI.getTrueValue();
9252 Value *FalseVal = SI.getFalseValue();
9253
9254 // Check cases where the comparison is with a constant that
9255 // can be adjusted to fit the min/max idiom. We may edit ICI in
9256 // place here, so make sure the select is the only user.
9257 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009258 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009259 switch (Pred) {
9260 default: break;
9261 case ICmpInst::ICMP_ULT:
9262 case ICmpInst::ICMP_SLT: {
9263 // X < MIN ? T : F --> F
9264 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9265 return ReplaceInstUsesWith(SI, FalseVal);
9266 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009267 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009268 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9269 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9270 Pred = ICmpInst::getSwappedPredicate(Pred);
9271 CmpRHS = AdjustedRHS;
9272 std::swap(FalseVal, TrueVal);
9273 ICI->setPredicate(Pred);
9274 ICI->setOperand(1, CmpRHS);
9275 SI.setOperand(1, TrueVal);
9276 SI.setOperand(2, FalseVal);
9277 Changed = true;
9278 }
9279 break;
9280 }
9281 case ICmpInst::ICMP_UGT:
9282 case ICmpInst::ICMP_SGT: {
9283 // X > MAX ? T : F --> F
9284 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9285 return ReplaceInstUsesWith(SI, FalseVal);
9286 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009287 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009288 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9289 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9290 Pred = ICmpInst::getSwappedPredicate(Pred);
9291 CmpRHS = AdjustedRHS;
9292 std::swap(FalseVal, TrueVal);
9293 ICI->setPredicate(Pred);
9294 ICI->setOperand(1, CmpRHS);
9295 SI.setOperand(1, TrueVal);
9296 SI.setOperand(2, FalseVal);
9297 Changed = true;
9298 }
9299 break;
9300 }
9301 }
9302
Dan Gohman1975d032008-10-30 20:40:10 +00009303 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9304 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009305 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009306 if (match(TrueVal, m_ConstantInt<-1>()) &&
9307 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009308 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009309 else if (match(TrueVal, m_ConstantInt<0>()) &&
9310 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009311 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9312
Dan Gohman1975d032008-10-30 20:40:10 +00009313 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9314 // If we are just checking for a icmp eq of a single bit and zext'ing it
9315 // to an integer, then shift the bit to the appropriate place and then
9316 // cast to integer to avoid the comparison.
9317 const APInt &Op1CV = CI->getValue();
9318
9319 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9320 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9321 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009322 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009323 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009324 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009325 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009326 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009327 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009328 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009329 if (In->getType() != SI.getType())
9330 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009331 true/*SExt*/, "tmp", ICI);
9332
9333 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009334 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009335 In->getName()+".not"), *ICI);
9336
9337 return ReplaceInstUsesWith(SI, In);
9338 }
9339 }
9340 }
9341
Dan Gohman81b28ce2008-09-16 18:46:06 +00009342 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9343 // Transform (X == Y) ? X : Y -> Y
9344 if (Pred == ICmpInst::ICMP_EQ)
9345 return ReplaceInstUsesWith(SI, FalseVal);
9346 // Transform (X != Y) ? X : Y -> X
9347 if (Pred == ICmpInst::ICMP_NE)
9348 return ReplaceInstUsesWith(SI, TrueVal);
9349 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9350
9351 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9352 // Transform (X == Y) ? Y : X -> X
9353 if (Pred == ICmpInst::ICMP_EQ)
9354 return ReplaceInstUsesWith(SI, FalseVal);
9355 // Transform (X != Y) ? Y : X -> Y
9356 if (Pred == ICmpInst::ICMP_NE)
9357 return ReplaceInstUsesWith(SI, TrueVal);
9358 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9359 }
9360
9361 /// NOTE: if we wanted to, this is where to detect integer ABS
9362
9363 return Changed ? &SI : 0;
9364}
9365
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009366
Chris Lattner7f239582009-10-22 00:17:26 +00009367/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9368/// PHI node (but the two may be in different blocks). See if the true/false
9369/// values (V) are live in all of the predecessor blocks of the PHI. For
9370/// example, cases like this cannot be mapped:
9371///
9372/// X = phi [ C1, BB1], [C2, BB2]
9373/// Y = add
9374/// Z = select X, Y, 0
9375///
9376/// because Y is not live in BB1/BB2.
9377///
9378static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9379 const SelectInst &SI) {
9380 // If the value is a non-instruction value like a constant or argument, it
9381 // can always be mapped.
9382 const Instruction *I = dyn_cast<Instruction>(V);
9383 if (I == 0) return true;
9384
9385 // If V is a PHI node defined in the same block as the condition PHI, we can
9386 // map the arguments.
9387 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9388
9389 if (const PHINode *VP = dyn_cast<PHINode>(I))
9390 if (VP->getParent() == CondPHI->getParent())
9391 return true;
9392
9393 // Otherwise, if the PHI and select are defined in the same block and if V is
9394 // defined in a different block, then we can transform it.
9395 if (SI.getParent() == CondPHI->getParent() &&
9396 I->getParent() != CondPHI->getParent())
9397 return true;
9398
9399 // Otherwise we have a 'hard' case and we can't tell without doing more
9400 // detailed dominator based analysis, punt.
9401 return false;
9402}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009403
Chris Lattner3d69f462004-03-12 05:52:32 +00009404Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009405 Value *CondVal = SI.getCondition();
9406 Value *TrueVal = SI.getTrueValue();
9407 Value *FalseVal = SI.getFalseValue();
9408
9409 // select true, X, Y -> X
9410 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009411 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009412 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009413
9414 // select C, X, X -> X
9415 if (TrueVal == FalseVal)
9416 return ReplaceInstUsesWith(SI, TrueVal);
9417
Chris Lattnere87597f2004-10-16 18:11:37 +00009418 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9419 return ReplaceInstUsesWith(SI, FalseVal);
9420 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9421 return ReplaceInstUsesWith(SI, TrueVal);
9422 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9423 if (isa<Constant>(TrueVal))
9424 return ReplaceInstUsesWith(SI, TrueVal);
9425 else
9426 return ReplaceInstUsesWith(SI, FalseVal);
9427 }
9428
Owen Anderson1d0be152009-08-13 21:58:54 +00009429 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009430 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009431 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009432 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009433 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009434 } else {
9435 // Change: A = select B, false, C --> A = and !B, C
9436 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009437 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009438 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009439 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009440 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009441 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009442 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009443 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009444 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009445 } else {
9446 // Change: A = select B, C, true --> A = or !B, C
9447 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009448 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009449 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009450 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009451 }
9452 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009453
9454 // select a, b, a -> a&b
9455 // select a, a, b -> a|b
9456 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009457 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009458 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009459 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009460 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009461
Chris Lattner2eefe512004-04-09 19:05:30 +00009462 // Selecting between two integer constants?
9463 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9464 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009465 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009466 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009467 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009468 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009469 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009470 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009471 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009472 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009473 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009474 }
Chris Lattner457dd822004-06-09 07:59:58 +00009475
Reid Spencere4d87aa2006-12-23 06:05:41 +00009476 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009477 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009478 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009479 // non-constant value, eliminate this whole mess. This corresponds to
9480 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009481 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009482 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009483 cast<Constant>(IC->getOperand(1))->isNullValue())
9484 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9485 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009486 isa<ConstantInt>(ICA->getOperand(1)) &&
9487 (ICA->getOperand(1) == TrueValC ||
9488 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009489 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9490 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009491 // know whether we have a icmp_ne or icmp_eq and whether the
9492 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009493 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009494 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009495 Value *V = ICA;
9496 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009497 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009498 Instruction::Xor, V, ICA->getOperand(1)), SI);
9499 return ReplaceInstUsesWith(SI, V);
9500 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009501 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009502 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009503
9504 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009505 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9506 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009507 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009508 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9509 // This is not safe in general for floating point:
9510 // consider X== -0, Y== +0.
9511 // It becomes safe if either operand is a nonzero constant.
9512 ConstantFP *CFPt, *CFPf;
9513 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9514 !CFPt->getValueAPF().isZero()) ||
9515 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9516 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009517 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009518 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009519 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009520 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009521 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009522 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009523
Reid Spencere4d87aa2006-12-23 06:05:41 +00009524 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009525 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009526 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9527 // This is not safe in general for floating point:
9528 // consider X== -0, Y== +0.
9529 // It becomes safe if either operand is a nonzero constant.
9530 ConstantFP *CFPt, *CFPf;
9531 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9532 !CFPt->getValueAPF().isZero()) ||
9533 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9534 !CFPf->getValueAPF().isZero()))
9535 return ReplaceInstUsesWith(SI, FalseVal);
9536 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009537 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009538 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9539 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009540 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009541 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009542 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009543 }
9544
9545 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009546 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9547 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9548 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009549
Chris Lattner87875da2005-01-13 22:52:24 +00009550 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9551 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9552 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009553 Instruction *AddOp = 0, *SubOp = 0;
9554
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009555 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9556 if (TI->getOpcode() == FI->getOpcode())
9557 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9558 return IV;
9559
9560 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9561 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009562 if ((TI->getOpcode() == Instruction::Sub &&
9563 FI->getOpcode() == Instruction::Add) ||
9564 (TI->getOpcode() == Instruction::FSub &&
9565 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009566 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009567 } else if ((FI->getOpcode() == Instruction::Sub &&
9568 TI->getOpcode() == Instruction::Add) ||
9569 (FI->getOpcode() == Instruction::FSub &&
9570 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009571 AddOp = TI; SubOp = FI;
9572 }
9573
9574 if (AddOp) {
9575 Value *OtherAddOp = 0;
9576 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9577 OtherAddOp = AddOp->getOperand(1);
9578 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9579 OtherAddOp = AddOp->getOperand(0);
9580 }
9581
9582 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009583 // So at this point we know we have (Y -> OtherAddOp):
9584 // select C, (add X, Y), (sub X, Z)
9585 Value *NegVal; // Compute -Z
9586 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009587 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009588 } else {
9589 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009590 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009591 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009592 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009593
9594 Value *NewTrueOp = OtherAddOp;
9595 Value *NewFalseOp = NegVal;
9596 if (AddOp != TI)
9597 std::swap(NewTrueOp, NewFalseOp);
9598 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009599 SelectInst::Create(CondVal, NewTrueOp,
9600 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009601
9602 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009603 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009604 }
9605 }
9606 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009607
Chris Lattnere576b912004-04-09 23:46:01 +00009608 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009609 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009610 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9611 if (FoldI)
9612 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009613 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009614
Chris Lattner7f239582009-10-22 00:17:26 +00009615 // See if we can fold the select into a phi node if the condition is a select.
9616 if (isa<PHINode>(SI.getCondition()))
9617 // The true/false values have to be live in the PHI predecessor's blocks.
9618 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9619 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9620 if (Instruction *NV = FoldOpIntoPhi(SI))
9621 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009622
Chris Lattnera1df33c2005-04-24 07:30:14 +00009623 if (BinaryOperator::isNot(CondVal)) {
9624 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9625 SI.setOperand(1, FalseVal);
9626 SI.setOperand(2, TrueVal);
9627 return &SI;
9628 }
9629
Chris Lattner3d69f462004-03-12 05:52:32 +00009630 return 0;
9631}
9632
Dan Gohmaneee962e2008-04-10 18:43:06 +00009633/// EnforceKnownAlignment - If the specified pointer points to an object that
9634/// we control, modify the object's alignment to PrefAlign. This isn't
9635/// often possible though. If alignment is important, a more reliable approach
9636/// is to simply align all global variables and allocation instructions to
9637/// their preferred alignment from the beginning.
9638///
9639static unsigned EnforceKnownAlignment(Value *V,
9640 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009641
Dan Gohmaneee962e2008-04-10 18:43:06 +00009642 User *U = dyn_cast<User>(V);
9643 if (!U) return Align;
9644
Dan Gohmanca178902009-07-17 20:47:02 +00009645 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009646 default: break;
9647 case Instruction::BitCast:
9648 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9649 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009650 // If all indexes are zero, it is just the alignment of the base pointer.
9651 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009652 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009653 if (!isa<Constant>(*i) ||
9654 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009655 AllZeroOperands = false;
9656 break;
9657 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009658
9659 if (AllZeroOperands) {
9660 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009661 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009662 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009663 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009664 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009665 }
9666
9667 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9668 // If there is a large requested alignment and we can, bump up the alignment
9669 // of the global.
9670 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009671 if (GV->getAlignment() >= PrefAlign)
9672 Align = GV->getAlignment();
9673 else {
9674 GV->setAlignment(PrefAlign);
9675 Align = PrefAlign;
9676 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009677 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009678 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9679 // If there is a requested alignment and if this is an alloca, round up.
9680 if (AI->getAlignment() >= PrefAlign)
9681 Align = AI->getAlignment();
9682 else {
9683 AI->setAlignment(PrefAlign);
9684 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009685 }
9686 }
9687
9688 return Align;
9689}
9690
9691/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9692/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9693/// and it is more than the alignment of the ultimate object, see if we can
9694/// increase the alignment of the ultimate object, making this check succeed.
9695unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9696 unsigned PrefAlign) {
9697 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9698 sizeof(PrefAlign) * CHAR_BIT;
9699 APInt Mask = APInt::getAllOnesValue(BitWidth);
9700 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9701 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9702 unsigned TrailZ = KnownZero.countTrailingOnes();
9703 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9704
9705 if (PrefAlign > Align)
9706 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9707
9708 // We don't need to make any adjustment.
9709 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009710}
9711
Chris Lattnerf497b022008-01-13 23:50:23 +00009712Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009713 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009714 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009715 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009716 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009717
9718 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009719 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009720 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009721 return MI;
9722 }
9723
9724 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9725 // load/store.
9726 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9727 if (MemOpLength == 0) return 0;
9728
Chris Lattner37ac6082008-01-14 00:28:35 +00009729 // Source and destination pointer types are always "i8*" for intrinsic. See
9730 // if the size is something we can handle with a single primitive load/store.
9731 // A single load+store correctly handles overlapping memory in the memmove
9732 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009733 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009734 if (Size == 0) return MI; // Delete this mem transfer.
9735
9736 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009737 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009738
Chris Lattner37ac6082008-01-14 00:28:35 +00009739 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009740 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009741 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009742
9743 // Memcpy forces the use of i8* for the source and destination. That means
9744 // that if you're using memcpy to move one double around, you'll get a cast
9745 // from double* to i8*. We'd much rather use a double load+store rather than
9746 // an i64 load+store, here because this improves the odds that the source or
9747 // dest address will be promotable. See if we can find a better type than the
9748 // integer datatype.
9749 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9750 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009751 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009752 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9753 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009754 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009755 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9756 if (STy->getNumElements() == 1)
9757 SrcETy = STy->getElementType(0);
9758 else
9759 break;
9760 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9761 if (ATy->getNumElements() == 1)
9762 SrcETy = ATy->getElementType();
9763 else
9764 break;
9765 } else
9766 break;
9767 }
9768
Dan Gohman8f8e2692008-05-23 01:52:21 +00009769 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009770 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009771 }
9772 }
9773
9774
Chris Lattnerf497b022008-01-13 23:50:23 +00009775 // If the memcpy/memmove provides better alignment info than we can
9776 // infer, use it.
9777 SrcAlign = std::max(SrcAlign, CopyAlign);
9778 DstAlign = std::max(DstAlign, CopyAlign);
9779
Chris Lattner08142f22009-08-30 19:47:22 +00009780 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9781 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009782 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9783 InsertNewInstBefore(L, *MI);
9784 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9785
9786 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009787 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009788 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009789}
Chris Lattner3d69f462004-03-12 05:52:32 +00009790
Chris Lattner69ea9d22008-04-30 06:39:11 +00009791Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9792 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009793 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009794 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009795 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009796 return MI;
9797 }
9798
9799 // Extract the length and alignment and fill if they are constant.
9800 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9801 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009802 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009803 return 0;
9804 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009805 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009806
9807 // If the length is zero, this is a no-op
9808 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9809
9810 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9811 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009812 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009813
9814 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009815 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009816
9817 // Alignment 0 is identity for alignment 1 for memset, but not store.
9818 if (Alignment == 0) Alignment = 1;
9819
9820 // Extract the fill value and store.
9821 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009822 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009823 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009824
9825 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009826 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009827 return MI;
9828 }
9829
9830 return 0;
9831}
9832
9833
Chris Lattner8b0ea312006-01-13 20:11:04 +00009834/// visitCallInst - CallInst simplification. This mostly only handles folding
9835/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9836/// the heavy lifting.
9837///
Chris Lattner9fe38862003-06-19 17:00:31 +00009838Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009839 if (isFreeCall(&CI))
9840 return visitFree(CI);
9841
Chris Lattneraab6ec42009-05-13 17:39:14 +00009842 // If the caller function is nounwind, mark the call as nounwind, even if the
9843 // callee isn't.
9844 if (CI.getParent()->getParent()->doesNotThrow() &&
9845 !CI.doesNotThrow()) {
9846 CI.setDoesNotThrow();
9847 return &CI;
9848 }
9849
Chris Lattner8b0ea312006-01-13 20:11:04 +00009850 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9851 if (!II) return visitCallSite(&CI);
9852
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009853 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9854 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009855 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009856 bool Changed = false;
9857
9858 // memmove/cpy/set of zero bytes is a noop.
9859 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9860 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9861
Chris Lattner35b9e482004-10-12 04:52:52 +00009862 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009863 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009864 // Replace the instruction with just byte operations. We would
9865 // transform other cases to loads/stores, but we don't know if
9866 // alignment is sufficient.
9867 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009868 }
9869
Chris Lattner35b9e482004-10-12 04:52:52 +00009870 // If we have a memmove and the source operation is a constant global,
9871 // then the source and dest pointers can't alias, so we can change this
9872 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009873 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009874 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9875 if (GVSrc->isConstant()) {
9876 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009877 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9878 const Type *Tys[1];
9879 Tys[0] = CI.getOperand(3)->getType();
9880 CI.setOperand(0,
9881 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009882 Changed = true;
9883 }
Chris Lattnera935db82008-05-28 05:30:41 +00009884
9885 // memmove(x,x,size) -> noop.
9886 if (MMI->getSource() == MMI->getDest())
9887 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009888 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009889
Chris Lattner95a959d2006-03-06 20:18:44 +00009890 // If we can determine a pointer alignment that is bigger than currently
9891 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009892 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009893 if (Instruction *I = SimplifyMemTransfer(MI))
9894 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009895 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9896 if (Instruction *I = SimplifyMemSet(MSI))
9897 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009898 }
9899
Chris Lattner8b0ea312006-01-13 20:11:04 +00009900 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009901 }
9902
9903 switch (II->getIntrinsicID()) {
9904 default: break;
9905 case Intrinsic::bswap:
9906 // bswap(bswap(x)) -> x
9907 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9908 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9909 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9910 break;
9911 case Intrinsic::ppc_altivec_lvx:
9912 case Intrinsic::ppc_altivec_lvxl:
9913 case Intrinsic::x86_sse_loadu_ps:
9914 case Intrinsic::x86_sse2_loadu_pd:
9915 case Intrinsic::x86_sse2_loadu_dq:
9916 // Turn PPC lvx -> load if the pointer is known aligned.
9917 // Turn X86 loadups -> load if the pointer is known aligned.
9918 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009919 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9920 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009921 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009922 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009923 break;
9924 case Intrinsic::ppc_altivec_stvx:
9925 case Intrinsic::ppc_altivec_stvxl:
9926 // Turn stvx -> store if the pointer is known aligned.
9927 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9928 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009929 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009930 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009931 return new StoreInst(II->getOperand(1), Ptr);
9932 }
9933 break;
9934 case Intrinsic::x86_sse_storeu_ps:
9935 case Intrinsic::x86_sse2_storeu_pd:
9936 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 // Turn X86 storeu -> store if the pointer is known aligned.
9938 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9939 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009940 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009941 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009942 return new StoreInst(II->getOperand(2), Ptr);
9943 }
9944 break;
9945
9946 case Intrinsic::x86_sse_cvttss2si: {
9947 // These intrinsics only demands the 0th element of its input vector. If
9948 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009949 unsigned VWidth =
9950 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9951 APInt DemandedElts(VWidth, 1);
9952 APInt UndefElts(VWidth, 0);
9953 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009954 UndefElts)) {
9955 II->setOperand(1, V);
9956 return II;
9957 }
9958 break;
9959 }
9960
9961 case Intrinsic::ppc_altivec_vperm:
9962 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9963 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9964 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009965
Chris Lattner0521e3c2008-06-18 04:33:20 +00009966 // Check that all of the elements are integer constants or undefs.
9967 bool AllEltsOk = true;
9968 for (unsigned i = 0; i != 16; ++i) {
9969 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9970 !isa<UndefValue>(Mask->getOperand(i))) {
9971 AllEltsOk = false;
9972 break;
9973 }
9974 }
9975
9976 if (AllEltsOk) {
9977 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009978 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9979 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009980 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009981
Chris Lattner0521e3c2008-06-18 04:33:20 +00009982 // Only extract each element once.
9983 Value *ExtractedElts[32];
9984 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9985
Chris Lattnere2ed0572006-04-06 19:19:17 +00009986 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009987 if (isa<UndefValue>(Mask->getOperand(i)))
9988 continue;
9989 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9990 Idx &= 31; // Match the hardware behavior.
9991
9992 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009993 ExtractedElts[Idx] =
9994 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9995 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9996 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009997 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009998
Chris Lattner0521e3c2008-06-18 04:33:20 +00009999 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010000 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10001 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10002 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010003 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010004 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010005 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010006 }
10007 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010008
Chris Lattner0521e3c2008-06-18 04:33:20 +000010009 case Intrinsic::stackrestore: {
10010 // If the save is right next to the restore, remove the restore. This can
10011 // happen when variable allocas are DCE'd.
10012 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10013 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10014 BasicBlock::iterator BI = SS;
10015 if (&*++BI == II)
10016 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010017 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010018 }
10019
10020 // Scan down this block to see if there is another stack restore in the
10021 // same block without an intervening call/alloca.
10022 BasicBlock::iterator BI = II;
10023 TerminatorInst *TI = II->getParent()->getTerminator();
10024 bool CannotRemove = false;
10025 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010026 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010027 CannotRemove = true;
10028 break;
10029 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010030 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10031 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10032 // If there is a stackrestore below this one, remove this one.
10033 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10034 return EraseInstFromFunction(CI);
10035 // Otherwise, ignore the intrinsic.
10036 } else {
10037 // If we found a non-intrinsic call, we can't remove the stack
10038 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010039 CannotRemove = true;
10040 break;
10041 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010042 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010043 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010044
10045 // If the stack restore is in a return/unwind block and if there are no
10046 // allocas or calls between the restore and the return, nuke the restore.
10047 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10048 return EraseInstFromFunction(CI);
10049 break;
10050 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010051 }
10052
Chris Lattner8b0ea312006-01-13 20:11:04 +000010053 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010054}
10055
10056// InvokeInst simplification
10057//
10058Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010059 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010060}
10061
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010062/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10063/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010064static bool isSafeToEliminateVarargsCast(const CallSite CS,
10065 const CastInst * const CI,
10066 const TargetData * const TD,
10067 const int ix) {
10068 if (!CI->isLosslessCast())
10069 return false;
10070
10071 // The size of ByVal arguments is derived from the type, so we
10072 // can't change to a type with a different size. If the size were
10073 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010074 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010075 return true;
10076
10077 const Type* SrcTy =
10078 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10079 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10080 if (!SrcTy->isSized() || !DstTy->isSized())
10081 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010082 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010083 return false;
10084 return true;
10085}
10086
Chris Lattnera44d8a22003-10-07 22:32:43 +000010087// visitCallSite - Improvements for call and invoke instructions.
10088//
10089Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010090 bool Changed = false;
10091
10092 // If the callee is a constexpr cast of a function, attempt to move the cast
10093 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010094 if (transformConstExprCastCall(CS)) return 0;
10095
Chris Lattner6c266db2003-10-07 22:54:13 +000010096 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010097
Chris Lattner08b22ec2005-05-13 07:09:09 +000010098 if (Function *CalleeF = dyn_cast<Function>(Callee))
10099 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10100 Instruction *OldCall = CS.getInstruction();
10101 // If the call and callee calling conventions don't match, this call must
10102 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010103 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010104 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010105 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010106 // If OldCall dues not return void then replaceAllUsesWith undef.
10107 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010108 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010109 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010110 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10111 return EraseInstFromFunction(*OldCall);
10112 return 0;
10113 }
10114
Chris Lattner17be6352004-10-18 02:59:09 +000010115 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10116 // This instruction is not reachable, just remove it. We insert a store to
10117 // undef so that we know that this code is not reachable, despite the fact
10118 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010119 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010120 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010121 CS.getInstruction());
10122
Devang Patel228ebd02009-10-13 22:56:32 +000010123 // If CS dues not return void then replaceAllUsesWith undef.
10124 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010125 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010126 CS.getInstruction()->
10127 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010128
10129 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10130 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010131 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010132 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010133 }
Chris Lattner17be6352004-10-18 02:59:09 +000010134 return EraseInstFromFunction(*CS.getInstruction());
10135 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010136
Duncan Sandscdb6d922007-09-17 10:26:40 +000010137 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10138 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10139 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10140 return transformCallThroughTrampoline(CS);
10141
Chris Lattner6c266db2003-10-07 22:54:13 +000010142 const PointerType *PTy = cast<PointerType>(Callee->getType());
10143 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10144 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010145 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010146 // See if we can optimize any arguments passed through the varargs area of
10147 // the call.
10148 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010149 E = CS.arg_end(); I != E; ++I, ++ix) {
10150 CastInst *CI = dyn_cast<CastInst>(*I);
10151 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10152 *I = CI->getOperand(0);
10153 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010154 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010155 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010156 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010157
Duncan Sandsf0c33542007-12-19 21:13:37 +000010158 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010159 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010160 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010161 Changed = true;
10162 }
10163
Chris Lattner6c266db2003-10-07 22:54:13 +000010164 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010165}
10166
Chris Lattner9fe38862003-06-19 17:00:31 +000010167// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10168// attempt to move the cast to the arguments of the call/invoke.
10169//
10170bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10171 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10172 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010173 if (CE->getOpcode() != Instruction::BitCast ||
10174 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010175 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010176 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010177 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010178 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010179
10180 // Okay, this is a cast from a function to a different type. Unless doing so
10181 // would cause a type conversion of one of our arguments, change this call to
10182 // be a direct call with arguments casted to the appropriate types.
10183 //
10184 const FunctionType *FT = Callee->getFunctionType();
10185 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010186 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010187
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010188 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010189 return false; // TODO: Handle multiple return values.
10190
Chris Lattnerf78616b2004-01-14 06:06:08 +000010191 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010192 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010193 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010194 // Conversion is ok if changing from one pointer type to another or from
10195 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010196 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010197 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010198 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010199 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010200 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010201
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010202 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010203 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010204 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010205 return false; // Cannot transform this return value.
10206
Chris Lattner58d74912008-03-12 17:45:29 +000010207 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010208 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010209 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010210 return false; // Attribute not compatible with transformed value.
10211 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010212
Chris Lattnerf78616b2004-01-14 06:06:08 +000010213 // If the callsite is an invoke instruction, and the return value is used by
10214 // a PHI node in a successor, we cannot change the return type of the call
10215 // because there is no place to put the cast instruction (without breaking
10216 // the critical edge). Bail out in this case.
10217 if (!Caller->use_empty())
10218 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10219 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10220 UI != E; ++UI)
10221 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10222 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010223 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010224 return false;
10225 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010226
10227 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10228 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010229
Chris Lattner9fe38862003-06-19 17:00:31 +000010230 CallSite::arg_iterator AI = CS.arg_begin();
10231 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10232 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010233 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010234
10235 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010236 return false; // Cannot transform this parameter value.
10237
Devang Patel19c87462008-09-26 22:53:05 +000010238 if (CallerPAL.getParamAttributes(i + 1)
10239 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010240 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010241
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010242 // Converting from one pointer type to another or between a pointer and an
10243 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010244 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010245 (TD && ((isa<PointerType>(ParamTy) ||
10246 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10247 (isa<PointerType>(ActTy) ||
10248 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010249 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010250 }
10251
10252 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010253 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010254 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010255
Chris Lattner58d74912008-03-12 17:45:29 +000010256 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10257 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010258 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010259 // won't be dropping them. Check that these extra arguments have attributes
10260 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010261 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10262 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010263 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010264 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010265 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010266 return false;
10267 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010268
Chris Lattner9fe38862003-06-19 17:00:31 +000010269 // Okay, we decided that this is a safe thing to do: go ahead and start
10270 // inserting cast instructions as necessary...
10271 std::vector<Value*> Args;
10272 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010273 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010274 attrVec.reserve(NumCommonArgs);
10275
10276 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010277 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010278
10279 // If the return value is not being used, the type may not be compatible
10280 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010281 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010282
10283 // Add the new return attributes.
10284 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010285 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010286
10287 AI = CS.arg_begin();
10288 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10289 const Type *ParamTy = FT->getParamType(i);
10290 if ((*AI)->getType() == ParamTy) {
10291 Args.push_back(*AI);
10292 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010293 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010294 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010295 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010296 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010297
10298 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010299 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010300 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010301 }
10302
10303 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010304 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010305 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010306 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010307
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010308 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010309 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010310 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010311 errs() << "WARNING: While resolving call to function '"
10312 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010313 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010314 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010315 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10316 const Type *PTy = getPromotedType((*AI)->getType());
10317 if (PTy != (*AI)->getType()) {
10318 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010319 Instruction::CastOps opcode =
10320 CastInst::getCastOpcode(*AI, false, PTy, false);
10321 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010322 } else {
10323 Args.push_back(*AI);
10324 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010325
Duncan Sandse1e520f2008-01-13 08:02:44 +000010326 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010327 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010328 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010329 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010330 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010331 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010332
Devang Patel19c87462008-09-26 22:53:05 +000010333 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10334 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10335
Devang Patel9674d152009-10-14 17:29:00 +000010336 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010337 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010338
Eric Christophera66297a2009-07-25 02:45:27 +000010339 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10340 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010341
Chris Lattner9fe38862003-06-19 17:00:31 +000010342 Instruction *NC;
10343 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010344 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010345 Args.begin(), Args.end(),
10346 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010347 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010348 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010349 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010350 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10351 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010352 CallInst *CI = cast<CallInst>(Caller);
10353 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010354 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010355 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010356 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010357 }
10358
Chris Lattner6934a042007-02-11 01:23:03 +000010359 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010360 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010361 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010362 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010363 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010364 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010365 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010366
10367 // If this is an invoke instruction, we should insert it after the first
10368 // non-phi, instruction in the normal successor block.
10369 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010370 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010371 InsertNewInstBefore(NC, *I);
10372 } else {
10373 // Otherwise, it's a call, just insert cast right after the call instr
10374 InsertNewInstBefore(NC, *Caller);
10375 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010376 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010377 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010378 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010379 }
10380 }
10381
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010382
Chris Lattner931f8f32009-08-31 05:17:58 +000010383 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010384 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010385
10386 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010387 return true;
10388}
10389
Duncan Sandscdb6d922007-09-17 10:26:40 +000010390// transformCallThroughTrampoline - Turn a call to a function created by the
10391// init_trampoline intrinsic into a direct call to the underlying function.
10392//
10393Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10394 Value *Callee = CS.getCalledValue();
10395 const PointerType *PTy = cast<PointerType>(Callee->getType());
10396 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010397 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010398
10399 // If the call already has the 'nest' attribute somewhere then give up -
10400 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010401 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010402 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010403
10404 IntrinsicInst *Tramp =
10405 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10406
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010407 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010408 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10409 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10410
Devang Patel05988662008-09-25 21:00:45 +000010411 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010412 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 unsigned NestIdx = 1;
10414 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010415 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010416
10417 // Look for a parameter marked with the 'nest' attribute.
10418 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10419 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010420 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010421 // Record the parameter type and any other attributes.
10422 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010423 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424 break;
10425 }
10426
10427 if (NestTy) {
10428 Instruction *Caller = CS.getInstruction();
10429 std::vector<Value*> NewArgs;
10430 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10431
Devang Patel05988662008-09-25 21:00:45 +000010432 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010433 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010434
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010436 // mean appending it. Likewise for attributes.
10437
Devang Patel19c87462008-09-26 22:53:05 +000010438 // Add any result attributes.
10439 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010440 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010441
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 {
10443 unsigned Idx = 1;
10444 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10445 do {
10446 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010447 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010448 Value *NestVal = Tramp->getOperand(3);
10449 if (NestVal->getType() != NestTy)
10450 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10451 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010452 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010453 }
10454
10455 if (I == E)
10456 break;
10457
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010458 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010460 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010461 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010462 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010463
10464 ++Idx, ++I;
10465 } while (1);
10466 }
10467
Devang Patel19c87462008-09-26 22:53:05 +000010468 // Add any function attributes.
10469 if (Attributes Attr = Attrs.getFnAttributes())
10470 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10471
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472 // The trampoline may have been bitcast to a bogus type (FTy).
10473 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010474 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010475
Duncan Sandscdb6d922007-09-17 10:26:40 +000010476 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 NewTypes.reserve(FTy->getNumParams()+1);
10478
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010480 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481 {
10482 unsigned Idx = 1;
10483 FunctionType::param_iterator I = FTy->param_begin(),
10484 E = FTy->param_end();
10485
10486 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010487 if (Idx == NestIdx)
10488 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010489 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010490
10491 if (I == E)
10492 break;
10493
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010494 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010495 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010496
10497 ++Idx, ++I;
10498 } while (1);
10499 }
10500
10501 // Replace the trampoline call with a direct call. Let the generic
10502 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010503 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010504 FTy->isVarArg());
10505 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010506 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010507 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010508 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010509 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10510 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010511
10512 Instruction *NewCaller;
10513 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010514 NewCaller = InvokeInst::Create(NewCallee,
10515 II->getNormalDest(), II->getUnwindDest(),
10516 NewArgs.begin(), NewArgs.end(),
10517 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010518 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010519 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010520 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010521 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10522 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010523 if (cast<CallInst>(Caller)->isTailCall())
10524 cast<CallInst>(NewCaller)->setTailCall();
10525 cast<CallInst>(NewCaller)->
10526 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010527 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010528 }
Devang Patel9674d152009-10-14 17:29:00 +000010529 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010530 Caller->replaceAllUsesWith(NewCaller);
10531 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010532 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010533 return 0;
10534 }
10535 }
10536
10537 // Replace the trampoline call with a direct call. Since there is no 'nest'
10538 // parameter, there is no need to adjust the argument list. Let the generic
10539 // code sort out any function type mismatches.
10540 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010541 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010542 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010543 CS.setCalledFunction(NewCallee);
10544 return CS.getInstruction();
10545}
10546
Dan Gohman9ad29202009-09-16 16:50:24 +000010547/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10548/// 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 +000010549/// and a single binop.
10550Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10551 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010552 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010553 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010554 Value *LHSVal = FirstInst->getOperand(0);
10555 Value *RHSVal = FirstInst->getOperand(1);
10556
10557 const Type *LHSType = LHSVal->getType();
10558 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010559
Dan Gohman9ad29202009-09-16 16:50:24 +000010560 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010561 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010562 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010563 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010564 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010565 // types or GEP's with different index types.
10566 I->getOperand(0)->getType() != LHSType ||
10567 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010568 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010569
10570 // If they are CmpInst instructions, check their predicates
10571 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10572 if (cast<CmpInst>(I)->getPredicate() !=
10573 cast<CmpInst>(FirstInst)->getPredicate())
10574 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010575
10576 // Keep track of which operand needs a phi node.
10577 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10578 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010579 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010580
10581 // If both LHS and RHS would need a PHI, don't do this transformation,
10582 // because it would increase the number of PHIs entering the block,
10583 // which leads to higher register pressure. This is especially
10584 // bad when the PHIs are in the header of a loop.
10585 if (!LHSVal && !RHSVal)
10586 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010587
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010588 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010589
Chris Lattner7da52b22006-11-01 04:51:18 +000010590 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010591 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010592 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010593 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010594 NewLHS = PHINode::Create(LHSType,
10595 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010596 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10597 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010598 InsertNewInstBefore(NewLHS, PN);
10599 LHSVal = NewLHS;
10600 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010601
10602 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010603 NewRHS = PHINode::Create(RHSType,
10604 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010605 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10606 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010607 InsertNewInstBefore(NewRHS, PN);
10608 RHSVal = NewRHS;
10609 }
10610
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010611 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010612 if (NewLHS || NewRHS) {
10613 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10614 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10615 if (NewLHS) {
10616 Value *NewInLHS = InInst->getOperand(0);
10617 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10618 }
10619 if (NewRHS) {
10620 Value *NewInRHS = InInst->getOperand(1);
10621 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10622 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010623 }
10624 }
10625
Chris Lattner7da52b22006-11-01 04:51:18 +000010626 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010627 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010628 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010629 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010630 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010631}
10632
Chris Lattner05f18922008-12-01 02:34:36 +000010633Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10634 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10635
10636 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10637 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010638 // This is true if all GEP bases are allocas and if all indices into them are
10639 // constants.
10640 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010641
10642 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010643 // more than one phi, which leads to higher register pressure. This is
10644 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010645 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010646
Dan Gohman9ad29202009-09-16 16:50:24 +000010647 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010648 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10649 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10650 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10651 GEP->getNumOperands() != FirstInst->getNumOperands())
10652 return 0;
10653
Chris Lattner36d3e322009-02-21 00:46:50 +000010654 // Keep track of whether or not all GEPs are of alloca pointers.
10655 if (AllBasePointersAreAllocas &&
10656 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10657 !GEP->hasAllConstantIndices()))
10658 AllBasePointersAreAllocas = false;
10659
Chris Lattner05f18922008-12-01 02:34:36 +000010660 // Compare the operand lists.
10661 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10662 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10663 continue;
10664
10665 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10666 // if one of the PHIs has a constant for the index. The index may be
10667 // substantially cheaper to compute for the constants, so making it a
10668 // variable index could pessimize the path. This also handles the case
10669 // for struct indices, which must always be constant.
10670 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10671 isa<ConstantInt>(GEP->getOperand(op)))
10672 return 0;
10673
10674 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10675 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010676
10677 // If we already needed a PHI for an earlier operand, and another operand
10678 // also requires a PHI, we'd be introducing more PHIs than we're
10679 // eliminating, which increases register pressure on entry to the PHI's
10680 // block.
10681 if (NeededPhi)
10682 return 0;
10683
Chris Lattner05f18922008-12-01 02:34:36 +000010684 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010685 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010686 }
10687 }
10688
Chris Lattner36d3e322009-02-21 00:46:50 +000010689 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010690 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010691 // offset calculation, but all the predecessors will have to materialize the
10692 // stack address into a register anyway. We'd actually rather *clone* the
10693 // load up into the predecessors so that we have a load of a gep of an alloca,
10694 // which can usually all be folded into the load.
10695 if (AllBasePointersAreAllocas)
10696 return 0;
10697
Chris Lattner05f18922008-12-01 02:34:36 +000010698 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10699 // that is variable.
10700 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10701
10702 bool HasAnyPHIs = false;
10703 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10704 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10705 Value *FirstOp = FirstInst->getOperand(i);
10706 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10707 FirstOp->getName()+".pn");
10708 InsertNewInstBefore(NewPN, PN);
10709
10710 NewPN->reserveOperandSpace(e);
10711 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10712 OperandPhis[i] = NewPN;
10713 FixedOperands[i] = NewPN;
10714 HasAnyPHIs = true;
10715 }
10716
10717
10718 // Add all operands to the new PHIs.
10719 if (HasAnyPHIs) {
10720 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10721 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10722 BasicBlock *InBB = PN.getIncomingBlock(i);
10723
10724 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10725 if (PHINode *OpPhi = OperandPhis[op])
10726 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10727 }
10728 }
10729
10730 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010731 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10732 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10733 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010734 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10735 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010736}
10737
10738
Chris Lattner21550882009-02-23 05:56:17 +000010739/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10740/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010741/// obvious the value of the load is not changed from the point of the load to
10742/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010743///
10744/// Finally, it is safe, but not profitable, to sink a load targetting a
10745/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10746/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010747static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010748 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10749
10750 for (++BBI; BBI != E; ++BBI)
10751 if (BBI->mayWriteToMemory())
10752 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010753
10754 // Check for non-address taken alloca. If not address-taken already, it isn't
10755 // profitable to do this xform.
10756 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10757 bool isAddressTaken = false;
10758 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10759 UI != E; ++UI) {
10760 if (isa<LoadInst>(UI)) continue;
10761 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10762 // If storing TO the alloca, then the address isn't taken.
10763 if (SI->getOperand(1) == AI) continue;
10764 }
10765 isAddressTaken = true;
10766 break;
10767 }
10768
Chris Lattner36d3e322009-02-21 00:46:50 +000010769 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010770 return false;
10771 }
10772
Chris Lattner36d3e322009-02-21 00:46:50 +000010773 // If this load is a load from a GEP with a constant offset from an alloca,
10774 // then we don't want to sink it. In its present form, it will be
10775 // load [constant stack offset]. Sinking it will cause us to have to
10776 // materialize the stack addresses in each predecessor in a register only to
10777 // do a shared load from register in the successor.
10778 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10779 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10780 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10781 return false;
10782
Chris Lattner76c73142006-11-01 07:13:54 +000010783 return true;
10784}
10785
Chris Lattner751a3622009-11-01 20:04:24 +000010786Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10787 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10788
10789 // When processing loads, we need to propagate two bits of information to the
10790 // sunk load: whether it is volatile, and what its alignment is. We currently
10791 // don't sink loads when some have their alignment specified and some don't.
10792 // visitLoadInst will propagate an alignment onto the load when TD is around,
10793 // and if TD isn't around, we can't handle the mixed case.
10794 bool isVolatile = FirstLI->isVolatile();
10795 unsigned LoadAlignment = FirstLI->getAlignment();
10796
10797 // We can't sink the load if the loaded value could be modified between the
10798 // load and the PHI.
10799 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10800 !isSafeAndProfitableToSinkLoad(FirstLI))
10801 return 0;
10802
10803 // If the PHI is of volatile loads and the load block has multiple
10804 // successors, sinking it would remove a load of the volatile value from
10805 // the path through the other successor.
10806 if (isVolatile &&
10807 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10808 return 0;
10809
10810 // Check to see if all arguments are the same operation.
10811 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10812 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10813 if (!LI || !LI->hasOneUse())
10814 return 0;
10815
10816 // We can't sink the load if the loaded value could be modified between
10817 // the load and the PHI.
10818 if (LI->isVolatile() != isVolatile ||
10819 LI->getParent() != PN.getIncomingBlock(i) ||
10820 !isSafeAndProfitableToSinkLoad(LI))
10821 return 0;
10822
10823 // If some of the loads have an alignment specified but not all of them,
10824 // we can't do the transformation.
10825 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10826 return 0;
10827
Chris Lattnera664bb72009-11-01 20:07:07 +000010828 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010829
10830 // If the PHI is of volatile loads and the load block has multiple
10831 // successors, sinking it would remove a load of the volatile value from
10832 // the path through the other successor.
10833 if (isVolatile &&
10834 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10835 return 0;
10836 }
10837
10838 // Okay, they are all the same operation. Create a new PHI node of the
10839 // correct type, and PHI together all of the LHS's of the instructions.
10840 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10841 PN.getName()+".in");
10842 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10843
10844 Value *InVal = FirstLI->getOperand(0);
10845 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10846
10847 // Add all operands to the new PHI.
10848 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10849 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10850 if (NewInVal != InVal)
10851 InVal = 0;
10852 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10853 }
10854
10855 Value *PhiVal;
10856 if (InVal) {
10857 // The new PHI unions all of the same values together. This is really
10858 // common, so we handle it intelligently here for compile-time speed.
10859 PhiVal = InVal;
10860 delete NewPN;
10861 } else {
10862 InsertNewInstBefore(NewPN, PN);
10863 PhiVal = NewPN;
10864 }
10865
10866 // If this was a volatile load that we are merging, make sure to loop through
10867 // and mark all the input loads as non-volatile. If we don't do this, we will
10868 // insert a new volatile load and the old ones will not be deletable.
10869 if (isVolatile)
10870 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10871 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10872
10873 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10874}
10875
Chris Lattner9fe38862003-06-19 17:00:31 +000010876
Chris Lattnerbac32862004-11-14 19:13:23 +000010877// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10878// operator and they all are only used by the PHI, PHI together their
10879// inputs, and do the operation once, to the result of the PHI.
10880Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10881 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10882
Chris Lattner751a3622009-11-01 20:04:24 +000010883 if (isa<GetElementPtrInst>(FirstInst))
10884 return FoldPHIArgGEPIntoPHI(PN);
10885 if (isa<LoadInst>(FirstInst))
10886 return FoldPHIArgLoadIntoPHI(PN);
10887
Chris Lattnerbac32862004-11-14 19:13:23 +000010888 // Scan the instruction, looking for input operations that can be folded away.
10889 // If all input operands to the phi are the same instruction (e.g. a cast from
10890 // the same type or "+42") we can pull the operation through the PHI, reducing
10891 // code size and simplifying code.
10892 Constant *ConstantOp = 0;
10893 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000010894
Chris Lattnerbac32862004-11-14 19:13:23 +000010895 if (isa<CastInst>(FirstInst)) {
10896 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000010897
10898 // Be careful about transforming integer PHIs. We don't want to pessimize
10899 // the code by turning an i32 into an i1293.
10900 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
10901 // If we don't have TD, we don't know if the original PHI was legal.
10902 if (!TD) return 0;
10903
10904 unsigned PHIWidth = PN.getType()->getPrimitiveSizeInBits();
10905 unsigned NewWidth = CastSrcTy->getPrimitiveSizeInBits();
10906 bool PHILegal = TD->isLegalInteger(PHIWidth);
10907 bool NewLegal = TD->isLegalInteger(NewWidth);
Chris Lattner9956c052009-11-08 19:23:30 +000010908
Chris Lattnerbf382b52009-11-08 21:20:06 +000010909 // If this is a legal integer PHI node, and pulling the operation through
10910 // would cause it to be an illegal integer PHI, don't do the
10911 // transformation.
10912 if (PHILegal && !NewLegal)
10913 return 0;
10914
10915 // Otherwise, if both are illegal, do not increase the size of the PHI. We
10916 // do allow things like i160 -> i64, but not i64 -> i160.
10917 if (!PHILegal && !NewLegal && NewWidth > PHIWidth)
10918 return 0;
10919 }
Reid Spencer832254e2007-02-02 02:16:23 +000010920 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010921 // Can fold binop, compare or shift here if the RHS is a constant,
10922 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010923 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010924 if (ConstantOp == 0)
10925 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010926 } else {
10927 return 0; // Cannot fold this operation.
10928 }
10929
10930 // Check to see if all arguments are the same operation.
10931 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000010932 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10933 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010934 return 0;
10935 if (CastSrcTy) {
10936 if (I->getOperand(0)->getType() != CastSrcTy)
10937 return 0; // Cast operation must match.
10938 } else if (I->getOperand(1) != ConstantOp) {
10939 return 0;
10940 }
10941 }
10942
10943 // Okay, they are all the same operation. Create a new PHI node of the
10944 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010945 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10946 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010947 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010948
10949 Value *InVal = FirstInst->getOperand(0);
10950 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010951
10952 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010953 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10954 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10955 if (NewInVal != InVal)
10956 InVal = 0;
10957 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10958 }
10959
10960 Value *PhiVal;
10961 if (InVal) {
10962 // The new PHI unions all of the same values together. This is really
10963 // common, so we handle it intelligently here for compile-time speed.
10964 PhiVal = InVal;
10965 delete NewPN;
10966 } else {
10967 InsertNewInstBefore(NewPN, PN);
10968 PhiVal = NewPN;
10969 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010970
Chris Lattnerbac32862004-11-14 19:13:23 +000010971 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000010972 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010973 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000010974
Chris Lattner54545ac2008-04-29 17:13:43 +000010975 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010976 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000010977
Chris Lattner751a3622009-11-01 20:04:24 +000010978 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10979 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10980 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000010981}
Chris Lattnera1be5662002-05-02 17:06:02 +000010982
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010983/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10984/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010985static bool DeadPHICycle(PHINode *PN,
10986 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010987 if (PN->use_empty()) return true;
10988 if (!PN->hasOneUse()) return false;
10989
10990 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010991 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010992 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010993
10994 // Don't scan crazily complex things.
10995 if (PotentiallyDeadPHIs.size() == 16)
10996 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010997
10998 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10999 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011000
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011001 return false;
11002}
11003
Chris Lattnercf5008a2007-11-06 21:52:06 +000011004/// PHIsEqualValue - Return true if this phi node is always equal to
11005/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11006/// z = some value; x = phi (y, z); y = phi (x, z)
11007static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11008 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11009 // See if we already saw this PHI node.
11010 if (!ValueEqualPHIs.insert(PN))
11011 return true;
11012
11013 // Don't scan crazily complex things.
11014 if (ValueEqualPHIs.size() == 16)
11015 return false;
11016
11017 // Scan the operands to see if they are either phi nodes or are equal to
11018 // the value.
11019 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11020 Value *Op = PN->getIncomingValue(i);
11021 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11022 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11023 return false;
11024 } else if (Op != NonPhiInVal)
11025 return false;
11026 }
11027
11028 return true;
11029}
11030
11031
Chris Lattner9956c052009-11-08 19:23:30 +000011032namespace {
11033struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011034 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011035 unsigned Shift; // The amount shifted.
11036 Instruction *Inst; // The trunc instruction.
11037
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011038 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11039 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011040
11041 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011042 if (PHIId < RHS.PHIId) return true;
11043 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011044 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011045 if (Shift > RHS.Shift) return false;
11046 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011047 RHS.Inst->getType()->getPrimitiveSizeInBits();
11048 }
11049};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011050
11051struct LoweredPHIRecord {
11052 PHINode *PN; // The PHI that was lowered.
11053 unsigned Shift; // The amount shifted.
11054 unsigned Width; // The width extracted.
11055
11056 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11057 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11058
11059 // Ctor form used by DenseMap.
11060 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11061 : PN(pn), Shift(Sh), Width(0) {}
11062};
11063}
11064
11065namespace llvm {
11066 template<>
11067 struct DenseMapInfo<LoweredPHIRecord> {
11068 static inline LoweredPHIRecord getEmptyKey() {
11069 return LoweredPHIRecord(0, 0);
11070 }
11071 static inline LoweredPHIRecord getTombstoneKey() {
11072 return LoweredPHIRecord(0, 1);
11073 }
11074 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11075 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11076 (Val.Width>>3);
11077 }
11078 static bool isEqual(const LoweredPHIRecord &LHS,
11079 const LoweredPHIRecord &RHS) {
11080 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11081 LHS.Width == RHS.Width;
11082 }
11083 static bool isPod() { return true; }
11084 };
Chris Lattner9956c052009-11-08 19:23:30 +000011085}
11086
11087
11088/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11089/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11090/// so, we split the PHI into the various pieces being extracted. This sort of
11091/// thing is introduced when SROA promotes an aggregate to large integer values.
11092///
11093/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11094/// inttoptr. We should produce new PHIs in the right type.
11095///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011096Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11097 // PHIUsers - Keep track of all of the truncated values extracted from a set
11098 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011099 SmallVector<PHIUsageRecord, 16> PHIUsers;
11100
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011101 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11102 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11103 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11104 // check the uses of (to ensure they are all extracts).
11105 SmallVector<PHINode*, 8> PHIsToSlice;
11106 SmallPtrSet<PHINode*, 8> PHIsInspected;
11107
11108 PHIsToSlice.push_back(&FirstPhi);
11109 PHIsInspected.insert(&FirstPhi);
11110
11111 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11112 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011113
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011114 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11115 UI != E; ++UI) {
11116 Instruction *User = cast<Instruction>(*UI);
11117
11118 // If the user is a PHI, inspect its uses recursively.
11119 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11120 if (PHIsInspected.insert(UserPN))
11121 PHIsToSlice.push_back(UserPN);
11122 continue;
11123 }
11124
11125 // Truncates are always ok.
11126 if (isa<TruncInst>(User)) {
11127 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11128 continue;
11129 }
11130
11131 // Otherwise it must be a lshr which can only be used by one trunc.
11132 if (User->getOpcode() != Instruction::LShr ||
11133 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11134 !isa<ConstantInt>(User->getOperand(1)))
11135 return 0;
11136
11137 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11138 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011139 }
Chris Lattner9956c052009-11-08 19:23:30 +000011140 }
11141
11142 // If we have no users, they must be all self uses, just nuke the PHI.
11143 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011144 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011145
11146 // If this phi node is transformable, create new PHIs for all the pieces
11147 // extracted out of it. First, sort the users by their offset and size.
11148 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11149
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011150 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11151 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11152 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11153 );
Chris Lattner9956c052009-11-08 19:23:30 +000011154
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011155 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11156 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011157 DenseMap<BasicBlock*, Value*> PredValues;
11158
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011159 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11160 // introduce redundant PHIs.
11161 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11162
11163 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11164 unsigned PHIId = PHIUsers[UserI].PHIId;
11165 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011166 unsigned Offset = PHIUsers[UserI].Shift;
11167 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011168
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011169 PHINode *EltPHI;
11170
11171 // If we've already lowered a user like this, reuse the previously lowered
11172 // value.
11173 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011174
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011175 // Otherwise, Create the new PHI node for this user.
11176 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11177 assert(EltPHI->getType() != PN->getType() &&
11178 "Truncate didn't shrink phi?");
11179
11180 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11181 BasicBlock *Pred = PN->getIncomingBlock(i);
11182 Value *&PredVal = PredValues[Pred];
11183
11184 // If we already have a value for this predecessor, reuse it.
11185 if (PredVal) {
11186 EltPHI->addIncoming(PredVal, Pred);
11187 continue;
11188 }
Chris Lattner9956c052009-11-08 19:23:30 +000011189
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011190 // Handle the PHI self-reuse case.
11191 Value *InVal = PN->getIncomingValue(i);
11192 if (InVal == PN) {
11193 PredVal = EltPHI;
11194 EltPHI->addIncoming(PredVal, Pred);
11195 continue;
11196 } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11197 // If the incoming value was a PHI, and if it was one of the PHIs we
11198 // already rewrote it, just use the lowered value.
11199 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11200 PredVal = Res;
11201 EltPHI->addIncoming(PredVal, Pred);
11202 continue;
11203 }
11204 }
11205
11206 // Otherwise, do an extract in the predecessor.
11207 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11208 Value *Res = InVal;
11209 if (Offset)
11210 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11211 Offset), "extract");
11212 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11213 PredVal = Res;
11214 EltPHI->addIncoming(Res, Pred);
11215
11216 // If the incoming value was a PHI, and if it was one of the PHIs we are
11217 // rewriting, we will ultimately delete the code we inserted. This
11218 // means we need to revisit that PHI to make sure we extract out the
11219 // needed piece.
11220 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11221 if (PHIsInspected.count(OldInVal)) {
11222 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11223 OldInVal)-PHIsToSlice.begin();
11224 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11225 cast<Instruction>(Res)));
11226 ++UserE;
11227 }
Chris Lattner9956c052009-11-08 19:23:30 +000011228 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011229 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011230
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011231 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11232 << *EltPHI << '\n');
11233 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011234 }
Chris Lattner9956c052009-11-08 19:23:30 +000011235
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011236 // Replace the use of this piece with the PHI node.
11237 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011238 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011239
11240 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11241 // with undefs.
11242 Value *Undef = UndefValue::get(FirstPhi.getType());
11243 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11244 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11245 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011246}
11247
Chris Lattner473945d2002-05-06 18:06:38 +000011248// PHINode simplification
11249//
Chris Lattner7e708292002-06-25 16:13:24 +000011250Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011251 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011252 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011253
Owen Anderson7e057142006-07-10 22:03:18 +000011254 if (Value *V = PN.hasConstantValue())
11255 return ReplaceInstUsesWith(PN, V);
11256
Owen Anderson7e057142006-07-10 22:03:18 +000011257 // If all PHI operands are the same operation, pull them through the PHI,
11258 // reducing code size.
11259 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011260 isa<Instruction>(PN.getIncomingValue(1)) &&
11261 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11262 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11263 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11264 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011265 PN.getIncomingValue(0)->hasOneUse())
11266 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11267 return Result;
11268
11269 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11270 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11271 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011272 if (PN.hasOneUse()) {
11273 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11274 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011275 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011276 PotentiallyDeadPHIs.insert(&PN);
11277 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011278 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011279 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011280
11281 // If this phi has a single use, and if that use just computes a value for
11282 // the next iteration of a loop, delete the phi. This occurs with unused
11283 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11284 // common case here is good because the only other things that catch this
11285 // are induction variable analysis (sometimes) and ADCE, which is only run
11286 // late.
11287 if (PHIUser->hasOneUse() &&
11288 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11289 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011290 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011291 }
11292 }
Owen Anderson7e057142006-07-10 22:03:18 +000011293
Chris Lattnercf5008a2007-11-06 21:52:06 +000011294 // We sometimes end up with phi cycles that non-obviously end up being the
11295 // same value, for example:
11296 // z = some value; x = phi (y, z); y = phi (x, z)
11297 // where the phi nodes don't necessarily need to be in the same block. Do a
11298 // quick check to see if the PHI node only contains a single non-phi value, if
11299 // so, scan to see if the phi cycle is actually equal to that value.
11300 {
11301 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11302 // Scan for the first non-phi operand.
11303 while (InValNo != NumOperandVals &&
11304 isa<PHINode>(PN.getIncomingValue(InValNo)))
11305 ++InValNo;
11306
11307 if (InValNo != NumOperandVals) {
11308 Value *NonPhiInVal = PN.getOperand(InValNo);
11309
11310 // Scan the rest of the operands to see if there are any conflicts, if so
11311 // there is no need to recursively scan other phis.
11312 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11313 Value *OpVal = PN.getIncomingValue(InValNo);
11314 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11315 break;
11316 }
11317
11318 // If we scanned over all operands, then we have one unique value plus
11319 // phi values. Scan PHI nodes to see if they all merge in each other or
11320 // the value.
11321 if (InValNo == NumOperandVals) {
11322 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11323 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11324 return ReplaceInstUsesWith(PN, NonPhiInVal);
11325 }
11326 }
11327 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011328
Dan Gohman5b097012009-10-31 14:22:52 +000011329 // If there are multiple PHIs, sort their operands so that they all list
11330 // the blocks in the same order. This will help identical PHIs be eliminated
11331 // by other passes. Other passes shouldn't depend on this for correctness
11332 // however.
11333 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11334 if (&PN != FirstPN)
11335 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011336 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011337 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11338 if (BBA != BBB) {
11339 Value *VA = PN.getIncomingValue(i);
11340 unsigned j = PN.getBasicBlockIndex(BBB);
11341 Value *VB = PN.getIncomingValue(j);
11342 PN.setIncomingBlock(i, BBB);
11343 PN.setIncomingValue(i, VB);
11344 PN.setIncomingBlock(j, BBA);
11345 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011346 // NOTE: Instcombine normally would want us to "return &PN" if we
11347 // modified any of the operands of an instruction. However, since we
11348 // aren't adding or removing uses (just rearranging them) we don't do
11349 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011350 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011351 }
11352
Chris Lattner9956c052009-11-08 19:23:30 +000011353 // If this is an integer PHI and we know that it has an illegal type, see if
11354 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11355 // PHI into the various pieces being extracted. This sort of thing is
11356 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011357 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011358 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11359 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11360 return Res;
11361
Chris Lattner60921c92003-12-19 05:58:40 +000011362 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011363}
11364
Chris Lattner7e708292002-06-25 16:13:24 +000011365Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011366 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000011367 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011368 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011369 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011370
Chris Lattnere87597f2004-10-16 18:11:37 +000011371 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011372 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011373
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011374 bool HasZeroPointerIndex = false;
11375 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11376 HasZeroPointerIndex = C->isNullValue();
11377
11378 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011379 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011380
Chris Lattner28977af2004-04-05 01:30:19 +000011381 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011382 if (TD) {
11383 bool MadeChange = false;
11384 unsigned PtrSize = TD->getPointerSizeInBits();
11385
11386 gep_type_iterator GTI = gep_type_begin(GEP);
11387 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11388 I != E; ++I, ++GTI) {
11389 if (!isa<SequentialType>(*GTI)) continue;
11390
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011391 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011392 // to what we need. If narrower, sign-extend it to what we need. This
11393 // explicit cast can make subsequent optimizations more obvious.
11394 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011395 if (OpBits == PtrSize)
11396 continue;
11397
Chris Lattner2345d1d2009-08-30 20:01:10 +000011398 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011399 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011400 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011401 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011402 }
Chris Lattner28977af2004-04-05 01:30:19 +000011403
Chris Lattner90ac28c2002-08-02 19:29:35 +000011404 // Combine Indices - If the source pointer to this getelementptr instruction
11405 // is a getelementptr instruction, combine the indices of the two
11406 // getelementptr instructions into a single instruction.
11407 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011408 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011409 // Note that if our source is a gep chain itself that we wait for that
11410 // chain to be resolved before we perform this transformation. This
11411 // avoids us creating a TON of code in some cases.
11412 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011413 if (GetElementPtrInst *SrcGEP =
11414 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11415 if (SrcGEP->getNumOperands() == 2)
11416 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011417
Chris Lattner72588fc2007-02-15 22:48:32 +000011418 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011419
11420 // Find out whether the last index in the source GEP is a sequential idx.
11421 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011422 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11423 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011424 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011425
Chris Lattner90ac28c2002-08-02 19:29:35 +000011426 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011427 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011428 // Replace: gep (gep %P, long B), long A, ...
11429 // With: T = long A+B; gep %P, T, ...
11430 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011431 Value *Sum;
11432 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11433 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011434 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011435 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011436 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011437 Sum = SO1;
11438 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011439 // If they aren't the same type, then the input hasn't been processed
11440 // by the loop above yet (which canonicalizes sequential index types to
11441 // intptr_t). Just avoid transforming this until the input has been
11442 // normalized.
11443 if (SO1->getType() != GO1->getType())
11444 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011445 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011446 }
Chris Lattner620ce142004-05-07 22:09:22 +000011447
Chris Lattnerab984842009-08-30 05:30:55 +000011448 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011449 if (Src->getNumOperands() == 2) {
11450 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011451 GEP.setOperand(1, Sum);
11452 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011453 }
Chris Lattnerab984842009-08-30 05:30:55 +000011454 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011455 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011456 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011457 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011458 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011459 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011460 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011461 Indices.append(Src->op_begin()+1, Src->op_end());
11462 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011463 }
11464
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011465 if (!Indices.empty())
11466 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11467 Src->isInBounds()) ?
11468 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11469 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011470 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011471 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011472 }
11473
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011474 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11475 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011476 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011477
Chris Lattner2de23192009-08-30 20:38:21 +000011478 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11479 // want to change the gep until the bitcasts are eliminated.
11480 if (getBitCastOperand(X)) {
11481 Worklist.AddValue(PtrOp);
11482 return 0;
11483 }
11484
Chris Lattner963f4ba2009-08-30 20:36:46 +000011485 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11486 // into : GEP [10 x i8]* X, i32 0, ...
11487 //
11488 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11489 // into : GEP i8* X, ...
11490 //
11491 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011492 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011493 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11494 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011495 if (const ArrayType *CATy =
11496 dyn_cast<ArrayType>(CPTy->getElementType())) {
11497 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11498 if (CATy->getElementType() == XTy->getElementType()) {
11499 // -> GEP i8* X, ...
11500 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011501 return cast<GEPOperator>(&GEP)->isInBounds() ?
11502 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11503 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011504 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11505 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011506 }
11507
11508 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011509 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011510 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011511 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011512 // At this point, we know that the cast source type is a pointer
11513 // to an array of the same type as the destination pointer
11514 // array. Because the array type is never stepped over (there
11515 // is a leading zero) we can fold the cast into this GEP.
11516 GEP.setOperand(0, X);
11517 return &GEP;
11518 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011519 }
11520 }
Chris Lattnereed48272005-09-13 00:40:14 +000011521 } else if (GEP.getNumOperands() == 2) {
11522 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011523 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11524 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011525 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11526 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011527 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011528 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11529 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011530 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011531 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011532 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011533 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11534 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011535 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011536 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011537 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011538 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011539
11540 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011541 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011542 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011543 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011544
Owen Anderson1d0be152009-08-13 21:58:54 +000011545 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011546 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011547 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011548
11549 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11550 // allow either a mul, shift, or constant here.
11551 Value *NewIdx = 0;
11552 ConstantInt *Scale = 0;
11553 if (ArrayEltSize == 1) {
11554 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011555 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011556 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011557 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011558 Scale = CI;
11559 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11560 if (Inst->getOpcode() == Instruction::Shl &&
11561 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011562 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11563 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011564 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011565 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011566 NewIdx = Inst->getOperand(0);
11567 } else if (Inst->getOpcode() == Instruction::Mul &&
11568 isa<ConstantInt>(Inst->getOperand(1))) {
11569 Scale = cast<ConstantInt>(Inst->getOperand(1));
11570 NewIdx = Inst->getOperand(0);
11571 }
11572 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011573
Chris Lattner7835cdd2005-09-13 18:36:04 +000011574 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011575 // out, perform the transformation. Note, we don't know whether Scale is
11576 // signed or not. We'll use unsigned version of division/modulo
11577 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011578 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011579 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011580 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011581 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011582 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011583 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11584 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011585 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011586 }
11587
11588 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011589 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011590 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011591 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011592 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11593 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11594 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011595 // The NewGEP must be pointer typed, so must the old one -> BitCast
11596 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011597 }
11598 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011599 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011600 }
Chris Lattner58407792009-01-09 04:53:57 +000011601
Chris Lattner46cd5a12009-01-09 05:44:56 +000011602 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011603 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011604 /// Y = gep X, <...constant indices...>
11605 /// into a gep of the original struct. This is important for SROA and alias
11606 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011607 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011608 if (TD &&
11609 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011610 // Determine how much the GEP moves the pointer. We are guaranteed to get
11611 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011612 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011613 int64_t Offset = OffsetV->getSExtValue();
11614
11615 // If this GEP instruction doesn't move the pointer, just replace the GEP
11616 // with a bitcast of the real input to the dest type.
11617 if (Offset == 0) {
11618 // If the bitcast is of an allocation, and the allocation will be
11619 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011620 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011621 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011622 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11623 if (Instruction *I = visitBitCast(*BCI)) {
11624 if (I != BCI) {
11625 I->takeName(BCI);
11626 BCI->getParent()->getInstList().insert(BCI, I);
11627 ReplaceInstUsesWith(*BCI, I);
11628 }
11629 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011630 }
Chris Lattner58407792009-01-09 04:53:57 +000011631 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011632 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011633 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011634
11635 // Otherwise, if the offset is non-zero, we need to find out if there is a
11636 // field at Offset in 'A's type. If so, we can pull the cast through the
11637 // GEP.
11638 SmallVector<Value*, 8> NewIndices;
11639 const Type *InTy =
11640 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011641 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011642 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11643 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11644 NewIndices.end()) :
11645 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11646 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011647
11648 if (NGEP->getType() == GEP.getType())
11649 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011650 NGEP->takeName(&GEP);
11651 return new BitCastInst(NGEP, GEP.getType());
11652 }
Chris Lattner58407792009-01-09 04:53:57 +000011653 }
11654 }
11655
Chris Lattner8a2a3112001-12-14 16:52:21 +000011656 return 0;
11657}
11658
Victor Hernandez7b929da2009-10-23 21:09:37 +000011659Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011660 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011661 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011662 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11663 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011664 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011665 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011666 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011667 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011668
Chris Lattner0864acf2002-11-04 16:18:53 +000011669 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011670 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011671 //
11672 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011673 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011674
11675 // Now that I is pointing to the first non-allocation-inst in the block,
11676 // insert our getelementptr instruction...
11677 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011678 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011679 Value *Idx[2];
11680 Idx[0] = NullIdx;
11681 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011682 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11683 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011684
11685 // Now make everything use the getelementptr instead of the original
11686 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011687 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011688 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011689 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011690 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011691 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011692
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011693 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011694 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011695 // Note that we only do this for alloca's, because malloc should allocate
11696 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011697 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011698 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011699
11700 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11701 if (AI.getAlignment() == 0)
11702 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11703 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011704
Chris Lattner0864acf2002-11-04 16:18:53 +000011705 return 0;
11706}
11707
Victor Hernandez66284e02009-10-24 04:23:03 +000011708Instruction *InstCombiner::visitFree(Instruction &FI) {
11709 Value *Op = FI.getOperand(1);
11710
11711 // free undef -> unreachable.
11712 if (isa<UndefValue>(Op)) {
11713 // Insert a new store to null because we cannot modify the CFG here.
11714 new StoreInst(ConstantInt::getTrue(*Context),
11715 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11716 return EraseInstFromFunction(FI);
11717 }
11718
11719 // If we have 'free null' delete the instruction. This can happen in stl code
11720 // when lots of inlining happens.
11721 if (isa<ConstantPointerNull>(Op))
11722 return EraseInstFromFunction(FI);
11723
Victor Hernandez046e78c2009-10-26 23:43:48 +000011724 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011725 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011726 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11727 if (Op->hasOneUse() && CI->hasOneUse()) {
11728 EraseInstFromFunction(FI);
11729 EraseInstFromFunction(*CI);
11730 return EraseInstFromFunction(*cast<Instruction>(Op));
11731 }
11732 } else {
11733 // Op is a call to malloc
11734 if (Op->hasOneUse()) {
11735 EraseInstFromFunction(FI);
11736 return EraseInstFromFunction(*cast<Instruction>(Op));
11737 }
11738 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011739 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011740
11741 return 0;
11742}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011743
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011744/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011745static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011746 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011747 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011748 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011749 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011750
Mon P Wang6753f952009-02-07 22:19:29 +000011751 const PointerType *DestTy = cast<PointerType>(CI->getType());
11752 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011753 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011754
11755 // If the address spaces don't match, don't eliminate the cast.
11756 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11757 return 0;
11758
Chris Lattnerb89e0712004-07-13 01:49:43 +000011759 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011760
Reid Spencer42230162007-01-22 05:51:25 +000011761 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011762 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011763 // If the source is an array, the code below will not succeed. Check to
11764 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11765 // constants.
11766 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11767 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11768 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011769 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011770 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11771 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011772 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011773 SrcTy = cast<PointerType>(CastOp->getType());
11774 SrcPTy = SrcTy->getElementType();
11775 }
11776
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011777 if (IC.getTargetData() &&
11778 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011779 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011780 // Do not allow turning this into a load of an integer, which is then
11781 // casted to a pointer, this pessimizes pointer analysis a lot.
11782 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011783 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11784 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011785
Chris Lattnerf9527852005-01-31 04:50:46 +000011786 // Okay, we are casting from one integer or pointer type to another of
11787 // the same size. Instead of casting the pointer before the load, cast
11788 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011789 Value *NewLoad =
11790 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011791 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011792 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011793 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011794 }
11795 }
11796 return 0;
11797}
11798
Chris Lattner833b8a42003-06-26 05:06:25 +000011799Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11800 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011801
Dan Gohman9941f742007-07-20 16:34:21 +000011802 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011803 if (TD) {
11804 unsigned KnownAlign =
11805 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11806 if (KnownAlign >
11807 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11808 LI.getAlignment()))
11809 LI.setAlignment(KnownAlign);
11810 }
Dan Gohman9941f742007-07-20 16:34:21 +000011811
Chris Lattner963f4ba2009-08-30 20:36:46 +000011812 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011813 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011814 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011815 return Res;
11816
11817 // None of the following transforms are legal for volatile loads.
11818 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011819
Dan Gohman2276a7b2008-10-15 23:19:35 +000011820 // Do really simple store-to-load forwarding and load CSE, to catch cases
11821 // where there are several consequtive memory accesses to the same location,
11822 // separated by a few arithmetic operations.
11823 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011824 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11825 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011826
Chris Lattner878e4942009-10-22 06:25:11 +000011827 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011828 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11829 const Value *GEPI0 = GEPI->getOperand(0);
11830 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011831 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011832 // Insert a new store to null instruction before the load to indicate
11833 // that this code is not reachable. We do this instead of inserting
11834 // an unreachable instruction directly because we cannot modify the
11835 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011836 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011837 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011838 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011839 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011840 }
Chris Lattner37366c12005-05-01 04:24:53 +000011841
Chris Lattner878e4942009-10-22 06:25:11 +000011842 // load null/undef -> unreachable
11843 // TODO: Consider a target hook for valid address spaces for this xform.
11844 if (isa<UndefValue>(Op) ||
11845 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11846 // Insert a new store to null instruction before the load to indicate that
11847 // this code is not reachable. We do this instead of inserting an
11848 // unreachable instruction directly because we cannot modify the CFG.
11849 new StoreInst(UndefValue::get(LI.getType()),
11850 Constant::getNullValue(Op->getType()), &LI);
11851 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011852 }
Chris Lattner878e4942009-10-22 06:25:11 +000011853
11854 // Instcombine load (constantexpr_cast global) -> cast (load global)
11855 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11856 if (CE->isCast())
11857 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11858 return Res;
11859
Chris Lattner37366c12005-05-01 04:24:53 +000011860 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011861 // Change select and PHI nodes to select values instead of addresses: this
11862 // helps alias analysis out a lot, allows many others simplifications, and
11863 // exposes redundancy in the code.
11864 //
11865 // Note that we cannot do the transformation unless we know that the
11866 // introduced loads cannot trap! Something like this is valid as long as
11867 // the condition is always false: load (select bool %C, int* null, int* %G),
11868 // but it would not be valid if we transformed it to load from null
11869 // unconditionally.
11870 //
11871 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11872 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011873 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11874 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011875 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11876 SI->getOperand(1)->getName()+".val");
11877 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11878 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011879 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011880 }
11881
Chris Lattner684fe212004-09-23 15:46:00 +000011882 // load (select (cond, null, P)) -> load P
11883 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11884 if (C->isNullValue()) {
11885 LI.setOperand(0, SI->getOperand(2));
11886 return &LI;
11887 }
11888
11889 // load (select (cond, P, null)) -> load P
11890 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11891 if (C->isNullValue()) {
11892 LI.setOperand(0, SI->getOperand(1));
11893 return &LI;
11894 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011895 }
11896 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011897 return 0;
11898}
11899
Reid Spencer55af2b52007-01-19 21:20:31 +000011900/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011901/// when possible. This makes it generally easy to do alias analysis and/or
11902/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011903static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11904 User *CI = cast<User>(SI.getOperand(1));
11905 Value *CastOp = CI->getOperand(0);
11906
11907 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011908 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11909 if (SrcTy == 0) return 0;
11910
11911 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011912
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011913 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11914 return 0;
11915
Chris Lattner3914f722009-01-24 01:00:13 +000011916 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11917 /// to its first element. This allows us to handle things like:
11918 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11919 /// on 32-bit hosts.
11920 SmallVector<Value*, 4> NewGEPIndices;
11921
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011922 // If the source is an array, the code below will not succeed. Check to
11923 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11924 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011925 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11926 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011927 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011928 NewGEPIndices.push_back(Zero);
11929
11930 while (1) {
11931 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011932 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011933 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011934 NewGEPIndices.push_back(Zero);
11935 SrcPTy = STy->getElementType(0);
11936 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11937 NewGEPIndices.push_back(Zero);
11938 SrcPTy = ATy->getElementType();
11939 } else {
11940 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011941 }
Chris Lattner3914f722009-01-24 01:00:13 +000011942 }
11943
Owen Andersondebcb012009-07-29 22:17:13 +000011944 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011945 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011946
11947 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11948 return 0;
11949
Chris Lattner71759c42009-01-16 20:12:52 +000011950 // If the pointers point into different address spaces or if they point to
11951 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011952 if (!IC.getTargetData() ||
11953 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011954 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011955 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11956 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011957 return 0;
11958
11959 // Okay, we are casting from one integer or pointer type to another of
11960 // the same size. Instead of casting the pointer before
11961 // the store, cast the value to be stored.
11962 Value *NewCast;
11963 Value *SIOp0 = SI.getOperand(0);
11964 Instruction::CastOps opcode = Instruction::BitCast;
11965 const Type* CastSrcTy = SIOp0->getType();
11966 const Type* CastDstTy = SrcPTy;
11967 if (isa<PointerType>(CastDstTy)) {
11968 if (CastSrcTy->isInteger())
11969 opcode = Instruction::IntToPtr;
11970 } else if (isa<IntegerType>(CastDstTy)) {
11971 if (isa<PointerType>(SIOp0->getType()))
11972 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011973 }
Chris Lattner3914f722009-01-24 01:00:13 +000011974
11975 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11976 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011977 if (!NewGEPIndices.empty())
11978 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11979 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011980
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011981 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11982 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011983 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011984}
11985
Chris Lattner4aebaee2008-11-27 08:56:30 +000011986/// equivalentAddressValues - Test if A and B will obviously have the same
11987/// value. This includes recognizing that %t0 and %t1 will have the same
11988/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011989/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011990/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011991/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011992/// %t2 = load i32* %t1
11993///
11994static bool equivalentAddressValues(Value *A, Value *B) {
11995 // Test if the values are trivially equivalent.
11996 if (A == B) return true;
11997
11998 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011999 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12000 // its only used to compare two uses within the same basic block, which
12001 // means that they'll always either have the same value or one of them
12002 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012003 if (isa<BinaryOperator>(A) ||
12004 isa<CastInst>(A) ||
12005 isa<PHINode>(A) ||
12006 isa<GetElementPtrInst>(A))
12007 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012008 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012009 return true;
12010
12011 // Otherwise they may not be equivalent.
12012 return false;
12013}
12014
Dale Johannesen4945c652009-03-03 21:26:39 +000012015// If this instruction has two uses, one of which is a llvm.dbg.declare,
12016// return the llvm.dbg.declare.
12017DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12018 if (!V->hasNUses(2))
12019 return 0;
12020 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12021 UI != E; ++UI) {
12022 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12023 return DI;
12024 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12025 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12026 return DI;
12027 }
12028 }
12029 return 0;
12030}
12031
Chris Lattner2f503e62005-01-31 05:36:43 +000012032Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12033 Value *Val = SI.getOperand(0);
12034 Value *Ptr = SI.getOperand(1);
12035
12036 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000012037 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012038 ++NumCombined;
12039 return 0;
12040 }
Chris Lattner836692d2007-01-15 06:51:56 +000012041
12042 // If the RHS is an alloca with a single use, zapify the store, making the
12043 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012044 // If the RHS is an alloca with a two uses, the other one being a
12045 // llvm.dbg.declare, zapify the store and the declare, making the
12046 // alloca dead. We must do this to prevent declare's from affecting
12047 // codegen.
12048 if (!SI.isVolatile()) {
12049 if (Ptr->hasOneUse()) {
12050 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012051 EraseInstFromFunction(SI);
12052 ++NumCombined;
12053 return 0;
12054 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012055 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12056 if (isa<AllocaInst>(GEP->getOperand(0))) {
12057 if (GEP->getOperand(0)->hasOneUse()) {
12058 EraseInstFromFunction(SI);
12059 ++NumCombined;
12060 return 0;
12061 }
12062 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12063 EraseInstFromFunction(*DI);
12064 EraseInstFromFunction(SI);
12065 ++NumCombined;
12066 return 0;
12067 }
12068 }
12069 }
12070 }
12071 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12072 EraseInstFromFunction(*DI);
12073 EraseInstFromFunction(SI);
12074 ++NumCombined;
12075 return 0;
12076 }
Chris Lattner836692d2007-01-15 06:51:56 +000012077 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012078
Dan Gohman9941f742007-07-20 16:34:21 +000012079 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012080 if (TD) {
12081 unsigned KnownAlign =
12082 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12083 if (KnownAlign >
12084 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12085 SI.getAlignment()))
12086 SI.setAlignment(KnownAlign);
12087 }
Dan Gohman9941f742007-07-20 16:34:21 +000012088
Dale Johannesenacb51a32009-03-03 01:43:03 +000012089 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012090 // stores to the same location, separated by a few arithmetic operations. This
12091 // situation often occurs with bitfield accesses.
12092 BasicBlock::iterator BBI = &SI;
12093 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12094 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012095 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012096 // Don't count debug info directives, lest they affect codegen,
12097 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12098 // It is necessary for correctness to skip those that feed into a
12099 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012100 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012101 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012102 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012103 continue;
12104 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012105
12106 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12107 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012108 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12109 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012110 ++NumDeadStore;
12111 ++BBI;
12112 EraseInstFromFunction(*PrevSI);
12113 continue;
12114 }
12115 break;
12116 }
12117
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012118 // If this is a load, we have to stop. However, if the loaded value is from
12119 // the pointer we're loading and is producing the pointer we're storing,
12120 // then *this* store is dead (X = load P; store X -> P).
12121 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012122 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12123 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012124 EraseInstFromFunction(SI);
12125 ++NumCombined;
12126 return 0;
12127 }
12128 // Otherwise, this is a load from some other location. Stores before it
12129 // may not be dead.
12130 break;
12131 }
12132
Chris Lattner9ca96412006-02-08 03:25:32 +000012133 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012134 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012135 break;
12136 }
12137
12138
12139 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012140
12141 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012142 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012143 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012144 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012145 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012146 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012147 ++NumCombined;
12148 }
12149 return 0; // Do not modify these!
12150 }
12151
12152 // store undef, Ptr -> noop
12153 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012154 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012155 ++NumCombined;
12156 return 0;
12157 }
12158
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012159 // If the pointer destination is a cast, see if we can fold the cast into the
12160 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012161 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012162 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12163 return Res;
12164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012165 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012166 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12167 return Res;
12168
Chris Lattner408902b2005-09-12 23:23:25 +000012169
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012170 // If this store is the last instruction in the basic block (possibly
12171 // excepting debug info instructions and the pointer bitcasts that feed
12172 // into them), and if the block ends with an unconditional branch, try
12173 // to move it to the successor block.
12174 BBI = &SI;
12175 do {
12176 ++BBI;
12177 } while (isa<DbgInfoIntrinsic>(BBI) ||
12178 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012179 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012180 if (BI->isUnconditional())
12181 if (SimplifyStoreAtEndOfBlock(SI))
12182 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012183
Chris Lattner2f503e62005-01-31 05:36:43 +000012184 return 0;
12185}
12186
Chris Lattner3284d1f2007-04-15 00:07:55 +000012187/// SimplifyStoreAtEndOfBlock - Turn things like:
12188/// if () { *P = v1; } else { *P = v2 }
12189/// into a phi node with a store in the successor.
12190///
Chris Lattner31755a02007-04-15 01:02:18 +000012191/// Simplify things like:
12192/// *P = v1; if () { *P = v2; }
12193/// into a phi node with a store in the successor.
12194///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012195bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12196 BasicBlock *StoreBB = SI.getParent();
12197
12198 // Check to see if the successor block has exactly two incoming edges. If
12199 // so, see if the other predecessor contains a store to the same location.
12200 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012201 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012202
12203 // Determine whether Dest has exactly two predecessors and, if so, compute
12204 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012205 pred_iterator PI = pred_begin(DestBB);
12206 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012207 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012208 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012209 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012210 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012211 return false;
12212
12213 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012214 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012215 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012216 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012217 }
Chris Lattner31755a02007-04-15 01:02:18 +000012218 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012219 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012220
12221 // Bail out if all the relevant blocks aren't distinct (this can happen,
12222 // for example, if SI is in an infinite loop)
12223 if (StoreBB == DestBB || OtherBB == DestBB)
12224 return false;
12225
Chris Lattner31755a02007-04-15 01:02:18 +000012226 // Verify that the other block ends in a branch and is not otherwise empty.
12227 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012228 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012229 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012230 return false;
12231
Chris Lattner31755a02007-04-15 01:02:18 +000012232 // If the other block ends in an unconditional branch, check for the 'if then
12233 // else' case. there is an instruction before the branch.
12234 StoreInst *OtherStore = 0;
12235 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012236 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012237 // Skip over debugging info.
12238 while (isa<DbgInfoIntrinsic>(BBI) ||
12239 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12240 if (BBI==OtherBB->begin())
12241 return false;
12242 --BBI;
12243 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012244 // If this isn't a store, isn't a store to the same location, or if the
12245 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012246 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012247 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12248 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012249 return false;
12250 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012251 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012252 // destinations is StoreBB, then we have the if/then case.
12253 if (OtherBr->getSuccessor(0) != StoreBB &&
12254 OtherBr->getSuccessor(1) != StoreBB)
12255 return false;
12256
12257 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012258 // if/then triangle. See if there is a store to the same ptr as SI that
12259 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012260 for (;; --BBI) {
12261 // Check to see if we find the matching store.
12262 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012263 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12264 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012265 return false;
12266 break;
12267 }
Eli Friedman6903a242008-06-13 22:02:12 +000012268 // If we find something that may be using or overwriting the stored
12269 // value, or if we run out of instructions, we can't do the xform.
12270 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012271 BBI == OtherBB->begin())
12272 return false;
12273 }
12274
12275 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012276 // make sure nothing reads or overwrites the stored value in
12277 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012278 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12279 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012280 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012281 return false;
12282 }
12283 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012284
Chris Lattner31755a02007-04-15 01:02:18 +000012285 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012286 Value *MergedVal = OtherStore->getOperand(0);
12287 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012288 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012289 PN->reserveOperandSpace(2);
12290 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012291 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12292 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012293 }
12294
12295 // Advance to a place where it is safe to insert the new store and
12296 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012297 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012298 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012299 OtherStore->isVolatile(),
12300 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012301
12302 // Nuke the old stores.
12303 EraseInstFromFunction(SI);
12304 EraseInstFromFunction(*OtherStore);
12305 ++NumCombined;
12306 return true;
12307}
12308
Chris Lattner2f503e62005-01-31 05:36:43 +000012309
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012310Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12311 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012312 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012313 BasicBlock *TrueDest;
12314 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012315 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012316 !isa<Constant>(X)) {
12317 // Swap Destinations and condition...
12318 BI.setCondition(X);
12319 BI.setSuccessor(0, FalseDest);
12320 BI.setSuccessor(1, TrueDest);
12321 return &BI;
12322 }
12323
Reid Spencere4d87aa2006-12-23 06:05:41 +000012324 // Cannonicalize fcmp_one -> fcmp_oeq
12325 FCmpInst::Predicate FPred; Value *Y;
12326 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012327 TrueDest, FalseDest)) &&
12328 BI.getCondition()->hasOneUse())
12329 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12330 FPred == FCmpInst::FCMP_OGE) {
12331 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12332 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12333
12334 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012335 BI.setSuccessor(0, FalseDest);
12336 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012337 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012338 return &BI;
12339 }
12340
12341 // Cannonicalize icmp_ne -> icmp_eq
12342 ICmpInst::Predicate IPred;
12343 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012344 TrueDest, FalseDest)) &&
12345 BI.getCondition()->hasOneUse())
12346 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12347 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12348 IPred == ICmpInst::ICMP_SGE) {
12349 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12350 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12351 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012352 BI.setSuccessor(0, FalseDest);
12353 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012354 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012355 return &BI;
12356 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012357
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012358 return 0;
12359}
Chris Lattner0864acf2002-11-04 16:18:53 +000012360
Chris Lattner46238a62004-07-03 00:26:11 +000012361Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12362 Value *Cond = SI.getCondition();
12363 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12364 if (I->getOpcode() == Instruction::Add)
12365 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12366 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12367 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012368 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012369 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012370 AddRHS));
12371 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012372 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012373 return &SI;
12374 }
12375 }
12376 return 0;
12377}
12378
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012379Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012380 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012381
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012382 if (!EV.hasIndices())
12383 return ReplaceInstUsesWith(EV, Agg);
12384
12385 if (Constant *C = dyn_cast<Constant>(Agg)) {
12386 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012387 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012388
12389 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012390 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012391
12392 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12393 // Extract the element indexed by the first index out of the constant
12394 Value *V = C->getOperand(*EV.idx_begin());
12395 if (EV.getNumIndices() > 1)
12396 // Extract the remaining indices out of the constant indexed by the
12397 // first index
12398 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12399 else
12400 return ReplaceInstUsesWith(EV, V);
12401 }
12402 return 0; // Can't handle other constants
12403 }
12404 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12405 // We're extracting from an insertvalue instruction, compare the indices
12406 const unsigned *exti, *exte, *insi, *inse;
12407 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12408 exte = EV.idx_end(), inse = IV->idx_end();
12409 exti != exte && insi != inse;
12410 ++exti, ++insi) {
12411 if (*insi != *exti)
12412 // The insert and extract both reference distinctly different elements.
12413 // This means the extract is not influenced by the insert, and we can
12414 // replace the aggregate operand of the extract with the aggregate
12415 // operand of the insert. i.e., replace
12416 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12417 // %E = extractvalue { i32, { i32 } } %I, 0
12418 // with
12419 // %E = extractvalue { i32, { i32 } } %A, 0
12420 return ExtractValueInst::Create(IV->getAggregateOperand(),
12421 EV.idx_begin(), EV.idx_end());
12422 }
12423 if (exti == exte && insi == inse)
12424 // Both iterators are at the end: Index lists are identical. Replace
12425 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12426 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12427 // with "i32 42"
12428 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12429 if (exti == exte) {
12430 // The extract list is a prefix of the insert list. i.e. replace
12431 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12432 // %E = extractvalue { i32, { i32 } } %I, 1
12433 // with
12434 // %X = extractvalue { i32, { i32 } } %A, 1
12435 // %E = insertvalue { i32 } %X, i32 42, 0
12436 // by switching the order of the insert and extract (though the
12437 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012438 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12439 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012440 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12441 insi, inse);
12442 }
12443 if (insi == inse)
12444 // The insert list is a prefix of the extract list
12445 // We can simply remove the common indices from the extract and make it
12446 // operate on the inserted value instead of the insertvalue result.
12447 // i.e., replace
12448 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12449 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12450 // with
12451 // %E extractvalue { i32 } { i32 42 }, 0
12452 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12453 exti, exte);
12454 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012455 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12456 // We're extracting from an intrinsic, see if we're the only user, which
12457 // allows us to simplify multiple result intrinsics to simpler things that
12458 // just get one value..
12459 if (II->hasOneUse()) {
12460 // Check if we're grabbing the overflow bit or the result of a 'with
12461 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12462 // and replace it with a traditional binary instruction.
12463 switch (II->getIntrinsicID()) {
12464 case Intrinsic::uadd_with_overflow:
12465 case Intrinsic::sadd_with_overflow:
12466 if (*EV.idx_begin() == 0) { // Normal result.
12467 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12468 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12469 EraseInstFromFunction(*II);
12470 return BinaryOperator::CreateAdd(LHS, RHS);
12471 }
12472 break;
12473 case Intrinsic::usub_with_overflow:
12474 case Intrinsic::ssub_with_overflow:
12475 if (*EV.idx_begin() == 0) { // Normal result.
12476 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12477 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12478 EraseInstFromFunction(*II);
12479 return BinaryOperator::CreateSub(LHS, RHS);
12480 }
12481 break;
12482 case Intrinsic::umul_with_overflow:
12483 case Intrinsic::smul_with_overflow:
12484 if (*EV.idx_begin() == 0) { // Normal result.
12485 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12486 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12487 EraseInstFromFunction(*II);
12488 return BinaryOperator::CreateMul(LHS, RHS);
12489 }
12490 break;
12491 default:
12492 break;
12493 }
12494 }
12495 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012496 // Can't simplify extracts from other values. Note that nested extracts are
12497 // already simplified implicitely by the above (extract ( extract (insert) )
12498 // will be translated into extract ( insert ( extract ) ) first and then just
12499 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012500 return 0;
12501}
12502
Chris Lattner220b0cf2006-03-05 00:22:33 +000012503/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12504/// is to leave as a vector operation.
12505static bool CheapToScalarize(Value *V, bool isConstant) {
12506 if (isa<ConstantAggregateZero>(V))
12507 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012508 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012509 if (isConstant) return true;
12510 // If all elts are the same, we can extract.
12511 Constant *Op0 = C->getOperand(0);
12512 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12513 if (C->getOperand(i) != Op0)
12514 return false;
12515 return true;
12516 }
12517 Instruction *I = dyn_cast<Instruction>(V);
12518 if (!I) return false;
12519
12520 // Insert element gets simplified to the inserted element or is deleted if
12521 // this is constant idx extract element and its a constant idx insertelt.
12522 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12523 isa<ConstantInt>(I->getOperand(2)))
12524 return true;
12525 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12526 return true;
12527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12528 if (BO->hasOneUse() &&
12529 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12530 CheapToScalarize(BO->getOperand(1), isConstant)))
12531 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012532 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12533 if (CI->hasOneUse() &&
12534 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12535 CheapToScalarize(CI->getOperand(1), isConstant)))
12536 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012537
12538 return false;
12539}
12540
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012541/// Read and decode a shufflevector mask.
12542///
12543/// It turns undef elements into values that are larger than the number of
12544/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012545static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12546 unsigned NElts = SVI->getType()->getNumElements();
12547 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12548 return std::vector<unsigned>(NElts, 0);
12549 if (isa<UndefValue>(SVI->getOperand(2)))
12550 return std::vector<unsigned>(NElts, 2*NElts);
12551
12552 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012553 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012554 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12555 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012556 Result.push_back(NElts*2); // undef -> 8
12557 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012558 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012559 return Result;
12560}
12561
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012562/// FindScalarElement - Given a vector and an element number, see if the scalar
12563/// value is already around as a register, for example if it were inserted then
12564/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012565static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012566 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012567 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12568 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012569 unsigned Width = PTy->getNumElements();
12570 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012571 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012572
12573 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012574 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012575 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012576 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012577 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012578 return CP->getOperand(EltNo);
12579 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12580 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012581 if (!isa<ConstantInt>(III->getOperand(2)))
12582 return 0;
12583 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012584
12585 // If this is an insert to the element we are looking for, return the
12586 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012587 if (EltNo == IIElt)
12588 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012589
12590 // Otherwise, the insertelement doesn't modify the value, recurse on its
12591 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012592 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012593 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012594 unsigned LHSWidth =
12595 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012596 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012597 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012598 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012599 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012600 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012601 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012602 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012603 }
12604
12605 // Otherwise, we don't know.
12606 return 0;
12607}
12608
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012609Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012610 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012611 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012612 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012613
Dan Gohman07a96762007-07-16 14:29:03 +000012614 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012615 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012616 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012617
Reid Spencer9d6565a2007-02-15 02:26:10 +000012618 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012619 // If vector val is constant with all elements the same, replace EI with
12620 // that element. When the elements are not identical, we cannot replace yet
12621 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012622 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012623 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012624 if (C->getOperand(i) != op0) {
12625 op0 = 0;
12626 break;
12627 }
12628 if (op0)
12629 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012630 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012631
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012632 // If extracting a specified index from the vector, see if we can recursively
12633 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012634 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012635 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012636 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012637
12638 // If this is extracting an invalid index, turn this into undef, to avoid
12639 // crashing the code below.
12640 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012641 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012642
Chris Lattner867b99f2006-10-05 06:55:50 +000012643 // This instruction only demands the single element from the input vector.
12644 // If the input vector has a single use, simplify it based on this use
12645 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012646 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012647 APInt UndefElts(VectorWidth, 0);
12648 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012649 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012650 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012651 EI.setOperand(0, V);
12652 return &EI;
12653 }
12654 }
12655
Owen Andersond672ecb2009-07-03 00:17:18 +000012656 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012657 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012658
12659 // If the this extractelement is directly using a bitcast from a vector of
12660 // the same number of elements, see if we can find the source element from
12661 // it. In this case, we will end up needing to bitcast the scalars.
12662 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12663 if (const VectorType *VT =
12664 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12665 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012666 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12667 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012668 return new BitCastInst(Elt, EI.getType());
12669 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012670 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012671
Chris Lattner73fa49d2006-05-25 22:53:38 +000012672 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012673 // Push extractelement into predecessor operation if legal and
12674 // profitable to do so
12675 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12676 if (I->hasOneUse() &&
12677 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12678 Value *newEI0 =
12679 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12680 EI.getName()+".lhs");
12681 Value *newEI1 =
12682 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12683 EI.getName()+".rhs");
12684 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012685 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012686 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012687 // Extracting the inserted element?
12688 if (IE->getOperand(2) == EI.getOperand(1))
12689 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12690 // If the inserted and extracted elements are constants, they must not
12691 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012692 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012693 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012694 EI.setOperand(0, IE->getOperand(0));
12695 return &EI;
12696 }
12697 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12698 // If this is extracting an element from a shufflevector, figure out where
12699 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012700 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12701 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012702 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012703 unsigned LHSWidth =
12704 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12705
12706 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012707 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012708 else if (SrcIdx < LHSWidth*2) {
12709 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012710 Src = SVI->getOperand(1);
12711 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012712 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012713 }
Eric Christophera3500da2009-07-25 02:28:41 +000012714 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012715 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12716 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012717 }
12718 }
Eli Friedman2451a642009-07-18 23:06:53 +000012719 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012720 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012721 return 0;
12722}
12723
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012724/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12725/// elements from either LHS or RHS, return the shuffle mask and true.
12726/// Otherwise, return false.
12727static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012728 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012729 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012730 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12731 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012732 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012733
12734 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012735 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012736 return true;
12737 } else if (V == LHS) {
12738 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012739 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012740 return true;
12741 } else if (V == RHS) {
12742 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012743 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012744 return true;
12745 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12746 // If this is an insert of an extract from some other vector, include it.
12747 Value *VecOp = IEI->getOperand(0);
12748 Value *ScalarOp = IEI->getOperand(1);
12749 Value *IdxOp = IEI->getOperand(2);
12750
Chris Lattnerd929f062006-04-27 21:14:21 +000012751 if (!isa<ConstantInt>(IdxOp))
12752 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012753 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012754
12755 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12756 // Okay, we can handle this if the vector we are insertinting into is
12757 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012758 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012759 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012760 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012761 return true;
12762 }
12763 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12764 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012765 EI->getOperand(0)->getType() == V->getType()) {
12766 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012767 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012768
12769 // This must be extracting from either LHS or RHS.
12770 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12771 // Okay, we can handle this if the vector we are insertinting into is
12772 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012773 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012774 // If so, update the mask to reflect the inserted value.
12775 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012776 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012777 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012778 } else {
12779 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012780 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012781 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012782
12783 }
12784 return true;
12785 }
12786 }
12787 }
12788 }
12789 }
12790 // TODO: Handle shufflevector here!
12791
12792 return false;
12793}
12794
12795/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12796/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12797/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012798static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012799 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012800 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012801 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012802 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012803 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012804
12805 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012806 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012807 return V;
12808 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012809 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012810 return V;
12811 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12812 // If this is an insert of an extract from some other vector, include it.
12813 Value *VecOp = IEI->getOperand(0);
12814 Value *ScalarOp = IEI->getOperand(1);
12815 Value *IdxOp = IEI->getOperand(2);
12816
12817 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12818 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12819 EI->getOperand(0)->getType() == V->getType()) {
12820 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012821 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12822 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012823
12824 // Either the extracted from or inserted into vector must be RHSVec,
12825 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012826 if (EI->getOperand(0) == RHS || RHS == 0) {
12827 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012828 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012829 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012830 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012831 return V;
12832 }
12833
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012834 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012835 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12836 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012837 // Everything but the extracted element is replaced with the RHS.
12838 for (unsigned i = 0; i != NumElts; ++i) {
12839 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012840 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012841 }
12842 return V;
12843 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012844
12845 // If this insertelement is a chain that comes from exactly these two
12846 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012847 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12848 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012849 return EI->getOperand(0);
12850
Chris Lattnerefb47352006-04-15 01:39:45 +000012851 }
12852 }
12853 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012854 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012855
12856 // Otherwise, can't do anything fancy. Return an identity vector.
12857 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012858 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012859 return V;
12860}
12861
12862Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12863 Value *VecOp = IE.getOperand(0);
12864 Value *ScalarOp = IE.getOperand(1);
12865 Value *IdxOp = IE.getOperand(2);
12866
Chris Lattner599ded12007-04-09 01:11:16 +000012867 // Inserting an undef or into an undefined place, remove this.
12868 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12869 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012870
Chris Lattnerefb47352006-04-15 01:39:45 +000012871 // If the inserted element was extracted from some other vector, and if the
12872 // indexes are constant, try to turn this into a shufflevector operation.
12873 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12874 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12875 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012876 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012877 unsigned ExtractedIdx =
12878 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012879 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012880
12881 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12882 return ReplaceInstUsesWith(IE, VecOp);
12883
12884 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012885 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012886
12887 // If we are extracting a value from a vector, then inserting it right
12888 // back into the same place, just use the input vector.
12889 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12890 return ReplaceInstUsesWith(IE, VecOp);
12891
Chris Lattnerefb47352006-04-15 01:39:45 +000012892 // If this insertelement isn't used by some other insertelement, turn it
12893 // (and any insertelements it points to), into one big shuffle.
12894 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12895 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012896 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012897 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012898 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012899 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012900 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012901 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012902 }
12903 }
12904 }
12905
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012906 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12907 APInt UndefElts(VWidth, 0);
12908 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12909 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12910 return &IE;
12911
Chris Lattnerefb47352006-04-15 01:39:45 +000012912 return 0;
12913}
12914
12915
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012916Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12917 Value *LHS = SVI.getOperand(0);
12918 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012919 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012920
12921 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012922
Chris Lattner867b99f2006-10-05 06:55:50 +000012923 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012924 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012925 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012926
Dan Gohman488fbfc2008-09-09 18:11:14 +000012927 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012928
12929 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12930 return 0;
12931
Evan Cheng388df622009-02-03 10:05:09 +000012932 APInt UndefElts(VWidth, 0);
12933 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12934 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012935 LHS = SVI.getOperand(0);
12936 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012937 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012938 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012939
Chris Lattner863bcff2006-05-25 23:48:38 +000012940 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12941 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12942 if (LHS == RHS || isa<UndefValue>(LHS)) {
12943 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012944 // shuffle(undef,undef,mask) -> undef.
12945 return ReplaceInstUsesWith(SVI, LHS);
12946 }
12947
Chris Lattner863bcff2006-05-25 23:48:38 +000012948 // Remap any references to RHS to use LHS.
12949 std::vector<Constant*> Elts;
12950 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012951 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012952 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012953 else {
12954 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012955 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012956 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012957 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012958 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012959 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012960 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012961 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012962 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012963 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012964 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012965 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012966 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012967 LHS = SVI.getOperand(0);
12968 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012969 MadeChange = true;
12970 }
12971
Chris Lattner7b2e27922006-05-26 00:29:06 +000012972 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012973 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012974
Chris Lattner863bcff2006-05-25 23:48:38 +000012975 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12976 if (Mask[i] >= e*2) continue; // Ignore undef values.
12977 // Is this an identity shuffle of the LHS value?
12978 isLHSID &= (Mask[i] == i);
12979
12980 // Is this an identity shuffle of the RHS value?
12981 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012982 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012983
Chris Lattner863bcff2006-05-25 23:48:38 +000012984 // Eliminate identity shuffles.
12985 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12986 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012987
Chris Lattner7b2e27922006-05-26 00:29:06 +000012988 // If the LHS is a shufflevector itself, see if we can combine it with this
12989 // one without producing an unusual shuffle. Here we are really conservative:
12990 // we are absolutely afraid of producing a shuffle mask not in the input
12991 // program, because the code gen may not be smart enough to turn a merged
12992 // shuffle into two specific shuffles: it may produce worse code. As such,
12993 // we only merge two shuffles if the result is one of the two input shuffle
12994 // masks. In this case, merging the shuffles just removes one instruction,
12995 // which we know is safe. This is good for things like turning:
12996 // (splat(splat)) -> splat.
12997 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12998 if (isa<UndefValue>(RHS)) {
12999 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13000
13001 std::vector<unsigned> NewMask;
13002 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13003 if (Mask[i] >= 2*e)
13004 NewMask.push_back(2*e);
13005 else
13006 NewMask.push_back(LHSMask[Mask[i]]);
13007
13008 // If the result mask is equal to the src shuffle or this shuffle mask, do
13009 // the replacement.
13010 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000013011 unsigned LHSInNElts =
13012 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000013013 std::vector<Constant*> Elts;
13014 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000013015 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013016 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013017 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000013018 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013019 }
13020 }
13021 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13022 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000013023 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013024 }
13025 }
13026 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013027
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013028 return MadeChange ? &SVI : 0;
13029}
13030
13031
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013032
Chris Lattnerea1c4542004-12-08 23:43:58 +000013033
13034/// TryToSinkInstruction - Try to move the specified instruction from its
13035/// current block into the beginning of DestBlock, which can only happen if it's
13036/// safe to move the instruction past all of the instructions between it and the
13037/// end of its block.
13038static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13039 assert(I->hasOneUse() && "Invariants didn't hold!");
13040
Chris Lattner108e9022005-10-27 17:13:11 +000013041 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013042 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013043 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013044
Chris Lattnerea1c4542004-12-08 23:43:58 +000013045 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013046 if (isa<AllocaInst>(I) && I->getParent() ==
13047 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013048 return false;
13049
Chris Lattner96a52a62004-12-09 07:14:34 +000013050 // We can only sink load instructions if there is nothing between the load and
13051 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013052 if (I->mayReadFromMemory()) {
13053 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013054 Scan != E; ++Scan)
13055 if (Scan->mayWriteToMemory())
13056 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013057 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013058
Dan Gohman02dea8b2008-05-23 21:05:58 +000013059 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013060
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013061 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013062 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013063 ++NumSunkInst;
13064 return true;
13065}
13066
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013067
13068/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13069/// all reachable code to the worklist.
13070///
13071/// This has a couple of tricks to make the code faster and more powerful. In
13072/// particular, we constant fold and DCE instructions as we go, to avoid adding
13073/// them to the worklist (this significantly speeds up instcombine on code where
13074/// many instructions are dead or constant). Additionally, if we find a branch
13075/// whose condition is a known constant, we only visit the reachable successors.
13076///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013077static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013078 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013079 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013080 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013081 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013082 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013083 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013084
13085 std::vector<Instruction*> InstrsForInstCombineWorklist;
13086 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013087
Chris Lattner2ee743b2009-10-15 04:59:28 +000013088 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13089
Chris Lattner2c7718a2007-03-23 19:17:18 +000013090 while (!Worklist.empty()) {
13091 BB = Worklist.back();
13092 Worklist.pop_back();
13093
13094 // We have now visited this block! If we've already been here, ignore it.
13095 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013096
Chris Lattner2c7718a2007-03-23 19:17:18 +000013097 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13098 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013099
Chris Lattner2c7718a2007-03-23 19:17:18 +000013100 // DCE instruction if trivially dead.
13101 if (isInstructionTriviallyDead(Inst)) {
13102 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013103 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013104 Inst->eraseFromParent();
13105 continue;
13106 }
13107
13108 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013109 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013110 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013111 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13112 << *Inst << '\n');
13113 Inst->replaceAllUsesWith(C);
13114 ++NumConstProp;
13115 Inst->eraseFromParent();
13116 continue;
13117 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013118
13119
13120
13121 if (TD) {
13122 // See if we can constant fold its operands.
13123 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13124 i != e; ++i) {
13125 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13126 if (CE == 0) continue;
13127
13128 // If we already folded this constant, don't try again.
13129 if (!FoldedConstants.insert(CE))
13130 continue;
13131
Chris Lattner7b550cc2009-11-06 04:27:31 +000013132 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013133 if (NewC && NewC != CE) {
13134 *i = NewC;
13135 MadeIRChange = true;
13136 }
13137 }
13138 }
13139
Devang Patel7fe1dec2008-11-19 18:56:50 +000013140
Chris Lattner67f7d542009-10-12 03:58:40 +000013141 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013142 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013143
13144 // Recursively visit successors. If this is a branch or switch on a
13145 // constant, only visit the reachable successor.
13146 TerminatorInst *TI = BB->getTerminator();
13147 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13148 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13149 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013150 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013151 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013152 continue;
13153 }
13154 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13155 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13156 // See if this is an explicit destination.
13157 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13158 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013159 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013160 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013161 continue;
13162 }
13163
13164 // Otherwise it is the default destination.
13165 Worklist.push_back(SI->getSuccessor(0));
13166 continue;
13167 }
13168 }
13169
13170 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13171 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013172 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013173
13174 // Once we've found all of the instructions to add to instcombine's worklist,
13175 // add them in reverse order. This way instcombine will visit from the top
13176 // of the function down. This jives well with the way that it adds all uses
13177 // of instructions to the worklist after doing a transformation, thus avoiding
13178 // some N^2 behavior in pathological cases.
13179 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13180 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013181
13182 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013183}
13184
Chris Lattnerec9c3582007-03-03 02:04:50 +000013185bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013186 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013187
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013188 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13189 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013190
Chris Lattnerb3d59702005-07-07 20:40:38 +000013191 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013192 // Do a depth-first traversal of the function, populate the worklist with
13193 // the reachable instructions. Ignore blocks that are not reachable. Keep
13194 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013195 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013196 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013197
Chris Lattnerb3d59702005-07-07 20:40:38 +000013198 // Do a quick scan over the function. If we find any blocks that are
13199 // unreachable, remove any instructions inside of them. This prevents
13200 // the instcombine code from having to deal with some bad special cases.
13201 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13202 if (!Visited.count(BB)) {
13203 Instruction *Term = BB->getTerminator();
13204 while (Term != BB->begin()) { // Remove instrs bottom-up
13205 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013206
Chris Lattnerbdff5482009-08-23 04:37:46 +000013207 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013208 // A debug intrinsic shouldn't force another iteration if we weren't
13209 // going to do one without it.
13210 if (!isa<DbgInfoIntrinsic>(I)) {
13211 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013212 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013213 }
Devang Patel228ebd02009-10-13 22:56:32 +000013214
Devang Patel228ebd02009-10-13 22:56:32 +000013215 // If I is not void type then replaceAllUsesWith undef.
13216 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013217 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013218 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013219 I->eraseFromParent();
13220 }
13221 }
13222 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013223
Chris Lattner873ff012009-08-30 05:55:36 +000013224 while (!Worklist.isEmpty()) {
13225 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013226 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013227
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013228 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013229 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013230 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013231 EraseInstFromFunction(*I);
13232 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013233 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013234 continue;
13235 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013236
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013237 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013238 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013239 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013240 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013241
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013242 // Add operands to the worklist.
13243 ReplaceInstUsesWith(*I, C);
13244 ++NumConstProp;
13245 EraseInstFromFunction(*I);
13246 MadeIRChange = true;
13247 continue;
13248 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013249
Chris Lattnerea1c4542004-12-08 23:43:58 +000013250 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013251 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013252 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013253 Instruction *UserInst = cast<Instruction>(I->use_back());
13254 BasicBlock *UserParent;
13255
13256 // Get the block the use occurs in.
13257 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13258 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13259 else
13260 UserParent = UserInst->getParent();
13261
Chris Lattnerea1c4542004-12-08 23:43:58 +000013262 if (UserParent != BB) {
13263 bool UserIsSuccessor = false;
13264 // See if the user is one of our successors.
13265 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13266 if (*SI == UserParent) {
13267 UserIsSuccessor = true;
13268 break;
13269 }
13270
13271 // If the user is one of our immediate successors, and if that successor
13272 // only has us as a predecessors (we'd have to split the critical edge
13273 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013274 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013275 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013276 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013277 }
13278 }
13279
Chris Lattner74381062009-08-30 07:44:24 +000013280 // Now that we have an instruction, try combining it to simplify it.
13281 Builder->SetInsertPoint(I->getParent(), I);
13282
Reid Spencera9b81012007-03-26 17:44:01 +000013283#ifndef NDEBUG
13284 std::string OrigI;
13285#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013286 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013287 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13288
Chris Lattner90ac28c2002-08-02 19:29:35 +000013289 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013290 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013291 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013292 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013293 DEBUG(errs() << "IC: Old = " << *I << '\n'
13294 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013295
Chris Lattnerf523d062004-06-09 05:08:07 +000013296 // Everything uses the new instruction now.
13297 I->replaceAllUsesWith(Result);
13298
13299 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013300 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013301 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013302
Chris Lattner6934a042007-02-11 01:23:03 +000013303 // Move the name to the new instruction first.
13304 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013305
13306 // Insert the new instruction into the basic block...
13307 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013308 BasicBlock::iterator InsertPos = I;
13309
13310 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13311 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13312 ++InsertPos;
13313
13314 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013315
Chris Lattner7a1e9242009-08-30 06:13:40 +000013316 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013317 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013318#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013319 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13320 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013321#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013322
Chris Lattner90ac28c2002-08-02 19:29:35 +000013323 // If the instruction was modified, it's possible that it is now dead.
13324 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013325 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013326 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013327 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013328 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013329 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013330 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013331 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013332 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013333 }
13334 }
13335
Chris Lattner873ff012009-08-30 05:55:36 +000013336 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013337 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013338}
13339
Chris Lattnerec9c3582007-03-03 02:04:50 +000013340
13341bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013342 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013343 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013344 TD = getAnalysisIfAvailable<TargetData>();
13345
Chris Lattner74381062009-08-30 07:44:24 +000013346
13347 /// Builder - This is an IRBuilder that automatically inserts new
13348 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013349 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013350 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013351 InstCombineIRInserter(Worklist));
13352 Builder = &TheBuilder;
13353
Chris Lattnerec9c3582007-03-03 02:04:50 +000013354 bool EverMadeChange = false;
13355
13356 // Iterate while there is work to do.
13357 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013358 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013359 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013360
13361 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013362 return EverMadeChange;
13363}
13364
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013365FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013366 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013367}