1*9880d681SAndroid Build Coastguard Worker //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // InstructionCombining - Combine instructions to form fewer, simple
11*9880d681SAndroid Build Coastguard Worker // instructions. This pass does not modify the CFG. This pass is where
12*9880d681SAndroid Build Coastguard Worker // algebraic simplification happens.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker // This pass combines things like:
15*9880d681SAndroid Build Coastguard Worker // %Y = add i32 %X, 1
16*9880d681SAndroid Build Coastguard Worker // %Z = add i32 %Y, 1
17*9880d681SAndroid Build Coastguard Worker // into:
18*9880d681SAndroid Build Coastguard Worker // %Z = add i32 %X, 2
19*9880d681SAndroid Build Coastguard Worker //
20*9880d681SAndroid Build Coastguard Worker // This is a simple worklist driven algorithm.
21*9880d681SAndroid Build Coastguard Worker //
22*9880d681SAndroid Build Coastguard Worker // This pass guarantees that the following canonicalizations are performed on
23*9880d681SAndroid Build Coastguard Worker // the program:
24*9880d681SAndroid Build Coastguard Worker // 1. If a binary operator has a constant operand, it is moved to the RHS
25*9880d681SAndroid Build Coastguard Worker // 2. Bitwise operators with constant operands are always grouped so that
26*9880d681SAndroid Build Coastguard Worker // shifts are performed first, then or's, then and's, then xor's.
27*9880d681SAndroid Build Coastguard Worker // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28*9880d681SAndroid Build Coastguard Worker // 4. All cmp instructions on boolean values are replaced with logical ops
29*9880d681SAndroid Build Coastguard Worker // 5. add X, X is represented as (X*2) => (X << 1)
30*9880d681SAndroid Build Coastguard Worker // 6. Multiplies with a power-of-two constant argument are transformed into
31*9880d681SAndroid Build Coastguard Worker // shifts.
32*9880d681SAndroid Build Coastguard Worker // ... etc.
33*9880d681SAndroid Build Coastguard Worker //
34*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
35*9880d681SAndroid Build Coastguard Worker
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/InstCombine/InstCombine.h"
37*9880d681SAndroid Build Coastguard Worker #include "InstCombineInternal.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm-c/Initialization.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringSwitch.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BasicAliasAnalysis.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CFG.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/EHPersonalities.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
56*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
57*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GetElementPtrTypeIterator.h"
58*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
59*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
60*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ValueHandle.h"
61*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
62*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
63*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
64*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
65*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
66*9880d681SAndroid Build Coastguard Worker #include <algorithm>
67*9880d681SAndroid Build Coastguard Worker #include <climits>
68*9880d681SAndroid Build Coastguard Worker using namespace llvm;
69*9880d681SAndroid Build Coastguard Worker using namespace llvm::PatternMatch;
70*9880d681SAndroid Build Coastguard Worker
71*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "instcombine"
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker STATISTIC(NumCombined , "Number of insts combined");
74*9880d681SAndroid Build Coastguard Worker STATISTIC(NumConstProp, "Number of constant folds");
75*9880d681SAndroid Build Coastguard Worker STATISTIC(NumDeadInst , "Number of dead inst eliminated");
76*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSunkInst , "Number of instructions sunk");
77*9880d681SAndroid Build Coastguard Worker STATISTIC(NumExpand, "Number of expansions");
78*9880d681SAndroid Build Coastguard Worker STATISTIC(NumFactor , "Number of factorizations");
79*9880d681SAndroid Build Coastguard Worker STATISTIC(NumReassoc , "Number of reassociations");
80*9880d681SAndroid Build Coastguard Worker
81*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
82*9880d681SAndroid Build Coastguard Worker EnableExpensiveCombines("expensive-combines",
83*9880d681SAndroid Build Coastguard Worker cl::desc("Enable expensive instruction combines"));
84*9880d681SAndroid Build Coastguard Worker
EmitGEPOffset(User * GEP)85*9880d681SAndroid Build Coastguard Worker Value *InstCombiner::EmitGEPOffset(User *GEP) {
86*9880d681SAndroid Build Coastguard Worker return llvm::EmitGEPOffset(Builder, DL, GEP);
87*9880d681SAndroid Build Coastguard Worker }
88*9880d681SAndroid Build Coastguard Worker
89*9880d681SAndroid Build Coastguard Worker /// Return true if it is desirable to convert an integer computation from a
90*9880d681SAndroid Build Coastguard Worker /// given bit width to a new bit width.
91*9880d681SAndroid Build Coastguard Worker /// We don't want to convert from a legal to an illegal type for example or from
92*9880d681SAndroid Build Coastguard Worker /// a smaller to a larger illegal type.
ShouldChangeType(unsigned FromWidth,unsigned ToWidth) const93*9880d681SAndroid Build Coastguard Worker bool InstCombiner::ShouldChangeType(unsigned FromWidth,
94*9880d681SAndroid Build Coastguard Worker unsigned ToWidth) const {
95*9880d681SAndroid Build Coastguard Worker bool FromLegal = DL.isLegalInteger(FromWidth);
96*9880d681SAndroid Build Coastguard Worker bool ToLegal = DL.isLegalInteger(ToWidth);
97*9880d681SAndroid Build Coastguard Worker
98*9880d681SAndroid Build Coastguard Worker // If this is a legal integer from type, and the result would be an illegal
99*9880d681SAndroid Build Coastguard Worker // type, don't do the transformation.
100*9880d681SAndroid Build Coastguard Worker if (FromLegal && !ToLegal)
101*9880d681SAndroid Build Coastguard Worker return false;
102*9880d681SAndroid Build Coastguard Worker
103*9880d681SAndroid Build Coastguard Worker // Otherwise, if both are illegal, do not increase the size of the result. We
104*9880d681SAndroid Build Coastguard Worker // do allow things like i160 -> i64, but not i64 -> i160.
105*9880d681SAndroid Build Coastguard Worker if (!FromLegal && !ToLegal && ToWidth > FromWidth)
106*9880d681SAndroid Build Coastguard Worker return false;
107*9880d681SAndroid Build Coastguard Worker
108*9880d681SAndroid Build Coastguard Worker return true;
109*9880d681SAndroid Build Coastguard Worker }
110*9880d681SAndroid Build Coastguard Worker
111*9880d681SAndroid Build Coastguard Worker /// Return true if it is desirable to convert a computation from 'From' to 'To'.
112*9880d681SAndroid Build Coastguard Worker /// We don't want to convert from a legal to an illegal type for example or from
113*9880d681SAndroid Build Coastguard Worker /// a smaller to a larger illegal type.
ShouldChangeType(Type * From,Type * To) const114*9880d681SAndroid Build Coastguard Worker bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
115*9880d681SAndroid Build Coastguard Worker assert(From->isIntegerTy() && To->isIntegerTy());
116*9880d681SAndroid Build Coastguard Worker
117*9880d681SAndroid Build Coastguard Worker unsigned FromWidth = From->getPrimitiveSizeInBits();
118*9880d681SAndroid Build Coastguard Worker unsigned ToWidth = To->getPrimitiveSizeInBits();
119*9880d681SAndroid Build Coastguard Worker return ShouldChangeType(FromWidth, ToWidth);
120*9880d681SAndroid Build Coastguard Worker }
121*9880d681SAndroid Build Coastguard Worker
122*9880d681SAndroid Build Coastguard Worker // Return true, if No Signed Wrap should be maintained for I.
123*9880d681SAndroid Build Coastguard Worker // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
124*9880d681SAndroid Build Coastguard Worker // where both B and C should be ConstantInts, results in a constant that does
125*9880d681SAndroid Build Coastguard Worker // not overflow. This function only handles the Add and Sub opcodes. For
126*9880d681SAndroid Build Coastguard Worker // all other opcodes, the function conservatively returns false.
MaintainNoSignedWrap(BinaryOperator & I,Value * B,Value * C)127*9880d681SAndroid Build Coastguard Worker static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
128*9880d681SAndroid Build Coastguard Worker OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
129*9880d681SAndroid Build Coastguard Worker if (!OBO || !OBO->hasNoSignedWrap())
130*9880d681SAndroid Build Coastguard Worker return false;
131*9880d681SAndroid Build Coastguard Worker
132*9880d681SAndroid Build Coastguard Worker // We reason about Add and Sub Only.
133*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps Opcode = I.getOpcode();
134*9880d681SAndroid Build Coastguard Worker if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
135*9880d681SAndroid Build Coastguard Worker return false;
136*9880d681SAndroid Build Coastguard Worker
137*9880d681SAndroid Build Coastguard Worker const APInt *BVal, *CVal;
138*9880d681SAndroid Build Coastguard Worker if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
139*9880d681SAndroid Build Coastguard Worker return false;
140*9880d681SAndroid Build Coastguard Worker
141*9880d681SAndroid Build Coastguard Worker bool Overflow = false;
142*9880d681SAndroid Build Coastguard Worker if (Opcode == Instruction::Add)
143*9880d681SAndroid Build Coastguard Worker BVal->sadd_ov(*CVal, Overflow);
144*9880d681SAndroid Build Coastguard Worker else
145*9880d681SAndroid Build Coastguard Worker BVal->ssub_ov(*CVal, Overflow);
146*9880d681SAndroid Build Coastguard Worker
147*9880d681SAndroid Build Coastguard Worker return !Overflow;
148*9880d681SAndroid Build Coastguard Worker }
149*9880d681SAndroid Build Coastguard Worker
150*9880d681SAndroid Build Coastguard Worker /// Conservatively clears subclassOptionalData after a reassociation or
151*9880d681SAndroid Build Coastguard Worker /// commutation. We preserve fast-math flags when applicable as they can be
152*9880d681SAndroid Build Coastguard Worker /// preserved.
ClearSubclassDataAfterReassociation(BinaryOperator & I)153*9880d681SAndroid Build Coastguard Worker static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
154*9880d681SAndroid Build Coastguard Worker FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
155*9880d681SAndroid Build Coastguard Worker if (!FPMO) {
156*9880d681SAndroid Build Coastguard Worker I.clearSubclassOptionalData();
157*9880d681SAndroid Build Coastguard Worker return;
158*9880d681SAndroid Build Coastguard Worker }
159*9880d681SAndroid Build Coastguard Worker
160*9880d681SAndroid Build Coastguard Worker FastMathFlags FMF = I.getFastMathFlags();
161*9880d681SAndroid Build Coastguard Worker I.clearSubclassOptionalData();
162*9880d681SAndroid Build Coastguard Worker I.setFastMathFlags(FMF);
163*9880d681SAndroid Build Coastguard Worker }
164*9880d681SAndroid Build Coastguard Worker
165*9880d681SAndroid Build Coastguard Worker /// This performs a few simplifications for operators that are associative or
166*9880d681SAndroid Build Coastguard Worker /// commutative:
167*9880d681SAndroid Build Coastguard Worker ///
168*9880d681SAndroid Build Coastguard Worker /// Commutative operators:
169*9880d681SAndroid Build Coastguard Worker ///
170*9880d681SAndroid Build Coastguard Worker /// 1. Order operands such that they are listed from right (least complex) to
171*9880d681SAndroid Build Coastguard Worker /// left (most complex). This puts constants before unary operators before
172*9880d681SAndroid Build Coastguard Worker /// binary operators.
173*9880d681SAndroid Build Coastguard Worker ///
174*9880d681SAndroid Build Coastguard Worker /// Associative operators:
175*9880d681SAndroid Build Coastguard Worker ///
176*9880d681SAndroid Build Coastguard Worker /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
177*9880d681SAndroid Build Coastguard Worker /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
178*9880d681SAndroid Build Coastguard Worker ///
179*9880d681SAndroid Build Coastguard Worker /// Associative and commutative operators:
180*9880d681SAndroid Build Coastguard Worker ///
181*9880d681SAndroid Build Coastguard Worker /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
182*9880d681SAndroid Build Coastguard Worker /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
183*9880d681SAndroid Build Coastguard Worker /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
184*9880d681SAndroid Build Coastguard Worker /// if C1 and C2 are constants.
SimplifyAssociativeOrCommutative(BinaryOperator & I)185*9880d681SAndroid Build Coastguard Worker bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
186*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps Opcode = I.getOpcode();
187*9880d681SAndroid Build Coastguard Worker bool Changed = false;
188*9880d681SAndroid Build Coastguard Worker
189*9880d681SAndroid Build Coastguard Worker do {
190*9880d681SAndroid Build Coastguard Worker // Order operands such that they are listed from right (least complex) to
191*9880d681SAndroid Build Coastguard Worker // left (most complex). This puts constants before unary operators before
192*9880d681SAndroid Build Coastguard Worker // binary operators.
193*9880d681SAndroid Build Coastguard Worker if (I.isCommutative() && getComplexity(I.getOperand(0)) <
194*9880d681SAndroid Build Coastguard Worker getComplexity(I.getOperand(1)))
195*9880d681SAndroid Build Coastguard Worker Changed = !I.swapOperands();
196*9880d681SAndroid Build Coastguard Worker
197*9880d681SAndroid Build Coastguard Worker BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
198*9880d681SAndroid Build Coastguard Worker BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
199*9880d681SAndroid Build Coastguard Worker
200*9880d681SAndroid Build Coastguard Worker if (I.isAssociative()) {
201*9880d681SAndroid Build Coastguard Worker // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
202*9880d681SAndroid Build Coastguard Worker if (Op0 && Op0->getOpcode() == Opcode) {
203*9880d681SAndroid Build Coastguard Worker Value *A = Op0->getOperand(0);
204*9880d681SAndroid Build Coastguard Worker Value *B = Op0->getOperand(1);
205*9880d681SAndroid Build Coastguard Worker Value *C = I.getOperand(1);
206*9880d681SAndroid Build Coastguard Worker
207*9880d681SAndroid Build Coastguard Worker // Does "B op C" simplify?
208*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
209*9880d681SAndroid Build Coastguard Worker // It simplifies to V. Form "A op V".
210*9880d681SAndroid Build Coastguard Worker I.setOperand(0, A);
211*9880d681SAndroid Build Coastguard Worker I.setOperand(1, V);
212*9880d681SAndroid Build Coastguard Worker // Conservatively clear the optional flags, since they may not be
213*9880d681SAndroid Build Coastguard Worker // preserved by the reassociation.
214*9880d681SAndroid Build Coastguard Worker if (MaintainNoSignedWrap(I, B, C) &&
215*9880d681SAndroid Build Coastguard Worker (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
216*9880d681SAndroid Build Coastguard Worker // Note: this is only valid because SimplifyBinOp doesn't look at
217*9880d681SAndroid Build Coastguard Worker // the operands to Op0.
218*9880d681SAndroid Build Coastguard Worker I.clearSubclassOptionalData();
219*9880d681SAndroid Build Coastguard Worker I.setHasNoSignedWrap(true);
220*9880d681SAndroid Build Coastguard Worker } else {
221*9880d681SAndroid Build Coastguard Worker ClearSubclassDataAfterReassociation(I);
222*9880d681SAndroid Build Coastguard Worker }
223*9880d681SAndroid Build Coastguard Worker
224*9880d681SAndroid Build Coastguard Worker Changed = true;
225*9880d681SAndroid Build Coastguard Worker ++NumReassoc;
226*9880d681SAndroid Build Coastguard Worker continue;
227*9880d681SAndroid Build Coastguard Worker }
228*9880d681SAndroid Build Coastguard Worker }
229*9880d681SAndroid Build Coastguard Worker
230*9880d681SAndroid Build Coastguard Worker // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
231*9880d681SAndroid Build Coastguard Worker if (Op1 && Op1->getOpcode() == Opcode) {
232*9880d681SAndroid Build Coastguard Worker Value *A = I.getOperand(0);
233*9880d681SAndroid Build Coastguard Worker Value *B = Op1->getOperand(0);
234*9880d681SAndroid Build Coastguard Worker Value *C = Op1->getOperand(1);
235*9880d681SAndroid Build Coastguard Worker
236*9880d681SAndroid Build Coastguard Worker // Does "A op B" simplify?
237*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
238*9880d681SAndroid Build Coastguard Worker // It simplifies to V. Form "V op C".
239*9880d681SAndroid Build Coastguard Worker I.setOperand(0, V);
240*9880d681SAndroid Build Coastguard Worker I.setOperand(1, C);
241*9880d681SAndroid Build Coastguard Worker // Conservatively clear the optional flags, since they may not be
242*9880d681SAndroid Build Coastguard Worker // preserved by the reassociation.
243*9880d681SAndroid Build Coastguard Worker ClearSubclassDataAfterReassociation(I);
244*9880d681SAndroid Build Coastguard Worker Changed = true;
245*9880d681SAndroid Build Coastguard Worker ++NumReassoc;
246*9880d681SAndroid Build Coastguard Worker continue;
247*9880d681SAndroid Build Coastguard Worker }
248*9880d681SAndroid Build Coastguard Worker }
249*9880d681SAndroid Build Coastguard Worker }
250*9880d681SAndroid Build Coastguard Worker
251*9880d681SAndroid Build Coastguard Worker if (I.isAssociative() && I.isCommutative()) {
252*9880d681SAndroid Build Coastguard Worker // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
253*9880d681SAndroid Build Coastguard Worker if (Op0 && Op0->getOpcode() == Opcode) {
254*9880d681SAndroid Build Coastguard Worker Value *A = Op0->getOperand(0);
255*9880d681SAndroid Build Coastguard Worker Value *B = Op0->getOperand(1);
256*9880d681SAndroid Build Coastguard Worker Value *C = I.getOperand(1);
257*9880d681SAndroid Build Coastguard Worker
258*9880d681SAndroid Build Coastguard Worker // Does "C op A" simplify?
259*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
260*9880d681SAndroid Build Coastguard Worker // It simplifies to V. Form "V op B".
261*9880d681SAndroid Build Coastguard Worker I.setOperand(0, V);
262*9880d681SAndroid Build Coastguard Worker I.setOperand(1, B);
263*9880d681SAndroid Build Coastguard Worker // Conservatively clear the optional flags, since they may not be
264*9880d681SAndroid Build Coastguard Worker // preserved by the reassociation.
265*9880d681SAndroid Build Coastguard Worker ClearSubclassDataAfterReassociation(I);
266*9880d681SAndroid Build Coastguard Worker Changed = true;
267*9880d681SAndroid Build Coastguard Worker ++NumReassoc;
268*9880d681SAndroid Build Coastguard Worker continue;
269*9880d681SAndroid Build Coastguard Worker }
270*9880d681SAndroid Build Coastguard Worker }
271*9880d681SAndroid Build Coastguard Worker
272*9880d681SAndroid Build Coastguard Worker // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
273*9880d681SAndroid Build Coastguard Worker if (Op1 && Op1->getOpcode() == Opcode) {
274*9880d681SAndroid Build Coastguard Worker Value *A = I.getOperand(0);
275*9880d681SAndroid Build Coastguard Worker Value *B = Op1->getOperand(0);
276*9880d681SAndroid Build Coastguard Worker Value *C = Op1->getOperand(1);
277*9880d681SAndroid Build Coastguard Worker
278*9880d681SAndroid Build Coastguard Worker // Does "C op A" simplify?
279*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
280*9880d681SAndroid Build Coastguard Worker // It simplifies to V. Form "B op V".
281*9880d681SAndroid Build Coastguard Worker I.setOperand(0, B);
282*9880d681SAndroid Build Coastguard Worker I.setOperand(1, V);
283*9880d681SAndroid Build Coastguard Worker // Conservatively clear the optional flags, since they may not be
284*9880d681SAndroid Build Coastguard Worker // preserved by the reassociation.
285*9880d681SAndroid Build Coastguard Worker ClearSubclassDataAfterReassociation(I);
286*9880d681SAndroid Build Coastguard Worker Changed = true;
287*9880d681SAndroid Build Coastguard Worker ++NumReassoc;
288*9880d681SAndroid Build Coastguard Worker continue;
289*9880d681SAndroid Build Coastguard Worker }
290*9880d681SAndroid Build Coastguard Worker }
291*9880d681SAndroid Build Coastguard Worker
292*9880d681SAndroid Build Coastguard Worker // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
293*9880d681SAndroid Build Coastguard Worker // if C1 and C2 are constants.
294*9880d681SAndroid Build Coastguard Worker if (Op0 && Op1 &&
295*9880d681SAndroid Build Coastguard Worker Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
296*9880d681SAndroid Build Coastguard Worker isa<Constant>(Op0->getOperand(1)) &&
297*9880d681SAndroid Build Coastguard Worker isa<Constant>(Op1->getOperand(1)) &&
298*9880d681SAndroid Build Coastguard Worker Op0->hasOneUse() && Op1->hasOneUse()) {
299*9880d681SAndroid Build Coastguard Worker Value *A = Op0->getOperand(0);
300*9880d681SAndroid Build Coastguard Worker Constant *C1 = cast<Constant>(Op0->getOperand(1));
301*9880d681SAndroid Build Coastguard Worker Value *B = Op1->getOperand(0);
302*9880d681SAndroid Build Coastguard Worker Constant *C2 = cast<Constant>(Op1->getOperand(1));
303*9880d681SAndroid Build Coastguard Worker
304*9880d681SAndroid Build Coastguard Worker Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
305*9880d681SAndroid Build Coastguard Worker BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
306*9880d681SAndroid Build Coastguard Worker if (isa<FPMathOperator>(New)) {
307*9880d681SAndroid Build Coastguard Worker FastMathFlags Flags = I.getFastMathFlags();
308*9880d681SAndroid Build Coastguard Worker Flags &= Op0->getFastMathFlags();
309*9880d681SAndroid Build Coastguard Worker Flags &= Op1->getFastMathFlags();
310*9880d681SAndroid Build Coastguard Worker New->setFastMathFlags(Flags);
311*9880d681SAndroid Build Coastguard Worker }
312*9880d681SAndroid Build Coastguard Worker InsertNewInstWith(New, I);
313*9880d681SAndroid Build Coastguard Worker New->takeName(Op1);
314*9880d681SAndroid Build Coastguard Worker I.setOperand(0, New);
315*9880d681SAndroid Build Coastguard Worker I.setOperand(1, Folded);
316*9880d681SAndroid Build Coastguard Worker // Conservatively clear the optional flags, since they may not be
317*9880d681SAndroid Build Coastguard Worker // preserved by the reassociation.
318*9880d681SAndroid Build Coastguard Worker ClearSubclassDataAfterReassociation(I);
319*9880d681SAndroid Build Coastguard Worker
320*9880d681SAndroid Build Coastguard Worker Changed = true;
321*9880d681SAndroid Build Coastguard Worker continue;
322*9880d681SAndroid Build Coastguard Worker }
323*9880d681SAndroid Build Coastguard Worker }
324*9880d681SAndroid Build Coastguard Worker
325*9880d681SAndroid Build Coastguard Worker // No further simplifications.
326*9880d681SAndroid Build Coastguard Worker return Changed;
327*9880d681SAndroid Build Coastguard Worker } while (1);
328*9880d681SAndroid Build Coastguard Worker }
329*9880d681SAndroid Build Coastguard Worker
330*9880d681SAndroid Build Coastguard Worker /// Return whether "X LOp (Y ROp Z)" is always equal to
331*9880d681SAndroid Build Coastguard Worker /// "(X LOp Y) ROp (X LOp Z)".
LeftDistributesOverRight(Instruction::BinaryOps LOp,Instruction::BinaryOps ROp)332*9880d681SAndroid Build Coastguard Worker static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
333*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps ROp) {
334*9880d681SAndroid Build Coastguard Worker switch (LOp) {
335*9880d681SAndroid Build Coastguard Worker default:
336*9880d681SAndroid Build Coastguard Worker return false;
337*9880d681SAndroid Build Coastguard Worker
338*9880d681SAndroid Build Coastguard Worker case Instruction::And:
339*9880d681SAndroid Build Coastguard Worker // And distributes over Or and Xor.
340*9880d681SAndroid Build Coastguard Worker switch (ROp) {
341*9880d681SAndroid Build Coastguard Worker default:
342*9880d681SAndroid Build Coastguard Worker return false;
343*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
344*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
345*9880d681SAndroid Build Coastguard Worker return true;
346*9880d681SAndroid Build Coastguard Worker }
347*9880d681SAndroid Build Coastguard Worker
348*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
349*9880d681SAndroid Build Coastguard Worker // Multiplication distributes over addition and subtraction.
350*9880d681SAndroid Build Coastguard Worker switch (ROp) {
351*9880d681SAndroid Build Coastguard Worker default:
352*9880d681SAndroid Build Coastguard Worker return false;
353*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
354*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
355*9880d681SAndroid Build Coastguard Worker return true;
356*9880d681SAndroid Build Coastguard Worker }
357*9880d681SAndroid Build Coastguard Worker
358*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
359*9880d681SAndroid Build Coastguard Worker // Or distributes over And.
360*9880d681SAndroid Build Coastguard Worker switch (ROp) {
361*9880d681SAndroid Build Coastguard Worker default:
362*9880d681SAndroid Build Coastguard Worker return false;
363*9880d681SAndroid Build Coastguard Worker case Instruction::And:
364*9880d681SAndroid Build Coastguard Worker return true;
365*9880d681SAndroid Build Coastguard Worker }
366*9880d681SAndroid Build Coastguard Worker }
367*9880d681SAndroid Build Coastguard Worker }
368*9880d681SAndroid Build Coastguard Worker
369*9880d681SAndroid Build Coastguard Worker /// Return whether "(X LOp Y) ROp Z" is always equal to
370*9880d681SAndroid Build Coastguard Worker /// "(X ROp Z) LOp (Y ROp Z)".
RightDistributesOverLeft(Instruction::BinaryOps LOp,Instruction::BinaryOps ROp)371*9880d681SAndroid Build Coastguard Worker static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
372*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps ROp) {
373*9880d681SAndroid Build Coastguard Worker if (Instruction::isCommutative(ROp))
374*9880d681SAndroid Build Coastguard Worker return LeftDistributesOverRight(ROp, LOp);
375*9880d681SAndroid Build Coastguard Worker
376*9880d681SAndroid Build Coastguard Worker switch (LOp) {
377*9880d681SAndroid Build Coastguard Worker default:
378*9880d681SAndroid Build Coastguard Worker return false;
379*9880d681SAndroid Build Coastguard Worker // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
380*9880d681SAndroid Build Coastguard Worker // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
381*9880d681SAndroid Build Coastguard Worker // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
382*9880d681SAndroid Build Coastguard Worker case Instruction::And:
383*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
384*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
385*9880d681SAndroid Build Coastguard Worker switch (ROp) {
386*9880d681SAndroid Build Coastguard Worker default:
387*9880d681SAndroid Build Coastguard Worker return false;
388*9880d681SAndroid Build Coastguard Worker case Instruction::Shl:
389*9880d681SAndroid Build Coastguard Worker case Instruction::LShr:
390*9880d681SAndroid Build Coastguard Worker case Instruction::AShr:
391*9880d681SAndroid Build Coastguard Worker return true;
392*9880d681SAndroid Build Coastguard Worker }
393*9880d681SAndroid Build Coastguard Worker }
394*9880d681SAndroid Build Coastguard Worker // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
395*9880d681SAndroid Build Coastguard Worker // but this requires knowing that the addition does not overflow and other
396*9880d681SAndroid Build Coastguard Worker // such subtleties.
397*9880d681SAndroid Build Coastguard Worker return false;
398*9880d681SAndroid Build Coastguard Worker }
399*9880d681SAndroid Build Coastguard Worker
400*9880d681SAndroid Build Coastguard Worker /// This function returns identity value for given opcode, which can be used to
401*9880d681SAndroid Build Coastguard Worker /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
getIdentityValue(Instruction::BinaryOps OpCode,Value * V)402*9880d681SAndroid Build Coastguard Worker static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
403*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(V))
404*9880d681SAndroid Build Coastguard Worker return nullptr;
405*9880d681SAndroid Build Coastguard Worker
406*9880d681SAndroid Build Coastguard Worker if (OpCode == Instruction::Mul)
407*9880d681SAndroid Build Coastguard Worker return ConstantInt::get(V->getType(), 1);
408*9880d681SAndroid Build Coastguard Worker
409*9880d681SAndroid Build Coastguard Worker // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
410*9880d681SAndroid Build Coastguard Worker
411*9880d681SAndroid Build Coastguard Worker return nullptr;
412*9880d681SAndroid Build Coastguard Worker }
413*9880d681SAndroid Build Coastguard Worker
414*9880d681SAndroid Build Coastguard Worker /// This function factors binary ops which can be combined using distributive
415*9880d681SAndroid Build Coastguard Worker /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
416*9880d681SAndroid Build Coastguard Worker /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
417*9880d681SAndroid Build Coastguard Worker /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
418*9880d681SAndroid Build Coastguard Worker /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
419*9880d681SAndroid Build Coastguard Worker /// RHS to 4.
420*9880d681SAndroid Build Coastguard Worker static Instruction::BinaryOps
getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,BinaryOperator * Op,Value * & LHS,Value * & RHS)421*9880d681SAndroid Build Coastguard Worker getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
422*9880d681SAndroid Build Coastguard Worker BinaryOperator *Op, Value *&LHS, Value *&RHS) {
423*9880d681SAndroid Build Coastguard Worker if (!Op)
424*9880d681SAndroid Build Coastguard Worker return Instruction::BinaryOpsEnd;
425*9880d681SAndroid Build Coastguard Worker
426*9880d681SAndroid Build Coastguard Worker LHS = Op->getOperand(0);
427*9880d681SAndroid Build Coastguard Worker RHS = Op->getOperand(1);
428*9880d681SAndroid Build Coastguard Worker
429*9880d681SAndroid Build Coastguard Worker switch (TopLevelOpcode) {
430*9880d681SAndroid Build Coastguard Worker default:
431*9880d681SAndroid Build Coastguard Worker return Op->getOpcode();
432*9880d681SAndroid Build Coastguard Worker
433*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
434*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
435*9880d681SAndroid Build Coastguard Worker if (Op->getOpcode() == Instruction::Shl) {
436*9880d681SAndroid Build Coastguard Worker if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
437*9880d681SAndroid Build Coastguard Worker // The multiplier is really 1 << CST.
438*9880d681SAndroid Build Coastguard Worker RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
439*9880d681SAndroid Build Coastguard Worker return Instruction::Mul;
440*9880d681SAndroid Build Coastguard Worker }
441*9880d681SAndroid Build Coastguard Worker }
442*9880d681SAndroid Build Coastguard Worker return Op->getOpcode();
443*9880d681SAndroid Build Coastguard Worker }
444*9880d681SAndroid Build Coastguard Worker
445*9880d681SAndroid Build Coastguard Worker // TODO: We can add other conversions e.g. shr => div etc.
446*9880d681SAndroid Build Coastguard Worker }
447*9880d681SAndroid Build Coastguard Worker
448*9880d681SAndroid Build Coastguard Worker /// This tries to simplify binary operations by factorizing out common terms
449*9880d681SAndroid Build Coastguard Worker /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
tryFactorization(InstCombiner::BuilderTy * Builder,const DataLayout & DL,BinaryOperator & I,Instruction::BinaryOps InnerOpcode,Value * A,Value * B,Value * C,Value * D)450*9880d681SAndroid Build Coastguard Worker static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
451*9880d681SAndroid Build Coastguard Worker const DataLayout &DL, BinaryOperator &I,
452*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps InnerOpcode, Value *A,
453*9880d681SAndroid Build Coastguard Worker Value *B, Value *C, Value *D) {
454*9880d681SAndroid Build Coastguard Worker
455*9880d681SAndroid Build Coastguard Worker // If any of A, B, C, D are null, we can not factor I, return early.
456*9880d681SAndroid Build Coastguard Worker // Checking A and C should be enough.
457*9880d681SAndroid Build Coastguard Worker if (!A || !C || !B || !D)
458*9880d681SAndroid Build Coastguard Worker return nullptr;
459*9880d681SAndroid Build Coastguard Worker
460*9880d681SAndroid Build Coastguard Worker Value *V = nullptr;
461*9880d681SAndroid Build Coastguard Worker Value *SimplifiedInst = nullptr;
462*9880d681SAndroid Build Coastguard Worker Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
463*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
464*9880d681SAndroid Build Coastguard Worker
465*9880d681SAndroid Build Coastguard Worker // Does "X op' Y" always equal "Y op' X"?
466*9880d681SAndroid Build Coastguard Worker bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
467*9880d681SAndroid Build Coastguard Worker
468*9880d681SAndroid Build Coastguard Worker // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
469*9880d681SAndroid Build Coastguard Worker if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
470*9880d681SAndroid Build Coastguard Worker // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
471*9880d681SAndroid Build Coastguard Worker // commutative case, "(A op' B) op (C op' A)"?
472*9880d681SAndroid Build Coastguard Worker if (A == C || (InnerCommutative && A == D)) {
473*9880d681SAndroid Build Coastguard Worker if (A != C)
474*9880d681SAndroid Build Coastguard Worker std::swap(C, D);
475*9880d681SAndroid Build Coastguard Worker // Consider forming "A op' (B op D)".
476*9880d681SAndroid Build Coastguard Worker // If "B op D" simplifies then it can be formed with no cost.
477*9880d681SAndroid Build Coastguard Worker V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
478*9880d681SAndroid Build Coastguard Worker // If "B op D" doesn't simplify then only go on if both of the existing
479*9880d681SAndroid Build Coastguard Worker // operations "A op' B" and "C op' D" will be zapped as no longer used.
480*9880d681SAndroid Build Coastguard Worker if (!V && LHS->hasOneUse() && RHS->hasOneUse())
481*9880d681SAndroid Build Coastguard Worker V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
482*9880d681SAndroid Build Coastguard Worker if (V) {
483*9880d681SAndroid Build Coastguard Worker SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
484*9880d681SAndroid Build Coastguard Worker }
485*9880d681SAndroid Build Coastguard Worker }
486*9880d681SAndroid Build Coastguard Worker
487*9880d681SAndroid Build Coastguard Worker // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
488*9880d681SAndroid Build Coastguard Worker if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
489*9880d681SAndroid Build Coastguard Worker // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
490*9880d681SAndroid Build Coastguard Worker // commutative case, "(A op' B) op (B op' D)"?
491*9880d681SAndroid Build Coastguard Worker if (B == D || (InnerCommutative && B == C)) {
492*9880d681SAndroid Build Coastguard Worker if (B != D)
493*9880d681SAndroid Build Coastguard Worker std::swap(C, D);
494*9880d681SAndroid Build Coastguard Worker // Consider forming "(A op C) op' B".
495*9880d681SAndroid Build Coastguard Worker // If "A op C" simplifies then it can be formed with no cost.
496*9880d681SAndroid Build Coastguard Worker V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
497*9880d681SAndroid Build Coastguard Worker
498*9880d681SAndroid Build Coastguard Worker // If "A op C" doesn't simplify then only go on if both of the existing
499*9880d681SAndroid Build Coastguard Worker // operations "A op' B" and "C op' D" will be zapped as no longer used.
500*9880d681SAndroid Build Coastguard Worker if (!V && LHS->hasOneUse() && RHS->hasOneUse())
501*9880d681SAndroid Build Coastguard Worker V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
502*9880d681SAndroid Build Coastguard Worker if (V) {
503*9880d681SAndroid Build Coastguard Worker SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
504*9880d681SAndroid Build Coastguard Worker }
505*9880d681SAndroid Build Coastguard Worker }
506*9880d681SAndroid Build Coastguard Worker
507*9880d681SAndroid Build Coastguard Worker if (SimplifiedInst) {
508*9880d681SAndroid Build Coastguard Worker ++NumFactor;
509*9880d681SAndroid Build Coastguard Worker SimplifiedInst->takeName(&I);
510*9880d681SAndroid Build Coastguard Worker
511*9880d681SAndroid Build Coastguard Worker // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
512*9880d681SAndroid Build Coastguard Worker // TODO: Check for NUW.
513*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
514*9880d681SAndroid Build Coastguard Worker if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
515*9880d681SAndroid Build Coastguard Worker bool HasNSW = false;
516*9880d681SAndroid Build Coastguard Worker if (isa<OverflowingBinaryOperator>(&I))
517*9880d681SAndroid Build Coastguard Worker HasNSW = I.hasNoSignedWrap();
518*9880d681SAndroid Build Coastguard Worker
519*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
520*9880d681SAndroid Build Coastguard Worker if (isa<OverflowingBinaryOperator>(Op0))
521*9880d681SAndroid Build Coastguard Worker HasNSW &= Op0->hasNoSignedWrap();
522*9880d681SAndroid Build Coastguard Worker
523*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
524*9880d681SAndroid Build Coastguard Worker if (isa<OverflowingBinaryOperator>(Op1))
525*9880d681SAndroid Build Coastguard Worker HasNSW &= Op1->hasNoSignedWrap();
526*9880d681SAndroid Build Coastguard Worker
527*9880d681SAndroid Build Coastguard Worker // We can propagate 'nsw' if we know that
528*9880d681SAndroid Build Coastguard Worker // %Y = mul nsw i16 %X, C
529*9880d681SAndroid Build Coastguard Worker // %Z = add nsw i16 %Y, %X
530*9880d681SAndroid Build Coastguard Worker // =>
531*9880d681SAndroid Build Coastguard Worker // %Z = mul nsw i16 %X, C+1
532*9880d681SAndroid Build Coastguard Worker //
533*9880d681SAndroid Build Coastguard Worker // iff C+1 isn't INT_MIN
534*9880d681SAndroid Build Coastguard Worker const APInt *CInt;
535*9880d681SAndroid Build Coastguard Worker if (TopLevelOpcode == Instruction::Add &&
536*9880d681SAndroid Build Coastguard Worker InnerOpcode == Instruction::Mul)
537*9880d681SAndroid Build Coastguard Worker if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
538*9880d681SAndroid Build Coastguard Worker BO->setHasNoSignedWrap(HasNSW);
539*9880d681SAndroid Build Coastguard Worker }
540*9880d681SAndroid Build Coastguard Worker }
541*9880d681SAndroid Build Coastguard Worker }
542*9880d681SAndroid Build Coastguard Worker return SimplifiedInst;
543*9880d681SAndroid Build Coastguard Worker }
544*9880d681SAndroid Build Coastguard Worker
545*9880d681SAndroid Build Coastguard Worker /// This tries to simplify binary operations which some other binary operation
546*9880d681SAndroid Build Coastguard Worker /// distributes over either by factorizing out common terms
547*9880d681SAndroid Build Coastguard Worker /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
548*9880d681SAndroid Build Coastguard Worker /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
549*9880d681SAndroid Build Coastguard Worker /// Returns the simplified value, or null if it didn't simplify.
SimplifyUsingDistributiveLaws(BinaryOperator & I)550*9880d681SAndroid Build Coastguard Worker Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
551*9880d681SAndroid Build Coastguard Worker Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
552*9880d681SAndroid Build Coastguard Worker BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
553*9880d681SAndroid Build Coastguard Worker BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
554*9880d681SAndroid Build Coastguard Worker
555*9880d681SAndroid Build Coastguard Worker // Factorization.
556*9880d681SAndroid Build Coastguard Worker Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
557*9880d681SAndroid Build Coastguard Worker auto TopLevelOpcode = I.getOpcode();
558*9880d681SAndroid Build Coastguard Worker auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
559*9880d681SAndroid Build Coastguard Worker auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
560*9880d681SAndroid Build Coastguard Worker
561*9880d681SAndroid Build Coastguard Worker // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
562*9880d681SAndroid Build Coastguard Worker // a common term.
563*9880d681SAndroid Build Coastguard Worker if (LHSOpcode == RHSOpcode) {
564*9880d681SAndroid Build Coastguard Worker if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
565*9880d681SAndroid Build Coastguard Worker return V;
566*9880d681SAndroid Build Coastguard Worker }
567*9880d681SAndroid Build Coastguard Worker
568*9880d681SAndroid Build Coastguard Worker // The instruction has the form "(A op' B) op (C)". Try to factorize common
569*9880d681SAndroid Build Coastguard Worker // term.
570*9880d681SAndroid Build Coastguard Worker if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
571*9880d681SAndroid Build Coastguard Worker getIdentityValue(LHSOpcode, RHS)))
572*9880d681SAndroid Build Coastguard Worker return V;
573*9880d681SAndroid Build Coastguard Worker
574*9880d681SAndroid Build Coastguard Worker // The instruction has the form "(B) op (C op' D)". Try to factorize common
575*9880d681SAndroid Build Coastguard Worker // term.
576*9880d681SAndroid Build Coastguard Worker if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
577*9880d681SAndroid Build Coastguard Worker getIdentityValue(RHSOpcode, LHS), C, D))
578*9880d681SAndroid Build Coastguard Worker return V;
579*9880d681SAndroid Build Coastguard Worker
580*9880d681SAndroid Build Coastguard Worker // Expansion.
581*9880d681SAndroid Build Coastguard Worker if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
582*9880d681SAndroid Build Coastguard Worker // The instruction has the form "(A op' B) op C". See if expanding it out
583*9880d681SAndroid Build Coastguard Worker // to "(A op C) op' (B op C)" results in simplifications.
584*9880d681SAndroid Build Coastguard Worker Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
585*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
586*9880d681SAndroid Build Coastguard Worker
587*9880d681SAndroid Build Coastguard Worker // Do "A op C" and "B op C" both simplify?
588*9880d681SAndroid Build Coastguard Worker if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
589*9880d681SAndroid Build Coastguard Worker if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
590*9880d681SAndroid Build Coastguard Worker // They do! Return "L op' R".
591*9880d681SAndroid Build Coastguard Worker ++NumExpand;
592*9880d681SAndroid Build Coastguard Worker // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
593*9880d681SAndroid Build Coastguard Worker if ((L == A && R == B) ||
594*9880d681SAndroid Build Coastguard Worker (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
595*9880d681SAndroid Build Coastguard Worker return Op0;
596*9880d681SAndroid Build Coastguard Worker // Otherwise return "L op' R" if it simplifies.
597*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
598*9880d681SAndroid Build Coastguard Worker return V;
599*9880d681SAndroid Build Coastguard Worker // Otherwise, create a new instruction.
600*9880d681SAndroid Build Coastguard Worker C = Builder->CreateBinOp(InnerOpcode, L, R);
601*9880d681SAndroid Build Coastguard Worker C->takeName(&I);
602*9880d681SAndroid Build Coastguard Worker return C;
603*9880d681SAndroid Build Coastguard Worker }
604*9880d681SAndroid Build Coastguard Worker }
605*9880d681SAndroid Build Coastguard Worker
606*9880d681SAndroid Build Coastguard Worker if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
607*9880d681SAndroid Build Coastguard Worker // The instruction has the form "A op (B op' C)". See if expanding it out
608*9880d681SAndroid Build Coastguard Worker // to "(A op B) op' (A op C)" results in simplifications.
609*9880d681SAndroid Build Coastguard Worker Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
610*9880d681SAndroid Build Coastguard Worker Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
611*9880d681SAndroid Build Coastguard Worker
612*9880d681SAndroid Build Coastguard Worker // Do "A op B" and "A op C" both simplify?
613*9880d681SAndroid Build Coastguard Worker if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
614*9880d681SAndroid Build Coastguard Worker if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
615*9880d681SAndroid Build Coastguard Worker // They do! Return "L op' R".
616*9880d681SAndroid Build Coastguard Worker ++NumExpand;
617*9880d681SAndroid Build Coastguard Worker // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
618*9880d681SAndroid Build Coastguard Worker if ((L == B && R == C) ||
619*9880d681SAndroid Build Coastguard Worker (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
620*9880d681SAndroid Build Coastguard Worker return Op1;
621*9880d681SAndroid Build Coastguard Worker // Otherwise return "L op' R" if it simplifies.
622*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
623*9880d681SAndroid Build Coastguard Worker return V;
624*9880d681SAndroid Build Coastguard Worker // Otherwise, create a new instruction.
625*9880d681SAndroid Build Coastguard Worker A = Builder->CreateBinOp(InnerOpcode, L, R);
626*9880d681SAndroid Build Coastguard Worker A->takeName(&I);
627*9880d681SAndroid Build Coastguard Worker return A;
628*9880d681SAndroid Build Coastguard Worker }
629*9880d681SAndroid Build Coastguard Worker }
630*9880d681SAndroid Build Coastguard Worker
631*9880d681SAndroid Build Coastguard Worker // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
632*9880d681SAndroid Build Coastguard Worker // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
633*9880d681SAndroid Build Coastguard Worker if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
634*9880d681SAndroid Build Coastguard Worker if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
635*9880d681SAndroid Build Coastguard Worker if (SI0->getCondition() == SI1->getCondition()) {
636*9880d681SAndroid Build Coastguard Worker Value *SI = nullptr;
637*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
638*9880d681SAndroid Build Coastguard Worker SI1->getFalseValue(), DL, TLI, DT, AC))
639*9880d681SAndroid Build Coastguard Worker SI = Builder->CreateSelect(SI0->getCondition(),
640*9880d681SAndroid Build Coastguard Worker Builder->CreateBinOp(TopLevelOpcode,
641*9880d681SAndroid Build Coastguard Worker SI0->getTrueValue(),
642*9880d681SAndroid Build Coastguard Worker SI1->getTrueValue()),
643*9880d681SAndroid Build Coastguard Worker V);
644*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
645*9880d681SAndroid Build Coastguard Worker SI1->getTrueValue(), DL, TLI, DT, AC))
646*9880d681SAndroid Build Coastguard Worker SI = Builder->CreateSelect(
647*9880d681SAndroid Build Coastguard Worker SI0->getCondition(), V,
648*9880d681SAndroid Build Coastguard Worker Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
649*9880d681SAndroid Build Coastguard Worker SI1->getFalseValue()));
650*9880d681SAndroid Build Coastguard Worker if (SI) {
651*9880d681SAndroid Build Coastguard Worker SI->takeName(&I);
652*9880d681SAndroid Build Coastguard Worker return SI;
653*9880d681SAndroid Build Coastguard Worker }
654*9880d681SAndroid Build Coastguard Worker }
655*9880d681SAndroid Build Coastguard Worker }
656*9880d681SAndroid Build Coastguard Worker }
657*9880d681SAndroid Build Coastguard Worker
658*9880d681SAndroid Build Coastguard Worker return nullptr;
659*9880d681SAndroid Build Coastguard Worker }
660*9880d681SAndroid Build Coastguard Worker
661*9880d681SAndroid Build Coastguard Worker /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
662*9880d681SAndroid Build Coastguard Worker /// constant zero (which is the 'negate' form).
dyn_castNegVal(Value * V) const663*9880d681SAndroid Build Coastguard Worker Value *InstCombiner::dyn_castNegVal(Value *V) const {
664*9880d681SAndroid Build Coastguard Worker if (BinaryOperator::isNeg(V))
665*9880d681SAndroid Build Coastguard Worker return BinaryOperator::getNegArgument(V);
666*9880d681SAndroid Build Coastguard Worker
667*9880d681SAndroid Build Coastguard Worker // Constants can be considered to be negated values if they can be folded.
668*9880d681SAndroid Build Coastguard Worker if (ConstantInt *C = dyn_cast<ConstantInt>(V))
669*9880d681SAndroid Build Coastguard Worker return ConstantExpr::getNeg(C);
670*9880d681SAndroid Build Coastguard Worker
671*9880d681SAndroid Build Coastguard Worker if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
672*9880d681SAndroid Build Coastguard Worker if (C->getType()->getElementType()->isIntegerTy())
673*9880d681SAndroid Build Coastguard Worker return ConstantExpr::getNeg(C);
674*9880d681SAndroid Build Coastguard Worker
675*9880d681SAndroid Build Coastguard Worker return nullptr;
676*9880d681SAndroid Build Coastguard Worker }
677*9880d681SAndroid Build Coastguard Worker
678*9880d681SAndroid Build Coastguard Worker /// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
679*9880d681SAndroid Build Coastguard Worker /// a constant negative zero (which is the 'negate' form).
dyn_castFNegVal(Value * V,bool IgnoreZeroSign) const680*9880d681SAndroid Build Coastguard Worker Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
681*9880d681SAndroid Build Coastguard Worker if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
682*9880d681SAndroid Build Coastguard Worker return BinaryOperator::getFNegArgument(V);
683*9880d681SAndroid Build Coastguard Worker
684*9880d681SAndroid Build Coastguard Worker // Constants can be considered to be negated values if they can be folded.
685*9880d681SAndroid Build Coastguard Worker if (ConstantFP *C = dyn_cast<ConstantFP>(V))
686*9880d681SAndroid Build Coastguard Worker return ConstantExpr::getFNeg(C);
687*9880d681SAndroid Build Coastguard Worker
688*9880d681SAndroid Build Coastguard Worker if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
689*9880d681SAndroid Build Coastguard Worker if (C->getType()->getElementType()->isFloatingPointTy())
690*9880d681SAndroid Build Coastguard Worker return ConstantExpr::getFNeg(C);
691*9880d681SAndroid Build Coastguard Worker
692*9880d681SAndroid Build Coastguard Worker return nullptr;
693*9880d681SAndroid Build Coastguard Worker }
694*9880d681SAndroid Build Coastguard Worker
FoldOperationIntoSelectOperand(Instruction & I,Value * SO,InstCombiner * IC)695*9880d681SAndroid Build Coastguard Worker static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
696*9880d681SAndroid Build Coastguard Worker InstCombiner *IC) {
697*9880d681SAndroid Build Coastguard Worker if (CastInst *CI = dyn_cast<CastInst>(&I)) {
698*9880d681SAndroid Build Coastguard Worker return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
699*9880d681SAndroid Build Coastguard Worker }
700*9880d681SAndroid Build Coastguard Worker
701*9880d681SAndroid Build Coastguard Worker // Figure out if the constant is the left or the right argument.
702*9880d681SAndroid Build Coastguard Worker bool ConstIsRHS = isa<Constant>(I.getOperand(1));
703*9880d681SAndroid Build Coastguard Worker Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
704*9880d681SAndroid Build Coastguard Worker
705*9880d681SAndroid Build Coastguard Worker if (Constant *SOC = dyn_cast<Constant>(SO)) {
706*9880d681SAndroid Build Coastguard Worker if (ConstIsRHS)
707*9880d681SAndroid Build Coastguard Worker return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
708*9880d681SAndroid Build Coastguard Worker return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
709*9880d681SAndroid Build Coastguard Worker }
710*9880d681SAndroid Build Coastguard Worker
711*9880d681SAndroid Build Coastguard Worker Value *Op0 = SO, *Op1 = ConstOperand;
712*9880d681SAndroid Build Coastguard Worker if (!ConstIsRHS)
713*9880d681SAndroid Build Coastguard Worker std::swap(Op0, Op1);
714*9880d681SAndroid Build Coastguard Worker
715*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
716*9880d681SAndroid Build Coastguard Worker Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
717*9880d681SAndroid Build Coastguard Worker SO->getName()+".op");
718*9880d681SAndroid Build Coastguard Worker Instruction *FPInst = dyn_cast<Instruction>(RI);
719*9880d681SAndroid Build Coastguard Worker if (FPInst && isa<FPMathOperator>(FPInst))
720*9880d681SAndroid Build Coastguard Worker FPInst->copyFastMathFlags(BO);
721*9880d681SAndroid Build Coastguard Worker return RI;
722*9880d681SAndroid Build Coastguard Worker }
723*9880d681SAndroid Build Coastguard Worker if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
724*9880d681SAndroid Build Coastguard Worker return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
725*9880d681SAndroid Build Coastguard Worker SO->getName()+".cmp");
726*9880d681SAndroid Build Coastguard Worker if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
727*9880d681SAndroid Build Coastguard Worker return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
728*9880d681SAndroid Build Coastguard Worker SO->getName()+".cmp");
729*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Unknown binary instruction type!");
730*9880d681SAndroid Build Coastguard Worker }
731*9880d681SAndroid Build Coastguard Worker
732*9880d681SAndroid Build Coastguard Worker /// Given an instruction with a select as one operand and a constant as the
733*9880d681SAndroid Build Coastguard Worker /// other operand, try to fold the binary operator into the select arguments.
734*9880d681SAndroid Build Coastguard Worker /// This also works for Cast instructions, which obviously do not have a second
735*9880d681SAndroid Build Coastguard Worker /// operand.
FoldOpIntoSelect(Instruction & Op,SelectInst * SI)736*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
737*9880d681SAndroid Build Coastguard Worker // Don't modify shared select instructions
738*9880d681SAndroid Build Coastguard Worker if (!SI->hasOneUse()) return nullptr;
739*9880d681SAndroid Build Coastguard Worker Value *TV = SI->getOperand(1);
740*9880d681SAndroid Build Coastguard Worker Value *FV = SI->getOperand(2);
741*9880d681SAndroid Build Coastguard Worker
742*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(TV) || isa<Constant>(FV)) {
743*9880d681SAndroid Build Coastguard Worker // Bool selects with constant operands can be folded to logical ops.
744*9880d681SAndroid Build Coastguard Worker if (SI->getType()->isIntegerTy(1)) return nullptr;
745*9880d681SAndroid Build Coastguard Worker
746*9880d681SAndroid Build Coastguard Worker // If it's a bitcast involving vectors, make sure it has the same number of
747*9880d681SAndroid Build Coastguard Worker // elements on both sides.
748*9880d681SAndroid Build Coastguard Worker if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
749*9880d681SAndroid Build Coastguard Worker VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
750*9880d681SAndroid Build Coastguard Worker VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
751*9880d681SAndroid Build Coastguard Worker
752*9880d681SAndroid Build Coastguard Worker // Verify that either both or neither are vectors.
753*9880d681SAndroid Build Coastguard Worker if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
754*9880d681SAndroid Build Coastguard Worker // If vectors, verify that they have the same number of elements.
755*9880d681SAndroid Build Coastguard Worker if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
756*9880d681SAndroid Build Coastguard Worker return nullptr;
757*9880d681SAndroid Build Coastguard Worker }
758*9880d681SAndroid Build Coastguard Worker
759*9880d681SAndroid Build Coastguard Worker // Test if a CmpInst instruction is used exclusively by a select as
760*9880d681SAndroid Build Coastguard Worker // part of a minimum or maximum operation. If so, refrain from doing
761*9880d681SAndroid Build Coastguard Worker // any other folding. This helps out other analyses which understand
762*9880d681SAndroid Build Coastguard Worker // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
763*9880d681SAndroid Build Coastguard Worker // and CodeGen. And in this case, at least one of the comparison
764*9880d681SAndroid Build Coastguard Worker // operands has at least one user besides the compare (the select),
765*9880d681SAndroid Build Coastguard Worker // which would often largely negate the benefit of folding anyway.
766*9880d681SAndroid Build Coastguard Worker if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
767*9880d681SAndroid Build Coastguard Worker if (CI->hasOneUse()) {
768*9880d681SAndroid Build Coastguard Worker Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
769*9880d681SAndroid Build Coastguard Worker if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
770*9880d681SAndroid Build Coastguard Worker (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
771*9880d681SAndroid Build Coastguard Worker return nullptr;
772*9880d681SAndroid Build Coastguard Worker }
773*9880d681SAndroid Build Coastguard Worker }
774*9880d681SAndroid Build Coastguard Worker
775*9880d681SAndroid Build Coastguard Worker Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
776*9880d681SAndroid Build Coastguard Worker Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
777*9880d681SAndroid Build Coastguard Worker
778*9880d681SAndroid Build Coastguard Worker return SelectInst::Create(SI->getCondition(),
779*9880d681SAndroid Build Coastguard Worker SelectTrueVal, SelectFalseVal);
780*9880d681SAndroid Build Coastguard Worker }
781*9880d681SAndroid Build Coastguard Worker return nullptr;
782*9880d681SAndroid Build Coastguard Worker }
783*9880d681SAndroid Build Coastguard Worker
784*9880d681SAndroid Build Coastguard Worker /// Given a binary operator, cast instruction, or select which has a PHI node as
785*9880d681SAndroid Build Coastguard Worker /// operand #0, see if we can fold the instruction into the PHI (which is only
786*9880d681SAndroid Build Coastguard Worker /// possible if all operands to the PHI are constants).
FoldOpIntoPhi(Instruction & I)787*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
788*9880d681SAndroid Build Coastguard Worker PHINode *PN = cast<PHINode>(I.getOperand(0));
789*9880d681SAndroid Build Coastguard Worker unsigned NumPHIValues = PN->getNumIncomingValues();
790*9880d681SAndroid Build Coastguard Worker if (NumPHIValues == 0)
791*9880d681SAndroid Build Coastguard Worker return nullptr;
792*9880d681SAndroid Build Coastguard Worker
793*9880d681SAndroid Build Coastguard Worker // We normally only transform phis with a single use. However, if a PHI has
794*9880d681SAndroid Build Coastguard Worker // multiple uses and they are all the same operation, we can fold *all* of the
795*9880d681SAndroid Build Coastguard Worker // uses into the PHI.
796*9880d681SAndroid Build Coastguard Worker if (!PN->hasOneUse()) {
797*9880d681SAndroid Build Coastguard Worker // Walk the use list for the instruction, comparing them to I.
798*9880d681SAndroid Build Coastguard Worker for (User *U : PN->users()) {
799*9880d681SAndroid Build Coastguard Worker Instruction *UI = cast<Instruction>(U);
800*9880d681SAndroid Build Coastguard Worker if (UI != &I && !I.isIdenticalTo(UI))
801*9880d681SAndroid Build Coastguard Worker return nullptr;
802*9880d681SAndroid Build Coastguard Worker }
803*9880d681SAndroid Build Coastguard Worker // Otherwise, we can replace *all* users with the new PHI we form.
804*9880d681SAndroid Build Coastguard Worker }
805*9880d681SAndroid Build Coastguard Worker
806*9880d681SAndroid Build Coastguard Worker // Check to see if all of the operands of the PHI are simple constants
807*9880d681SAndroid Build Coastguard Worker // (constantint/constantfp/undef). If there is one non-constant value,
808*9880d681SAndroid Build Coastguard Worker // remember the BB it is in. If there is more than one or if *it* is a PHI,
809*9880d681SAndroid Build Coastguard Worker // bail out. We don't do arbitrary constant expressions here because moving
810*9880d681SAndroid Build Coastguard Worker // their computation can be expensive without a cost model.
811*9880d681SAndroid Build Coastguard Worker BasicBlock *NonConstBB = nullptr;
812*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != NumPHIValues; ++i) {
813*9880d681SAndroid Build Coastguard Worker Value *InVal = PN->getIncomingValue(i);
814*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
815*9880d681SAndroid Build Coastguard Worker continue;
816*9880d681SAndroid Build Coastguard Worker
817*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
818*9880d681SAndroid Build Coastguard Worker if (NonConstBB) return nullptr; // More than one non-const value.
819*9880d681SAndroid Build Coastguard Worker
820*9880d681SAndroid Build Coastguard Worker NonConstBB = PN->getIncomingBlock(i);
821*9880d681SAndroid Build Coastguard Worker
822*9880d681SAndroid Build Coastguard Worker // If the InVal is an invoke at the end of the pred block, then we can't
823*9880d681SAndroid Build Coastguard Worker // insert a computation after it without breaking the edge.
824*9880d681SAndroid Build Coastguard Worker if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
825*9880d681SAndroid Build Coastguard Worker if (II->getParent() == NonConstBB)
826*9880d681SAndroid Build Coastguard Worker return nullptr;
827*9880d681SAndroid Build Coastguard Worker
828*9880d681SAndroid Build Coastguard Worker // If the incoming non-constant value is in I's block, we will remove one
829*9880d681SAndroid Build Coastguard Worker // instruction, but insert another equivalent one, leading to infinite
830*9880d681SAndroid Build Coastguard Worker // instcombine.
831*9880d681SAndroid Build Coastguard Worker if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
832*9880d681SAndroid Build Coastguard Worker return nullptr;
833*9880d681SAndroid Build Coastguard Worker }
834*9880d681SAndroid Build Coastguard Worker
835*9880d681SAndroid Build Coastguard Worker // If there is exactly one non-constant value, we can insert a copy of the
836*9880d681SAndroid Build Coastguard Worker // operation in that block. However, if this is a critical edge, we would be
837*9880d681SAndroid Build Coastguard Worker // inserting the computation on some other paths (e.g. inside a loop). Only
838*9880d681SAndroid Build Coastguard Worker // do this if the pred block is unconditionally branching into the phi block.
839*9880d681SAndroid Build Coastguard Worker if (NonConstBB != nullptr) {
840*9880d681SAndroid Build Coastguard Worker BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
841*9880d681SAndroid Build Coastguard Worker if (!BI || !BI->isUnconditional()) return nullptr;
842*9880d681SAndroid Build Coastguard Worker }
843*9880d681SAndroid Build Coastguard Worker
844*9880d681SAndroid Build Coastguard Worker // Okay, we can do the transformation: create the new PHI node.
845*9880d681SAndroid Build Coastguard Worker PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
846*9880d681SAndroid Build Coastguard Worker InsertNewInstBefore(NewPN, *PN);
847*9880d681SAndroid Build Coastguard Worker NewPN->takeName(PN);
848*9880d681SAndroid Build Coastguard Worker
849*9880d681SAndroid Build Coastguard Worker // If we are going to have to insert a new computation, do so right before the
850*9880d681SAndroid Build Coastguard Worker // predecessor's terminator.
851*9880d681SAndroid Build Coastguard Worker if (NonConstBB)
852*9880d681SAndroid Build Coastguard Worker Builder->SetInsertPoint(NonConstBB->getTerminator());
853*9880d681SAndroid Build Coastguard Worker
854*9880d681SAndroid Build Coastguard Worker // Next, add all of the operands to the PHI.
855*9880d681SAndroid Build Coastguard Worker if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
856*9880d681SAndroid Build Coastguard Worker // We only currently try to fold the condition of a select when it is a phi,
857*9880d681SAndroid Build Coastguard Worker // not the true/false values.
858*9880d681SAndroid Build Coastguard Worker Value *TrueV = SI->getTrueValue();
859*9880d681SAndroid Build Coastguard Worker Value *FalseV = SI->getFalseValue();
860*9880d681SAndroid Build Coastguard Worker BasicBlock *PhiTransBB = PN->getParent();
861*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != NumPHIValues; ++i) {
862*9880d681SAndroid Build Coastguard Worker BasicBlock *ThisBB = PN->getIncomingBlock(i);
863*9880d681SAndroid Build Coastguard Worker Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
864*9880d681SAndroid Build Coastguard Worker Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
865*9880d681SAndroid Build Coastguard Worker Value *InV = nullptr;
866*9880d681SAndroid Build Coastguard Worker // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
867*9880d681SAndroid Build Coastguard Worker // even if currently isNullValue gives false.
868*9880d681SAndroid Build Coastguard Worker Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
869*9880d681SAndroid Build Coastguard Worker if (InC && !isa<ConstantExpr>(InC))
870*9880d681SAndroid Build Coastguard Worker InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
871*9880d681SAndroid Build Coastguard Worker else
872*9880d681SAndroid Build Coastguard Worker InV = Builder->CreateSelect(PN->getIncomingValue(i),
873*9880d681SAndroid Build Coastguard Worker TrueVInPred, FalseVInPred, "phitmp");
874*9880d681SAndroid Build Coastguard Worker NewPN->addIncoming(InV, ThisBB);
875*9880d681SAndroid Build Coastguard Worker }
876*9880d681SAndroid Build Coastguard Worker } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
877*9880d681SAndroid Build Coastguard Worker Constant *C = cast<Constant>(I.getOperand(1));
878*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != NumPHIValues; ++i) {
879*9880d681SAndroid Build Coastguard Worker Value *InV = nullptr;
880*9880d681SAndroid Build Coastguard Worker if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
881*9880d681SAndroid Build Coastguard Worker InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
882*9880d681SAndroid Build Coastguard Worker else if (isa<ICmpInst>(CI))
883*9880d681SAndroid Build Coastguard Worker InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
884*9880d681SAndroid Build Coastguard Worker C, "phitmp");
885*9880d681SAndroid Build Coastguard Worker else
886*9880d681SAndroid Build Coastguard Worker InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
887*9880d681SAndroid Build Coastguard Worker C, "phitmp");
888*9880d681SAndroid Build Coastguard Worker NewPN->addIncoming(InV, PN->getIncomingBlock(i));
889*9880d681SAndroid Build Coastguard Worker }
890*9880d681SAndroid Build Coastguard Worker } else if (I.getNumOperands() == 2) {
891*9880d681SAndroid Build Coastguard Worker Constant *C = cast<Constant>(I.getOperand(1));
892*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != NumPHIValues; ++i) {
893*9880d681SAndroid Build Coastguard Worker Value *InV = nullptr;
894*9880d681SAndroid Build Coastguard Worker if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
895*9880d681SAndroid Build Coastguard Worker InV = ConstantExpr::get(I.getOpcode(), InC, C);
896*9880d681SAndroid Build Coastguard Worker else
897*9880d681SAndroid Build Coastguard Worker InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
898*9880d681SAndroid Build Coastguard Worker PN->getIncomingValue(i), C, "phitmp");
899*9880d681SAndroid Build Coastguard Worker NewPN->addIncoming(InV, PN->getIncomingBlock(i));
900*9880d681SAndroid Build Coastguard Worker }
901*9880d681SAndroid Build Coastguard Worker } else {
902*9880d681SAndroid Build Coastguard Worker CastInst *CI = cast<CastInst>(&I);
903*9880d681SAndroid Build Coastguard Worker Type *RetTy = CI->getType();
904*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != NumPHIValues; ++i) {
905*9880d681SAndroid Build Coastguard Worker Value *InV;
906*9880d681SAndroid Build Coastguard Worker if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
907*9880d681SAndroid Build Coastguard Worker InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
908*9880d681SAndroid Build Coastguard Worker else
909*9880d681SAndroid Build Coastguard Worker InV = Builder->CreateCast(CI->getOpcode(),
910*9880d681SAndroid Build Coastguard Worker PN->getIncomingValue(i), I.getType(), "phitmp");
911*9880d681SAndroid Build Coastguard Worker NewPN->addIncoming(InV, PN->getIncomingBlock(i));
912*9880d681SAndroid Build Coastguard Worker }
913*9880d681SAndroid Build Coastguard Worker }
914*9880d681SAndroid Build Coastguard Worker
915*9880d681SAndroid Build Coastguard Worker for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
916*9880d681SAndroid Build Coastguard Worker Instruction *User = cast<Instruction>(*UI++);
917*9880d681SAndroid Build Coastguard Worker if (User == &I) continue;
918*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*User, NewPN);
919*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*User);
920*9880d681SAndroid Build Coastguard Worker }
921*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(I, NewPN);
922*9880d681SAndroid Build Coastguard Worker }
923*9880d681SAndroid Build Coastguard Worker
924*9880d681SAndroid Build Coastguard Worker /// Given a pointer type and a constant offset, determine whether or not there
925*9880d681SAndroid Build Coastguard Worker /// is a sequence of GEP indices into the pointed type that will land us at the
926*9880d681SAndroid Build Coastguard Worker /// specified offset. If so, fill them into NewIndices and return the resultant
927*9880d681SAndroid Build Coastguard Worker /// element type, otherwise return null.
FindElementAtOffset(PointerType * PtrTy,int64_t Offset,SmallVectorImpl<Value * > & NewIndices)928*9880d681SAndroid Build Coastguard Worker Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
929*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Value *> &NewIndices) {
930*9880d681SAndroid Build Coastguard Worker Type *Ty = PtrTy->getElementType();
931*9880d681SAndroid Build Coastguard Worker if (!Ty->isSized())
932*9880d681SAndroid Build Coastguard Worker return nullptr;
933*9880d681SAndroid Build Coastguard Worker
934*9880d681SAndroid Build Coastguard Worker // Start with the index over the outer type. Note that the type size
935*9880d681SAndroid Build Coastguard Worker // might be zero (even if the offset isn't zero) if the indexed type
936*9880d681SAndroid Build Coastguard Worker // is something like [0 x {int, int}]
937*9880d681SAndroid Build Coastguard Worker Type *IntPtrTy = DL.getIntPtrType(PtrTy);
938*9880d681SAndroid Build Coastguard Worker int64_t FirstIdx = 0;
939*9880d681SAndroid Build Coastguard Worker if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
940*9880d681SAndroid Build Coastguard Worker FirstIdx = Offset/TySize;
941*9880d681SAndroid Build Coastguard Worker Offset -= FirstIdx*TySize;
942*9880d681SAndroid Build Coastguard Worker
943*9880d681SAndroid Build Coastguard Worker // Handle hosts where % returns negative instead of values [0..TySize).
944*9880d681SAndroid Build Coastguard Worker if (Offset < 0) {
945*9880d681SAndroid Build Coastguard Worker --FirstIdx;
946*9880d681SAndroid Build Coastguard Worker Offset += TySize;
947*9880d681SAndroid Build Coastguard Worker assert(Offset >= 0);
948*9880d681SAndroid Build Coastguard Worker }
949*9880d681SAndroid Build Coastguard Worker assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
950*9880d681SAndroid Build Coastguard Worker }
951*9880d681SAndroid Build Coastguard Worker
952*9880d681SAndroid Build Coastguard Worker NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
953*9880d681SAndroid Build Coastguard Worker
954*9880d681SAndroid Build Coastguard Worker // Index into the types. If we fail, set OrigBase to null.
955*9880d681SAndroid Build Coastguard Worker while (Offset) {
956*9880d681SAndroid Build Coastguard Worker // Indexing into tail padding between struct/array elements.
957*9880d681SAndroid Build Coastguard Worker if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
958*9880d681SAndroid Build Coastguard Worker return nullptr;
959*9880d681SAndroid Build Coastguard Worker
960*9880d681SAndroid Build Coastguard Worker if (StructType *STy = dyn_cast<StructType>(Ty)) {
961*9880d681SAndroid Build Coastguard Worker const StructLayout *SL = DL.getStructLayout(STy);
962*9880d681SAndroid Build Coastguard Worker assert(Offset < (int64_t)SL->getSizeInBytes() &&
963*9880d681SAndroid Build Coastguard Worker "Offset must stay within the indexed type");
964*9880d681SAndroid Build Coastguard Worker
965*9880d681SAndroid Build Coastguard Worker unsigned Elt = SL->getElementContainingOffset(Offset);
966*9880d681SAndroid Build Coastguard Worker NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
967*9880d681SAndroid Build Coastguard Worker Elt));
968*9880d681SAndroid Build Coastguard Worker
969*9880d681SAndroid Build Coastguard Worker Offset -= SL->getElementOffset(Elt);
970*9880d681SAndroid Build Coastguard Worker Ty = STy->getElementType(Elt);
971*9880d681SAndroid Build Coastguard Worker } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
972*9880d681SAndroid Build Coastguard Worker uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
973*9880d681SAndroid Build Coastguard Worker assert(EltSize && "Cannot index into a zero-sized array");
974*9880d681SAndroid Build Coastguard Worker NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
975*9880d681SAndroid Build Coastguard Worker Offset %= EltSize;
976*9880d681SAndroid Build Coastguard Worker Ty = AT->getElementType();
977*9880d681SAndroid Build Coastguard Worker } else {
978*9880d681SAndroid Build Coastguard Worker // Otherwise, we can't index into the middle of this atomic type, bail.
979*9880d681SAndroid Build Coastguard Worker return nullptr;
980*9880d681SAndroid Build Coastguard Worker }
981*9880d681SAndroid Build Coastguard Worker }
982*9880d681SAndroid Build Coastguard Worker
983*9880d681SAndroid Build Coastguard Worker return Ty;
984*9880d681SAndroid Build Coastguard Worker }
985*9880d681SAndroid Build Coastguard Worker
shouldMergeGEPs(GEPOperator & GEP,GEPOperator & Src)986*9880d681SAndroid Build Coastguard Worker static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
987*9880d681SAndroid Build Coastguard Worker // If this GEP has only 0 indices, it is the same pointer as
988*9880d681SAndroid Build Coastguard Worker // Src. If Src is not a trivial GEP too, don't combine
989*9880d681SAndroid Build Coastguard Worker // the indices.
990*9880d681SAndroid Build Coastguard Worker if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
991*9880d681SAndroid Build Coastguard Worker !Src.hasOneUse())
992*9880d681SAndroid Build Coastguard Worker return false;
993*9880d681SAndroid Build Coastguard Worker return true;
994*9880d681SAndroid Build Coastguard Worker }
995*9880d681SAndroid Build Coastguard Worker
996*9880d681SAndroid Build Coastguard Worker /// Return a value X such that Val = X * Scale, or null if none.
997*9880d681SAndroid Build Coastguard Worker /// If the multiplication is known not to overflow, then NoSignedWrap is set.
Descale(Value * Val,APInt Scale,bool & NoSignedWrap)998*9880d681SAndroid Build Coastguard Worker Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
999*9880d681SAndroid Build Coastguard Worker assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1000*9880d681SAndroid Build Coastguard Worker assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1001*9880d681SAndroid Build Coastguard Worker Scale.getBitWidth() && "Scale not compatible with value!");
1002*9880d681SAndroid Build Coastguard Worker
1003*9880d681SAndroid Build Coastguard Worker // If Val is zero or Scale is one then Val = Val * Scale.
1004*9880d681SAndroid Build Coastguard Worker if (match(Val, m_Zero()) || Scale == 1) {
1005*9880d681SAndroid Build Coastguard Worker NoSignedWrap = true;
1006*9880d681SAndroid Build Coastguard Worker return Val;
1007*9880d681SAndroid Build Coastguard Worker }
1008*9880d681SAndroid Build Coastguard Worker
1009*9880d681SAndroid Build Coastguard Worker // If Scale is zero then it does not divide Val.
1010*9880d681SAndroid Build Coastguard Worker if (Scale.isMinValue())
1011*9880d681SAndroid Build Coastguard Worker return nullptr;
1012*9880d681SAndroid Build Coastguard Worker
1013*9880d681SAndroid Build Coastguard Worker // Look through chains of multiplications, searching for a constant that is
1014*9880d681SAndroid Build Coastguard Worker // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1015*9880d681SAndroid Build Coastguard Worker // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1016*9880d681SAndroid Build Coastguard Worker // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1017*9880d681SAndroid Build Coastguard Worker // down from Val:
1018*9880d681SAndroid Build Coastguard Worker //
1019*9880d681SAndroid Build Coastguard Worker // Val = M1 * X || Analysis starts here and works down
1020*9880d681SAndroid Build Coastguard Worker // M1 = M2 * Y || Doesn't descend into terms with more
1021*9880d681SAndroid Build Coastguard Worker // M2 = Z * 4 \/ than one use
1022*9880d681SAndroid Build Coastguard Worker //
1023*9880d681SAndroid Build Coastguard Worker // Then to modify a term at the bottom:
1024*9880d681SAndroid Build Coastguard Worker //
1025*9880d681SAndroid Build Coastguard Worker // Val = M1 * X
1026*9880d681SAndroid Build Coastguard Worker // M1 = Z * Y || Replaced M2 with Z
1027*9880d681SAndroid Build Coastguard Worker //
1028*9880d681SAndroid Build Coastguard Worker // Then to work back up correcting nsw flags.
1029*9880d681SAndroid Build Coastguard Worker
1030*9880d681SAndroid Build Coastguard Worker // Op - the term we are currently analyzing. Starts at Val then drills down.
1031*9880d681SAndroid Build Coastguard Worker // Replaced with its descaled value before exiting from the drill down loop.
1032*9880d681SAndroid Build Coastguard Worker Value *Op = Val;
1033*9880d681SAndroid Build Coastguard Worker
1034*9880d681SAndroid Build Coastguard Worker // Parent - initially null, but after drilling down notes where Op came from.
1035*9880d681SAndroid Build Coastguard Worker // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1036*9880d681SAndroid Build Coastguard Worker // 0'th operand of Val.
1037*9880d681SAndroid Build Coastguard Worker std::pair<Instruction*, unsigned> Parent;
1038*9880d681SAndroid Build Coastguard Worker
1039*9880d681SAndroid Build Coastguard Worker // Set if the transform requires a descaling at deeper levels that doesn't
1040*9880d681SAndroid Build Coastguard Worker // overflow.
1041*9880d681SAndroid Build Coastguard Worker bool RequireNoSignedWrap = false;
1042*9880d681SAndroid Build Coastguard Worker
1043*9880d681SAndroid Build Coastguard Worker // Log base 2 of the scale. Negative if not a power of 2.
1044*9880d681SAndroid Build Coastguard Worker int32_t logScale = Scale.exactLogBase2();
1045*9880d681SAndroid Build Coastguard Worker
1046*9880d681SAndroid Build Coastguard Worker for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1047*9880d681SAndroid Build Coastguard Worker
1048*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1049*9880d681SAndroid Build Coastguard Worker // If Op is a constant divisible by Scale then descale to the quotient.
1050*9880d681SAndroid Build Coastguard Worker APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1051*9880d681SAndroid Build Coastguard Worker APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1052*9880d681SAndroid Build Coastguard Worker if (!Remainder.isMinValue())
1053*9880d681SAndroid Build Coastguard Worker // Not divisible by Scale.
1054*9880d681SAndroid Build Coastguard Worker return nullptr;
1055*9880d681SAndroid Build Coastguard Worker // Replace with the quotient in the parent.
1056*9880d681SAndroid Build Coastguard Worker Op = ConstantInt::get(CI->getType(), Quotient);
1057*9880d681SAndroid Build Coastguard Worker NoSignedWrap = true;
1058*9880d681SAndroid Build Coastguard Worker break;
1059*9880d681SAndroid Build Coastguard Worker }
1060*9880d681SAndroid Build Coastguard Worker
1061*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1062*9880d681SAndroid Build Coastguard Worker
1063*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() == Instruction::Mul) {
1064*9880d681SAndroid Build Coastguard Worker // Multiplication.
1065*9880d681SAndroid Build Coastguard Worker NoSignedWrap = BO->hasNoSignedWrap();
1066*9880d681SAndroid Build Coastguard Worker if (RequireNoSignedWrap && !NoSignedWrap)
1067*9880d681SAndroid Build Coastguard Worker return nullptr;
1068*9880d681SAndroid Build Coastguard Worker
1069*9880d681SAndroid Build Coastguard Worker // There are three cases for multiplication: multiplication by exactly
1070*9880d681SAndroid Build Coastguard Worker // the scale, multiplication by a constant different to the scale, and
1071*9880d681SAndroid Build Coastguard Worker // multiplication by something else.
1072*9880d681SAndroid Build Coastguard Worker Value *LHS = BO->getOperand(0);
1073*9880d681SAndroid Build Coastguard Worker Value *RHS = BO->getOperand(1);
1074*9880d681SAndroid Build Coastguard Worker
1075*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1076*9880d681SAndroid Build Coastguard Worker // Multiplication by a constant.
1077*9880d681SAndroid Build Coastguard Worker if (CI->getValue() == Scale) {
1078*9880d681SAndroid Build Coastguard Worker // Multiplication by exactly the scale, replace the multiplication
1079*9880d681SAndroid Build Coastguard Worker // by its left-hand side in the parent.
1080*9880d681SAndroid Build Coastguard Worker Op = LHS;
1081*9880d681SAndroid Build Coastguard Worker break;
1082*9880d681SAndroid Build Coastguard Worker }
1083*9880d681SAndroid Build Coastguard Worker
1084*9880d681SAndroid Build Coastguard Worker // Otherwise drill down into the constant.
1085*9880d681SAndroid Build Coastguard Worker if (!Op->hasOneUse())
1086*9880d681SAndroid Build Coastguard Worker return nullptr;
1087*9880d681SAndroid Build Coastguard Worker
1088*9880d681SAndroid Build Coastguard Worker Parent = std::make_pair(BO, 1);
1089*9880d681SAndroid Build Coastguard Worker continue;
1090*9880d681SAndroid Build Coastguard Worker }
1091*9880d681SAndroid Build Coastguard Worker
1092*9880d681SAndroid Build Coastguard Worker // Multiplication by something else. Drill down into the left-hand side
1093*9880d681SAndroid Build Coastguard Worker // since that's where the reassociate pass puts the good stuff.
1094*9880d681SAndroid Build Coastguard Worker if (!Op->hasOneUse())
1095*9880d681SAndroid Build Coastguard Worker return nullptr;
1096*9880d681SAndroid Build Coastguard Worker
1097*9880d681SAndroid Build Coastguard Worker Parent = std::make_pair(BO, 0);
1098*9880d681SAndroid Build Coastguard Worker continue;
1099*9880d681SAndroid Build Coastguard Worker }
1100*9880d681SAndroid Build Coastguard Worker
1101*9880d681SAndroid Build Coastguard Worker if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1102*9880d681SAndroid Build Coastguard Worker isa<ConstantInt>(BO->getOperand(1))) {
1103*9880d681SAndroid Build Coastguard Worker // Multiplication by a power of 2.
1104*9880d681SAndroid Build Coastguard Worker NoSignedWrap = BO->hasNoSignedWrap();
1105*9880d681SAndroid Build Coastguard Worker if (RequireNoSignedWrap && !NoSignedWrap)
1106*9880d681SAndroid Build Coastguard Worker return nullptr;
1107*9880d681SAndroid Build Coastguard Worker
1108*9880d681SAndroid Build Coastguard Worker Value *LHS = BO->getOperand(0);
1109*9880d681SAndroid Build Coastguard Worker int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1110*9880d681SAndroid Build Coastguard Worker getLimitedValue(Scale.getBitWidth());
1111*9880d681SAndroid Build Coastguard Worker // Op = LHS << Amt.
1112*9880d681SAndroid Build Coastguard Worker
1113*9880d681SAndroid Build Coastguard Worker if (Amt == logScale) {
1114*9880d681SAndroid Build Coastguard Worker // Multiplication by exactly the scale, replace the multiplication
1115*9880d681SAndroid Build Coastguard Worker // by its left-hand side in the parent.
1116*9880d681SAndroid Build Coastguard Worker Op = LHS;
1117*9880d681SAndroid Build Coastguard Worker break;
1118*9880d681SAndroid Build Coastguard Worker }
1119*9880d681SAndroid Build Coastguard Worker if (Amt < logScale || !Op->hasOneUse())
1120*9880d681SAndroid Build Coastguard Worker return nullptr;
1121*9880d681SAndroid Build Coastguard Worker
1122*9880d681SAndroid Build Coastguard Worker // Multiplication by more than the scale. Reduce the multiplying amount
1123*9880d681SAndroid Build Coastguard Worker // by the scale in the parent.
1124*9880d681SAndroid Build Coastguard Worker Parent = std::make_pair(BO, 1);
1125*9880d681SAndroid Build Coastguard Worker Op = ConstantInt::get(BO->getType(), Amt - logScale);
1126*9880d681SAndroid Build Coastguard Worker break;
1127*9880d681SAndroid Build Coastguard Worker }
1128*9880d681SAndroid Build Coastguard Worker }
1129*9880d681SAndroid Build Coastguard Worker
1130*9880d681SAndroid Build Coastguard Worker if (!Op->hasOneUse())
1131*9880d681SAndroid Build Coastguard Worker return nullptr;
1132*9880d681SAndroid Build Coastguard Worker
1133*9880d681SAndroid Build Coastguard Worker if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1134*9880d681SAndroid Build Coastguard Worker if (Cast->getOpcode() == Instruction::SExt) {
1135*9880d681SAndroid Build Coastguard Worker // Op is sign-extended from a smaller type, descale in the smaller type.
1136*9880d681SAndroid Build Coastguard Worker unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1137*9880d681SAndroid Build Coastguard Worker APInt SmallScale = Scale.trunc(SmallSize);
1138*9880d681SAndroid Build Coastguard Worker // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1139*9880d681SAndroid Build Coastguard Worker // descale Op as (sext Y) * Scale. In order to have
1140*9880d681SAndroid Build Coastguard Worker // sext (Y * SmallScale) = (sext Y) * Scale
1141*9880d681SAndroid Build Coastguard Worker // some conditions need to hold however: SmallScale must sign-extend to
1142*9880d681SAndroid Build Coastguard Worker // Scale and the multiplication Y * SmallScale should not overflow.
1143*9880d681SAndroid Build Coastguard Worker if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1144*9880d681SAndroid Build Coastguard Worker // SmallScale does not sign-extend to Scale.
1145*9880d681SAndroid Build Coastguard Worker return nullptr;
1146*9880d681SAndroid Build Coastguard Worker assert(SmallScale.exactLogBase2() == logScale);
1147*9880d681SAndroid Build Coastguard Worker // Require that Y * SmallScale must not overflow.
1148*9880d681SAndroid Build Coastguard Worker RequireNoSignedWrap = true;
1149*9880d681SAndroid Build Coastguard Worker
1150*9880d681SAndroid Build Coastguard Worker // Drill down through the cast.
1151*9880d681SAndroid Build Coastguard Worker Parent = std::make_pair(Cast, 0);
1152*9880d681SAndroid Build Coastguard Worker Scale = SmallScale;
1153*9880d681SAndroid Build Coastguard Worker continue;
1154*9880d681SAndroid Build Coastguard Worker }
1155*9880d681SAndroid Build Coastguard Worker
1156*9880d681SAndroid Build Coastguard Worker if (Cast->getOpcode() == Instruction::Trunc) {
1157*9880d681SAndroid Build Coastguard Worker // Op is truncated from a larger type, descale in the larger type.
1158*9880d681SAndroid Build Coastguard Worker // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1159*9880d681SAndroid Build Coastguard Worker // trunc (Y * sext Scale) = (trunc Y) * Scale
1160*9880d681SAndroid Build Coastguard Worker // always holds. However (trunc Y) * Scale may overflow even if
1161*9880d681SAndroid Build Coastguard Worker // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1162*9880d681SAndroid Build Coastguard Worker // from this point up in the expression (see later).
1163*9880d681SAndroid Build Coastguard Worker if (RequireNoSignedWrap)
1164*9880d681SAndroid Build Coastguard Worker return nullptr;
1165*9880d681SAndroid Build Coastguard Worker
1166*9880d681SAndroid Build Coastguard Worker // Drill down through the cast.
1167*9880d681SAndroid Build Coastguard Worker unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1168*9880d681SAndroid Build Coastguard Worker Parent = std::make_pair(Cast, 0);
1169*9880d681SAndroid Build Coastguard Worker Scale = Scale.sext(LargeSize);
1170*9880d681SAndroid Build Coastguard Worker if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1171*9880d681SAndroid Build Coastguard Worker logScale = -1;
1172*9880d681SAndroid Build Coastguard Worker assert(Scale.exactLogBase2() == logScale);
1173*9880d681SAndroid Build Coastguard Worker continue;
1174*9880d681SAndroid Build Coastguard Worker }
1175*9880d681SAndroid Build Coastguard Worker }
1176*9880d681SAndroid Build Coastguard Worker
1177*9880d681SAndroid Build Coastguard Worker // Unsupported expression, bail out.
1178*9880d681SAndroid Build Coastguard Worker return nullptr;
1179*9880d681SAndroid Build Coastguard Worker }
1180*9880d681SAndroid Build Coastguard Worker
1181*9880d681SAndroid Build Coastguard Worker // If Op is zero then Val = Op * Scale.
1182*9880d681SAndroid Build Coastguard Worker if (match(Op, m_Zero())) {
1183*9880d681SAndroid Build Coastguard Worker NoSignedWrap = true;
1184*9880d681SAndroid Build Coastguard Worker return Op;
1185*9880d681SAndroid Build Coastguard Worker }
1186*9880d681SAndroid Build Coastguard Worker
1187*9880d681SAndroid Build Coastguard Worker // We know that we can successfully descale, so from here on we can safely
1188*9880d681SAndroid Build Coastguard Worker // modify the IR. Op holds the descaled version of the deepest term in the
1189*9880d681SAndroid Build Coastguard Worker // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1190*9880d681SAndroid Build Coastguard Worker // not to overflow.
1191*9880d681SAndroid Build Coastguard Worker
1192*9880d681SAndroid Build Coastguard Worker if (!Parent.first)
1193*9880d681SAndroid Build Coastguard Worker // The expression only had one term.
1194*9880d681SAndroid Build Coastguard Worker return Op;
1195*9880d681SAndroid Build Coastguard Worker
1196*9880d681SAndroid Build Coastguard Worker // Rewrite the parent using the descaled version of its operand.
1197*9880d681SAndroid Build Coastguard Worker assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1198*9880d681SAndroid Build Coastguard Worker assert(Op != Parent.first->getOperand(Parent.second) &&
1199*9880d681SAndroid Build Coastguard Worker "Descaling was a no-op?");
1200*9880d681SAndroid Build Coastguard Worker Parent.first->setOperand(Parent.second, Op);
1201*9880d681SAndroid Build Coastguard Worker Worklist.Add(Parent.first);
1202*9880d681SAndroid Build Coastguard Worker
1203*9880d681SAndroid Build Coastguard Worker // Now work back up the expression correcting nsw flags. The logic is based
1204*9880d681SAndroid Build Coastguard Worker // on the following observation: if X * Y is known not to overflow as a signed
1205*9880d681SAndroid Build Coastguard Worker // multiplication, and Y is replaced by a value Z with smaller absolute value,
1206*9880d681SAndroid Build Coastguard Worker // then X * Z will not overflow as a signed multiplication either. As we work
1207*9880d681SAndroid Build Coastguard Worker // our way up, having NoSignedWrap 'true' means that the descaled value at the
1208*9880d681SAndroid Build Coastguard Worker // current level has strictly smaller absolute value than the original.
1209*9880d681SAndroid Build Coastguard Worker Instruction *Ancestor = Parent.first;
1210*9880d681SAndroid Build Coastguard Worker do {
1211*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1212*9880d681SAndroid Build Coastguard Worker // If the multiplication wasn't nsw then we can't say anything about the
1213*9880d681SAndroid Build Coastguard Worker // value of the descaled multiplication, and we have to clear nsw flags
1214*9880d681SAndroid Build Coastguard Worker // from this point on up.
1215*9880d681SAndroid Build Coastguard Worker bool OpNoSignedWrap = BO->hasNoSignedWrap();
1216*9880d681SAndroid Build Coastguard Worker NoSignedWrap &= OpNoSignedWrap;
1217*9880d681SAndroid Build Coastguard Worker if (NoSignedWrap != OpNoSignedWrap) {
1218*9880d681SAndroid Build Coastguard Worker BO->setHasNoSignedWrap(NoSignedWrap);
1219*9880d681SAndroid Build Coastguard Worker Worklist.Add(Ancestor);
1220*9880d681SAndroid Build Coastguard Worker }
1221*9880d681SAndroid Build Coastguard Worker } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1222*9880d681SAndroid Build Coastguard Worker // The fact that the descaled input to the trunc has smaller absolute
1223*9880d681SAndroid Build Coastguard Worker // value than the original input doesn't tell us anything useful about
1224*9880d681SAndroid Build Coastguard Worker // the absolute values of the truncations.
1225*9880d681SAndroid Build Coastguard Worker NoSignedWrap = false;
1226*9880d681SAndroid Build Coastguard Worker }
1227*9880d681SAndroid Build Coastguard Worker assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1228*9880d681SAndroid Build Coastguard Worker "Failed to keep proper track of nsw flags while drilling down?");
1229*9880d681SAndroid Build Coastguard Worker
1230*9880d681SAndroid Build Coastguard Worker if (Ancestor == Val)
1231*9880d681SAndroid Build Coastguard Worker // Got to the top, all done!
1232*9880d681SAndroid Build Coastguard Worker return Val;
1233*9880d681SAndroid Build Coastguard Worker
1234*9880d681SAndroid Build Coastguard Worker // Move up one level in the expression.
1235*9880d681SAndroid Build Coastguard Worker assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1236*9880d681SAndroid Build Coastguard Worker Ancestor = Ancestor->user_back();
1237*9880d681SAndroid Build Coastguard Worker } while (1);
1238*9880d681SAndroid Build Coastguard Worker }
1239*9880d681SAndroid Build Coastguard Worker
1240*9880d681SAndroid Build Coastguard Worker /// \brief Creates node of binary operation with the same attributes as the
1241*9880d681SAndroid Build Coastguard Worker /// specified one but with other operands.
CreateBinOpAsGiven(BinaryOperator & Inst,Value * LHS,Value * RHS,InstCombiner::BuilderTy * B)1242*9880d681SAndroid Build Coastguard Worker static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1243*9880d681SAndroid Build Coastguard Worker InstCombiner::BuilderTy *B) {
1244*9880d681SAndroid Build Coastguard Worker Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1245*9880d681SAndroid Build Coastguard Worker // If LHS and RHS are constant, BO won't be a binary operator.
1246*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1247*9880d681SAndroid Build Coastguard Worker NewBO->copyIRFlags(&Inst);
1248*9880d681SAndroid Build Coastguard Worker return BO;
1249*9880d681SAndroid Build Coastguard Worker }
1250*9880d681SAndroid Build Coastguard Worker
1251*9880d681SAndroid Build Coastguard Worker /// \brief Makes transformation of binary operation specific for vector types.
1252*9880d681SAndroid Build Coastguard Worker /// \param Inst Binary operator to transform.
1253*9880d681SAndroid Build Coastguard Worker /// \return Pointer to node that must replace the original binary operator, or
1254*9880d681SAndroid Build Coastguard Worker /// null pointer if no transformation was made.
SimplifyVectorOp(BinaryOperator & Inst)1255*9880d681SAndroid Build Coastguard Worker Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1256*9880d681SAndroid Build Coastguard Worker if (!Inst.getType()->isVectorTy()) return nullptr;
1257*9880d681SAndroid Build Coastguard Worker
1258*9880d681SAndroid Build Coastguard Worker // It may not be safe to reorder shuffles and things like div, urem, etc.
1259*9880d681SAndroid Build Coastguard Worker // because we may trap when executing those ops on unknown vector elements.
1260*9880d681SAndroid Build Coastguard Worker // See PR20059.
1261*9880d681SAndroid Build Coastguard Worker if (!isSafeToSpeculativelyExecute(&Inst))
1262*9880d681SAndroid Build Coastguard Worker return nullptr;
1263*9880d681SAndroid Build Coastguard Worker
1264*9880d681SAndroid Build Coastguard Worker unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1265*9880d681SAndroid Build Coastguard Worker Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1266*9880d681SAndroid Build Coastguard Worker assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1267*9880d681SAndroid Build Coastguard Worker assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1268*9880d681SAndroid Build Coastguard Worker
1269*9880d681SAndroid Build Coastguard Worker // If both arguments of binary operation are shuffles, which use the same
1270*9880d681SAndroid Build Coastguard Worker // mask and shuffle within a single vector, it is worthwhile to move the
1271*9880d681SAndroid Build Coastguard Worker // shuffle after binary operation:
1272*9880d681SAndroid Build Coastguard Worker // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1273*9880d681SAndroid Build Coastguard Worker if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1274*9880d681SAndroid Build Coastguard Worker ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1275*9880d681SAndroid Build Coastguard Worker ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1276*9880d681SAndroid Build Coastguard Worker if (isa<UndefValue>(LShuf->getOperand(1)) &&
1277*9880d681SAndroid Build Coastguard Worker isa<UndefValue>(RShuf->getOperand(1)) &&
1278*9880d681SAndroid Build Coastguard Worker LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1279*9880d681SAndroid Build Coastguard Worker LShuf->getMask() == RShuf->getMask()) {
1280*9880d681SAndroid Build Coastguard Worker Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1281*9880d681SAndroid Build Coastguard Worker RShuf->getOperand(0), Builder);
1282*9880d681SAndroid Build Coastguard Worker return Builder->CreateShuffleVector(NewBO,
1283*9880d681SAndroid Build Coastguard Worker UndefValue::get(NewBO->getType()), LShuf->getMask());
1284*9880d681SAndroid Build Coastguard Worker }
1285*9880d681SAndroid Build Coastguard Worker }
1286*9880d681SAndroid Build Coastguard Worker
1287*9880d681SAndroid Build Coastguard Worker // If one argument is a shuffle within one vector, the other is a constant,
1288*9880d681SAndroid Build Coastguard Worker // try moving the shuffle after the binary operation.
1289*9880d681SAndroid Build Coastguard Worker ShuffleVectorInst *Shuffle = nullptr;
1290*9880d681SAndroid Build Coastguard Worker Constant *C1 = nullptr;
1291*9880d681SAndroid Build Coastguard Worker if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1292*9880d681SAndroid Build Coastguard Worker if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1293*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1294*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1295*9880d681SAndroid Build Coastguard Worker if (Shuffle && C1 &&
1296*9880d681SAndroid Build Coastguard Worker (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1297*9880d681SAndroid Build Coastguard Worker isa<UndefValue>(Shuffle->getOperand(1)) &&
1298*9880d681SAndroid Build Coastguard Worker Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1299*9880d681SAndroid Build Coastguard Worker SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1300*9880d681SAndroid Build Coastguard Worker // Find constant C2 that has property:
1301*9880d681SAndroid Build Coastguard Worker // shuffle(C2, ShMask) = C1
1302*9880d681SAndroid Build Coastguard Worker // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1303*9880d681SAndroid Build Coastguard Worker // reorder is not possible.
1304*9880d681SAndroid Build Coastguard Worker SmallVector<Constant*, 16> C2M(VWidth,
1305*9880d681SAndroid Build Coastguard Worker UndefValue::get(C1->getType()->getScalarType()));
1306*9880d681SAndroid Build Coastguard Worker bool MayChange = true;
1307*9880d681SAndroid Build Coastguard Worker for (unsigned I = 0; I < VWidth; ++I) {
1308*9880d681SAndroid Build Coastguard Worker if (ShMask[I] >= 0) {
1309*9880d681SAndroid Build Coastguard Worker assert(ShMask[I] < (int)VWidth);
1310*9880d681SAndroid Build Coastguard Worker if (!isa<UndefValue>(C2M[ShMask[I]])) {
1311*9880d681SAndroid Build Coastguard Worker MayChange = false;
1312*9880d681SAndroid Build Coastguard Worker break;
1313*9880d681SAndroid Build Coastguard Worker }
1314*9880d681SAndroid Build Coastguard Worker C2M[ShMask[I]] = C1->getAggregateElement(I);
1315*9880d681SAndroid Build Coastguard Worker }
1316*9880d681SAndroid Build Coastguard Worker }
1317*9880d681SAndroid Build Coastguard Worker if (MayChange) {
1318*9880d681SAndroid Build Coastguard Worker Constant *C2 = ConstantVector::get(C2M);
1319*9880d681SAndroid Build Coastguard Worker Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1320*9880d681SAndroid Build Coastguard Worker Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
1321*9880d681SAndroid Build Coastguard Worker Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1322*9880d681SAndroid Build Coastguard Worker return Builder->CreateShuffleVector(NewBO,
1323*9880d681SAndroid Build Coastguard Worker UndefValue::get(Inst.getType()), Shuffle->getMask());
1324*9880d681SAndroid Build Coastguard Worker }
1325*9880d681SAndroid Build Coastguard Worker }
1326*9880d681SAndroid Build Coastguard Worker
1327*9880d681SAndroid Build Coastguard Worker return nullptr;
1328*9880d681SAndroid Build Coastguard Worker }
1329*9880d681SAndroid Build Coastguard Worker
visitGetElementPtrInst(GetElementPtrInst & GEP)1330*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1331*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1332*9880d681SAndroid Build Coastguard Worker
1333*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, TLI, DT, AC))
1334*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(GEP, V);
1335*9880d681SAndroid Build Coastguard Worker
1336*9880d681SAndroid Build Coastguard Worker Value *PtrOp = GEP.getOperand(0);
1337*9880d681SAndroid Build Coastguard Worker
1338*9880d681SAndroid Build Coastguard Worker // Eliminate unneeded casts for indices, and replace indices which displace
1339*9880d681SAndroid Build Coastguard Worker // by multiples of a zero size type with zero.
1340*9880d681SAndroid Build Coastguard Worker bool MadeChange = false;
1341*9880d681SAndroid Build Coastguard Worker Type *IntPtrTy =
1342*9880d681SAndroid Build Coastguard Worker DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
1343*9880d681SAndroid Build Coastguard Worker
1344*9880d681SAndroid Build Coastguard Worker gep_type_iterator GTI = gep_type_begin(GEP);
1345*9880d681SAndroid Build Coastguard Worker for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1346*9880d681SAndroid Build Coastguard Worker ++I, ++GTI) {
1347*9880d681SAndroid Build Coastguard Worker // Skip indices into struct types.
1348*9880d681SAndroid Build Coastguard Worker if (isa<StructType>(*GTI))
1349*9880d681SAndroid Build Coastguard Worker continue;
1350*9880d681SAndroid Build Coastguard Worker
1351*9880d681SAndroid Build Coastguard Worker // Index type should have the same width as IntPtr
1352*9880d681SAndroid Build Coastguard Worker Type *IndexTy = (*I)->getType();
1353*9880d681SAndroid Build Coastguard Worker Type *NewIndexType = IndexTy->isVectorTy() ?
1354*9880d681SAndroid Build Coastguard Worker VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
1355*9880d681SAndroid Build Coastguard Worker
1356*9880d681SAndroid Build Coastguard Worker // If the element type has zero size then any index over it is equivalent
1357*9880d681SAndroid Build Coastguard Worker // to an index of zero, so replace it with zero if it is not zero already.
1358*9880d681SAndroid Build Coastguard Worker Type *EltTy = GTI.getIndexedType();
1359*9880d681SAndroid Build Coastguard Worker if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1360*9880d681SAndroid Build Coastguard Worker if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1361*9880d681SAndroid Build Coastguard Worker *I = Constant::getNullValue(NewIndexType);
1362*9880d681SAndroid Build Coastguard Worker MadeChange = true;
1363*9880d681SAndroid Build Coastguard Worker }
1364*9880d681SAndroid Build Coastguard Worker
1365*9880d681SAndroid Build Coastguard Worker if (IndexTy != NewIndexType) {
1366*9880d681SAndroid Build Coastguard Worker // If we are using a wider index than needed for this platform, shrink
1367*9880d681SAndroid Build Coastguard Worker // it to what we need. If narrower, sign-extend it to what we need.
1368*9880d681SAndroid Build Coastguard Worker // This explicit cast can make subsequent optimizations more obvious.
1369*9880d681SAndroid Build Coastguard Worker *I = Builder->CreateIntCast(*I, NewIndexType, true);
1370*9880d681SAndroid Build Coastguard Worker MadeChange = true;
1371*9880d681SAndroid Build Coastguard Worker }
1372*9880d681SAndroid Build Coastguard Worker }
1373*9880d681SAndroid Build Coastguard Worker if (MadeChange)
1374*9880d681SAndroid Build Coastguard Worker return &GEP;
1375*9880d681SAndroid Build Coastguard Worker
1376*9880d681SAndroid Build Coastguard Worker // Check to see if the inputs to the PHI node are getelementptr instructions.
1377*9880d681SAndroid Build Coastguard Worker if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1378*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1379*9880d681SAndroid Build Coastguard Worker if (!Op1)
1380*9880d681SAndroid Build Coastguard Worker return nullptr;
1381*9880d681SAndroid Build Coastguard Worker
1382*9880d681SAndroid Build Coastguard Worker // Don't fold a GEP into itself through a PHI node. This can only happen
1383*9880d681SAndroid Build Coastguard Worker // through the back-edge of a loop. Folding a GEP into itself means that
1384*9880d681SAndroid Build Coastguard Worker // the value of the previous iteration needs to be stored in the meantime,
1385*9880d681SAndroid Build Coastguard Worker // thus requiring an additional register variable to be live, but not
1386*9880d681SAndroid Build Coastguard Worker // actually achieving anything (the GEP still needs to be executed once per
1387*9880d681SAndroid Build Coastguard Worker // loop iteration).
1388*9880d681SAndroid Build Coastguard Worker if (Op1 == &GEP)
1389*9880d681SAndroid Build Coastguard Worker return nullptr;
1390*9880d681SAndroid Build Coastguard Worker
1391*9880d681SAndroid Build Coastguard Worker int DI = -1;
1392*9880d681SAndroid Build Coastguard Worker
1393*9880d681SAndroid Build Coastguard Worker for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1394*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1395*9880d681SAndroid Build Coastguard Worker if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1396*9880d681SAndroid Build Coastguard Worker return nullptr;
1397*9880d681SAndroid Build Coastguard Worker
1398*9880d681SAndroid Build Coastguard Worker // As for Op1 above, don't try to fold a GEP into itself.
1399*9880d681SAndroid Build Coastguard Worker if (Op2 == &GEP)
1400*9880d681SAndroid Build Coastguard Worker return nullptr;
1401*9880d681SAndroid Build Coastguard Worker
1402*9880d681SAndroid Build Coastguard Worker // Keep track of the type as we walk the GEP.
1403*9880d681SAndroid Build Coastguard Worker Type *CurTy = nullptr;
1404*9880d681SAndroid Build Coastguard Worker
1405*9880d681SAndroid Build Coastguard Worker for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1406*9880d681SAndroid Build Coastguard Worker if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1407*9880d681SAndroid Build Coastguard Worker return nullptr;
1408*9880d681SAndroid Build Coastguard Worker
1409*9880d681SAndroid Build Coastguard Worker if (Op1->getOperand(J) != Op2->getOperand(J)) {
1410*9880d681SAndroid Build Coastguard Worker if (DI == -1) {
1411*9880d681SAndroid Build Coastguard Worker // We have not seen any differences yet in the GEPs feeding the
1412*9880d681SAndroid Build Coastguard Worker // PHI yet, so we record this one if it is allowed to be a
1413*9880d681SAndroid Build Coastguard Worker // variable.
1414*9880d681SAndroid Build Coastguard Worker
1415*9880d681SAndroid Build Coastguard Worker // The first two arguments can vary for any GEP, the rest have to be
1416*9880d681SAndroid Build Coastguard Worker // static for struct slots
1417*9880d681SAndroid Build Coastguard Worker if (J > 1 && CurTy->isStructTy())
1418*9880d681SAndroid Build Coastguard Worker return nullptr;
1419*9880d681SAndroid Build Coastguard Worker
1420*9880d681SAndroid Build Coastguard Worker DI = J;
1421*9880d681SAndroid Build Coastguard Worker } else {
1422*9880d681SAndroid Build Coastguard Worker // The GEP is different by more than one input. While this could be
1423*9880d681SAndroid Build Coastguard Worker // extended to support GEPs that vary by more than one variable it
1424*9880d681SAndroid Build Coastguard Worker // doesn't make sense since it greatly increases the complexity and
1425*9880d681SAndroid Build Coastguard Worker // would result in an R+R+R addressing mode which no backend
1426*9880d681SAndroid Build Coastguard Worker // directly supports and would need to be broken into several
1427*9880d681SAndroid Build Coastguard Worker // simpler instructions anyway.
1428*9880d681SAndroid Build Coastguard Worker return nullptr;
1429*9880d681SAndroid Build Coastguard Worker }
1430*9880d681SAndroid Build Coastguard Worker }
1431*9880d681SAndroid Build Coastguard Worker
1432*9880d681SAndroid Build Coastguard Worker // Sink down a layer of the type for the next iteration.
1433*9880d681SAndroid Build Coastguard Worker if (J > 0) {
1434*9880d681SAndroid Build Coastguard Worker if (J == 1) {
1435*9880d681SAndroid Build Coastguard Worker CurTy = Op1->getSourceElementType();
1436*9880d681SAndroid Build Coastguard Worker } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1437*9880d681SAndroid Build Coastguard Worker CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1438*9880d681SAndroid Build Coastguard Worker } else {
1439*9880d681SAndroid Build Coastguard Worker CurTy = nullptr;
1440*9880d681SAndroid Build Coastguard Worker }
1441*9880d681SAndroid Build Coastguard Worker }
1442*9880d681SAndroid Build Coastguard Worker }
1443*9880d681SAndroid Build Coastguard Worker }
1444*9880d681SAndroid Build Coastguard Worker
1445*9880d681SAndroid Build Coastguard Worker // If not all GEPs are identical we'll have to create a new PHI node.
1446*9880d681SAndroid Build Coastguard Worker // Check that the old PHI node has only one use so that it will get
1447*9880d681SAndroid Build Coastguard Worker // removed.
1448*9880d681SAndroid Build Coastguard Worker if (DI != -1 && !PN->hasOneUse())
1449*9880d681SAndroid Build Coastguard Worker return nullptr;
1450*9880d681SAndroid Build Coastguard Worker
1451*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1452*9880d681SAndroid Build Coastguard Worker if (DI == -1) {
1453*9880d681SAndroid Build Coastguard Worker // All the GEPs feeding the PHI are identical. Clone one down into our
1454*9880d681SAndroid Build Coastguard Worker // BB so that it can be merged with the current GEP.
1455*9880d681SAndroid Build Coastguard Worker GEP.getParent()->getInstList().insert(
1456*9880d681SAndroid Build Coastguard Worker GEP.getParent()->getFirstInsertionPt(), NewGEP);
1457*9880d681SAndroid Build Coastguard Worker } else {
1458*9880d681SAndroid Build Coastguard Worker // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1459*9880d681SAndroid Build Coastguard Worker // into the current block so it can be merged, and create a new PHI to
1460*9880d681SAndroid Build Coastguard Worker // set that index.
1461*9880d681SAndroid Build Coastguard Worker PHINode *NewPN;
1462*9880d681SAndroid Build Coastguard Worker {
1463*9880d681SAndroid Build Coastguard Worker IRBuilderBase::InsertPointGuard Guard(*Builder);
1464*9880d681SAndroid Build Coastguard Worker Builder->SetInsertPoint(PN);
1465*9880d681SAndroid Build Coastguard Worker NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1466*9880d681SAndroid Build Coastguard Worker PN->getNumOperands());
1467*9880d681SAndroid Build Coastguard Worker }
1468*9880d681SAndroid Build Coastguard Worker
1469*9880d681SAndroid Build Coastguard Worker for (auto &I : PN->operands())
1470*9880d681SAndroid Build Coastguard Worker NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1471*9880d681SAndroid Build Coastguard Worker PN->getIncomingBlock(I));
1472*9880d681SAndroid Build Coastguard Worker
1473*9880d681SAndroid Build Coastguard Worker NewGEP->setOperand(DI, NewPN);
1474*9880d681SAndroid Build Coastguard Worker GEP.getParent()->getInstList().insert(
1475*9880d681SAndroid Build Coastguard Worker GEP.getParent()->getFirstInsertionPt(), NewGEP);
1476*9880d681SAndroid Build Coastguard Worker NewGEP->setOperand(DI, NewPN);
1477*9880d681SAndroid Build Coastguard Worker }
1478*9880d681SAndroid Build Coastguard Worker
1479*9880d681SAndroid Build Coastguard Worker GEP.setOperand(0, NewGEP);
1480*9880d681SAndroid Build Coastguard Worker PtrOp = NewGEP;
1481*9880d681SAndroid Build Coastguard Worker }
1482*9880d681SAndroid Build Coastguard Worker
1483*9880d681SAndroid Build Coastguard Worker // Combine Indices - If the source pointer to this getelementptr instruction
1484*9880d681SAndroid Build Coastguard Worker // is a getelementptr instruction, combine the indices of the two
1485*9880d681SAndroid Build Coastguard Worker // getelementptr instructions into a single instruction.
1486*9880d681SAndroid Build Coastguard Worker //
1487*9880d681SAndroid Build Coastguard Worker if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1488*9880d681SAndroid Build Coastguard Worker if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1489*9880d681SAndroid Build Coastguard Worker return nullptr;
1490*9880d681SAndroid Build Coastguard Worker
1491*9880d681SAndroid Build Coastguard Worker // Note that if our source is a gep chain itself then we wait for that
1492*9880d681SAndroid Build Coastguard Worker // chain to be resolved before we perform this transformation. This
1493*9880d681SAndroid Build Coastguard Worker // avoids us creating a TON of code in some cases.
1494*9880d681SAndroid Build Coastguard Worker if (GEPOperator *SrcGEP =
1495*9880d681SAndroid Build Coastguard Worker dyn_cast<GEPOperator>(Src->getOperand(0)))
1496*9880d681SAndroid Build Coastguard Worker if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1497*9880d681SAndroid Build Coastguard Worker return nullptr; // Wait until our source is folded to completion.
1498*9880d681SAndroid Build Coastguard Worker
1499*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 8> Indices;
1500*9880d681SAndroid Build Coastguard Worker
1501*9880d681SAndroid Build Coastguard Worker // Find out whether the last index in the source GEP is a sequential idx.
1502*9880d681SAndroid Build Coastguard Worker bool EndsWithSequential = false;
1503*9880d681SAndroid Build Coastguard Worker for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1504*9880d681SAndroid Build Coastguard Worker I != E; ++I)
1505*9880d681SAndroid Build Coastguard Worker EndsWithSequential = !(*I)->isStructTy();
1506*9880d681SAndroid Build Coastguard Worker
1507*9880d681SAndroid Build Coastguard Worker // Can we combine the two pointer arithmetics offsets?
1508*9880d681SAndroid Build Coastguard Worker if (EndsWithSequential) {
1509*9880d681SAndroid Build Coastguard Worker // Replace: gep (gep %P, long B), long A, ...
1510*9880d681SAndroid Build Coastguard Worker // With: T = long A+B; gep %P, T, ...
1511*9880d681SAndroid Build Coastguard Worker //
1512*9880d681SAndroid Build Coastguard Worker Value *Sum;
1513*9880d681SAndroid Build Coastguard Worker Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1514*9880d681SAndroid Build Coastguard Worker Value *GO1 = GEP.getOperand(1);
1515*9880d681SAndroid Build Coastguard Worker if (SO1 == Constant::getNullValue(SO1->getType())) {
1516*9880d681SAndroid Build Coastguard Worker Sum = GO1;
1517*9880d681SAndroid Build Coastguard Worker } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1518*9880d681SAndroid Build Coastguard Worker Sum = SO1;
1519*9880d681SAndroid Build Coastguard Worker } else {
1520*9880d681SAndroid Build Coastguard Worker // If they aren't the same type, then the input hasn't been processed
1521*9880d681SAndroid Build Coastguard Worker // by the loop above yet (which canonicalizes sequential index types to
1522*9880d681SAndroid Build Coastguard Worker // intptr_t). Just avoid transforming this until the input has been
1523*9880d681SAndroid Build Coastguard Worker // normalized.
1524*9880d681SAndroid Build Coastguard Worker if (SO1->getType() != GO1->getType())
1525*9880d681SAndroid Build Coastguard Worker return nullptr;
1526*9880d681SAndroid Build Coastguard Worker // Only do the combine when GO1 and SO1 are both constants. Only in
1527*9880d681SAndroid Build Coastguard Worker // this case, we are sure the cost after the merge is never more than
1528*9880d681SAndroid Build Coastguard Worker // that before the merge.
1529*9880d681SAndroid Build Coastguard Worker if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1530*9880d681SAndroid Build Coastguard Worker return nullptr;
1531*9880d681SAndroid Build Coastguard Worker Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1532*9880d681SAndroid Build Coastguard Worker }
1533*9880d681SAndroid Build Coastguard Worker
1534*9880d681SAndroid Build Coastguard Worker // Update the GEP in place if possible.
1535*9880d681SAndroid Build Coastguard Worker if (Src->getNumOperands() == 2) {
1536*9880d681SAndroid Build Coastguard Worker GEP.setOperand(0, Src->getOperand(0));
1537*9880d681SAndroid Build Coastguard Worker GEP.setOperand(1, Sum);
1538*9880d681SAndroid Build Coastguard Worker return &GEP;
1539*9880d681SAndroid Build Coastguard Worker }
1540*9880d681SAndroid Build Coastguard Worker Indices.append(Src->op_begin()+1, Src->op_end()-1);
1541*9880d681SAndroid Build Coastguard Worker Indices.push_back(Sum);
1542*9880d681SAndroid Build Coastguard Worker Indices.append(GEP.op_begin()+2, GEP.op_end());
1543*9880d681SAndroid Build Coastguard Worker } else if (isa<Constant>(*GEP.idx_begin()) &&
1544*9880d681SAndroid Build Coastguard Worker cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1545*9880d681SAndroid Build Coastguard Worker Src->getNumOperands() != 1) {
1546*9880d681SAndroid Build Coastguard Worker // Otherwise we can do the fold if the first index of the GEP is a zero
1547*9880d681SAndroid Build Coastguard Worker Indices.append(Src->op_begin()+1, Src->op_end());
1548*9880d681SAndroid Build Coastguard Worker Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1549*9880d681SAndroid Build Coastguard Worker }
1550*9880d681SAndroid Build Coastguard Worker
1551*9880d681SAndroid Build Coastguard Worker if (!Indices.empty())
1552*9880d681SAndroid Build Coastguard Worker return GEP.isInBounds() && Src->isInBounds()
1553*9880d681SAndroid Build Coastguard Worker ? GetElementPtrInst::CreateInBounds(
1554*9880d681SAndroid Build Coastguard Worker Src->getSourceElementType(), Src->getOperand(0), Indices,
1555*9880d681SAndroid Build Coastguard Worker GEP.getName())
1556*9880d681SAndroid Build Coastguard Worker : GetElementPtrInst::Create(Src->getSourceElementType(),
1557*9880d681SAndroid Build Coastguard Worker Src->getOperand(0), Indices,
1558*9880d681SAndroid Build Coastguard Worker GEP.getName());
1559*9880d681SAndroid Build Coastguard Worker }
1560*9880d681SAndroid Build Coastguard Worker
1561*9880d681SAndroid Build Coastguard Worker if (GEP.getNumIndices() == 1) {
1562*9880d681SAndroid Build Coastguard Worker unsigned AS = GEP.getPointerAddressSpace();
1563*9880d681SAndroid Build Coastguard Worker if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1564*9880d681SAndroid Build Coastguard Worker DL.getPointerSizeInBits(AS)) {
1565*9880d681SAndroid Build Coastguard Worker Type *Ty = GEP.getSourceElementType();
1566*9880d681SAndroid Build Coastguard Worker uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1567*9880d681SAndroid Build Coastguard Worker
1568*9880d681SAndroid Build Coastguard Worker bool Matched = false;
1569*9880d681SAndroid Build Coastguard Worker uint64_t C;
1570*9880d681SAndroid Build Coastguard Worker Value *V = nullptr;
1571*9880d681SAndroid Build Coastguard Worker if (TyAllocSize == 1) {
1572*9880d681SAndroid Build Coastguard Worker V = GEP.getOperand(1);
1573*9880d681SAndroid Build Coastguard Worker Matched = true;
1574*9880d681SAndroid Build Coastguard Worker } else if (match(GEP.getOperand(1),
1575*9880d681SAndroid Build Coastguard Worker m_AShr(m_Value(V), m_ConstantInt(C)))) {
1576*9880d681SAndroid Build Coastguard Worker if (TyAllocSize == 1ULL << C)
1577*9880d681SAndroid Build Coastguard Worker Matched = true;
1578*9880d681SAndroid Build Coastguard Worker } else if (match(GEP.getOperand(1),
1579*9880d681SAndroid Build Coastguard Worker m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1580*9880d681SAndroid Build Coastguard Worker if (TyAllocSize == C)
1581*9880d681SAndroid Build Coastguard Worker Matched = true;
1582*9880d681SAndroid Build Coastguard Worker }
1583*9880d681SAndroid Build Coastguard Worker
1584*9880d681SAndroid Build Coastguard Worker if (Matched) {
1585*9880d681SAndroid Build Coastguard Worker // Canonicalize (gep i8* X, -(ptrtoint Y))
1586*9880d681SAndroid Build Coastguard Worker // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1587*9880d681SAndroid Build Coastguard Worker // The GEP pattern is emitted by the SCEV expander for certain kinds of
1588*9880d681SAndroid Build Coastguard Worker // pointer arithmetic.
1589*9880d681SAndroid Build Coastguard Worker if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1590*9880d681SAndroid Build Coastguard Worker Operator *Index = cast<Operator>(V);
1591*9880d681SAndroid Build Coastguard Worker Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1592*9880d681SAndroid Build Coastguard Worker Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1593*9880d681SAndroid Build Coastguard Worker return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1594*9880d681SAndroid Build Coastguard Worker }
1595*9880d681SAndroid Build Coastguard Worker // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1596*9880d681SAndroid Build Coastguard Worker // to (bitcast Y)
1597*9880d681SAndroid Build Coastguard Worker Value *Y;
1598*9880d681SAndroid Build Coastguard Worker if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1599*9880d681SAndroid Build Coastguard Worker m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1600*9880d681SAndroid Build Coastguard Worker return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1601*9880d681SAndroid Build Coastguard Worker GEP.getType());
1602*9880d681SAndroid Build Coastguard Worker }
1603*9880d681SAndroid Build Coastguard Worker }
1604*9880d681SAndroid Build Coastguard Worker }
1605*9880d681SAndroid Build Coastguard Worker }
1606*9880d681SAndroid Build Coastguard Worker
1607*9880d681SAndroid Build Coastguard Worker // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1608*9880d681SAndroid Build Coastguard Worker Value *StrippedPtr = PtrOp->stripPointerCasts();
1609*9880d681SAndroid Build Coastguard Worker PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1610*9880d681SAndroid Build Coastguard Worker
1611*9880d681SAndroid Build Coastguard Worker // We do not handle pointer-vector geps here.
1612*9880d681SAndroid Build Coastguard Worker if (!StrippedPtrTy)
1613*9880d681SAndroid Build Coastguard Worker return nullptr;
1614*9880d681SAndroid Build Coastguard Worker
1615*9880d681SAndroid Build Coastguard Worker if (StrippedPtr != PtrOp) {
1616*9880d681SAndroid Build Coastguard Worker bool HasZeroPointerIndex = false;
1617*9880d681SAndroid Build Coastguard Worker if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1618*9880d681SAndroid Build Coastguard Worker HasZeroPointerIndex = C->isZero();
1619*9880d681SAndroid Build Coastguard Worker
1620*9880d681SAndroid Build Coastguard Worker // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1621*9880d681SAndroid Build Coastguard Worker // into : GEP [10 x i8]* X, i32 0, ...
1622*9880d681SAndroid Build Coastguard Worker //
1623*9880d681SAndroid Build Coastguard Worker // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1624*9880d681SAndroid Build Coastguard Worker // into : GEP i8* X, ...
1625*9880d681SAndroid Build Coastguard Worker //
1626*9880d681SAndroid Build Coastguard Worker // This occurs when the program declares an array extern like "int X[];"
1627*9880d681SAndroid Build Coastguard Worker if (HasZeroPointerIndex) {
1628*9880d681SAndroid Build Coastguard Worker if (ArrayType *CATy =
1629*9880d681SAndroid Build Coastguard Worker dyn_cast<ArrayType>(GEP.getSourceElementType())) {
1630*9880d681SAndroid Build Coastguard Worker // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1631*9880d681SAndroid Build Coastguard Worker if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1632*9880d681SAndroid Build Coastguard Worker // -> GEP i8* X, ...
1633*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1634*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *Res = GetElementPtrInst::Create(
1635*9880d681SAndroid Build Coastguard Worker StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1636*9880d681SAndroid Build Coastguard Worker Res->setIsInBounds(GEP.isInBounds());
1637*9880d681SAndroid Build Coastguard Worker if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1638*9880d681SAndroid Build Coastguard Worker return Res;
1639*9880d681SAndroid Build Coastguard Worker // Insert Res, and create an addrspacecast.
1640*9880d681SAndroid Build Coastguard Worker // e.g.,
1641*9880d681SAndroid Build Coastguard Worker // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1642*9880d681SAndroid Build Coastguard Worker // ->
1643*9880d681SAndroid Build Coastguard Worker // %0 = GEP i8 addrspace(1)* X, ...
1644*9880d681SAndroid Build Coastguard Worker // addrspacecast i8 addrspace(1)* %0 to i8*
1645*9880d681SAndroid Build Coastguard Worker return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1646*9880d681SAndroid Build Coastguard Worker }
1647*9880d681SAndroid Build Coastguard Worker
1648*9880d681SAndroid Build Coastguard Worker if (ArrayType *XATy =
1649*9880d681SAndroid Build Coastguard Worker dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1650*9880d681SAndroid Build Coastguard Worker // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1651*9880d681SAndroid Build Coastguard Worker if (CATy->getElementType() == XATy->getElementType()) {
1652*9880d681SAndroid Build Coastguard Worker // -> GEP [10 x i8]* X, i32 0, ...
1653*9880d681SAndroid Build Coastguard Worker // At this point, we know that the cast source type is a pointer
1654*9880d681SAndroid Build Coastguard Worker // to an array of the same type as the destination pointer
1655*9880d681SAndroid Build Coastguard Worker // array. Because the array type is never stepped over (there
1656*9880d681SAndroid Build Coastguard Worker // is a leading zero) we can fold the cast into this GEP.
1657*9880d681SAndroid Build Coastguard Worker if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1658*9880d681SAndroid Build Coastguard Worker GEP.setOperand(0, StrippedPtr);
1659*9880d681SAndroid Build Coastguard Worker GEP.setSourceElementType(XATy);
1660*9880d681SAndroid Build Coastguard Worker return &GEP;
1661*9880d681SAndroid Build Coastguard Worker }
1662*9880d681SAndroid Build Coastguard Worker // Cannot replace the base pointer directly because StrippedPtr's
1663*9880d681SAndroid Build Coastguard Worker // address space is different. Instead, create a new GEP followed by
1664*9880d681SAndroid Build Coastguard Worker // an addrspacecast.
1665*9880d681SAndroid Build Coastguard Worker // e.g.,
1666*9880d681SAndroid Build Coastguard Worker // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1667*9880d681SAndroid Build Coastguard Worker // i32 0, ...
1668*9880d681SAndroid Build Coastguard Worker // ->
1669*9880d681SAndroid Build Coastguard Worker // %0 = GEP [10 x i8] addrspace(1)* X, ...
1670*9880d681SAndroid Build Coastguard Worker // addrspacecast i8 addrspace(1)* %0 to i8*
1671*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1672*9880d681SAndroid Build Coastguard Worker Value *NewGEP = GEP.isInBounds()
1673*9880d681SAndroid Build Coastguard Worker ? Builder->CreateInBoundsGEP(
1674*9880d681SAndroid Build Coastguard Worker nullptr, StrippedPtr, Idx, GEP.getName())
1675*9880d681SAndroid Build Coastguard Worker : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1676*9880d681SAndroid Build Coastguard Worker GEP.getName());
1677*9880d681SAndroid Build Coastguard Worker return new AddrSpaceCastInst(NewGEP, GEP.getType());
1678*9880d681SAndroid Build Coastguard Worker }
1679*9880d681SAndroid Build Coastguard Worker }
1680*9880d681SAndroid Build Coastguard Worker }
1681*9880d681SAndroid Build Coastguard Worker } else if (GEP.getNumOperands() == 2) {
1682*9880d681SAndroid Build Coastguard Worker // Transform things like:
1683*9880d681SAndroid Build Coastguard Worker // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1684*9880d681SAndroid Build Coastguard Worker // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1685*9880d681SAndroid Build Coastguard Worker Type *SrcElTy = StrippedPtrTy->getElementType();
1686*9880d681SAndroid Build Coastguard Worker Type *ResElTy = GEP.getSourceElementType();
1687*9880d681SAndroid Build Coastguard Worker if (SrcElTy->isArrayTy() &&
1688*9880d681SAndroid Build Coastguard Worker DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1689*9880d681SAndroid Build Coastguard Worker DL.getTypeAllocSize(ResElTy)) {
1690*9880d681SAndroid Build Coastguard Worker Type *IdxType = DL.getIntPtrType(GEP.getType());
1691*9880d681SAndroid Build Coastguard Worker Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1692*9880d681SAndroid Build Coastguard Worker Value *NewGEP =
1693*9880d681SAndroid Build Coastguard Worker GEP.isInBounds()
1694*9880d681SAndroid Build Coastguard Worker ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1695*9880d681SAndroid Build Coastguard Worker GEP.getName())
1696*9880d681SAndroid Build Coastguard Worker : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1697*9880d681SAndroid Build Coastguard Worker
1698*9880d681SAndroid Build Coastguard Worker // V and GEP are both pointer types --> BitCast
1699*9880d681SAndroid Build Coastguard Worker return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1700*9880d681SAndroid Build Coastguard Worker GEP.getType());
1701*9880d681SAndroid Build Coastguard Worker }
1702*9880d681SAndroid Build Coastguard Worker
1703*9880d681SAndroid Build Coastguard Worker // Transform things like:
1704*9880d681SAndroid Build Coastguard Worker // %V = mul i64 %N, 4
1705*9880d681SAndroid Build Coastguard Worker // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1706*9880d681SAndroid Build Coastguard Worker // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1707*9880d681SAndroid Build Coastguard Worker if (ResElTy->isSized() && SrcElTy->isSized()) {
1708*9880d681SAndroid Build Coastguard Worker // Check that changing the type amounts to dividing the index by a scale
1709*9880d681SAndroid Build Coastguard Worker // factor.
1710*9880d681SAndroid Build Coastguard Worker uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1711*9880d681SAndroid Build Coastguard Worker uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1712*9880d681SAndroid Build Coastguard Worker if (ResSize && SrcSize % ResSize == 0) {
1713*9880d681SAndroid Build Coastguard Worker Value *Idx = GEP.getOperand(1);
1714*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1715*9880d681SAndroid Build Coastguard Worker uint64_t Scale = SrcSize / ResSize;
1716*9880d681SAndroid Build Coastguard Worker
1717*9880d681SAndroid Build Coastguard Worker // Earlier transforms ensure that the index has type IntPtrType, which
1718*9880d681SAndroid Build Coastguard Worker // considerably simplifies the logic by eliminating implicit casts.
1719*9880d681SAndroid Build Coastguard Worker assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1720*9880d681SAndroid Build Coastguard Worker "Index not cast to pointer width?");
1721*9880d681SAndroid Build Coastguard Worker
1722*9880d681SAndroid Build Coastguard Worker bool NSW;
1723*9880d681SAndroid Build Coastguard Worker if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1724*9880d681SAndroid Build Coastguard Worker // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1725*9880d681SAndroid Build Coastguard Worker // If the multiplication NewIdx * Scale may overflow then the new
1726*9880d681SAndroid Build Coastguard Worker // GEP may not be "inbounds".
1727*9880d681SAndroid Build Coastguard Worker Value *NewGEP =
1728*9880d681SAndroid Build Coastguard Worker GEP.isInBounds() && NSW
1729*9880d681SAndroid Build Coastguard Worker ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1730*9880d681SAndroid Build Coastguard Worker GEP.getName())
1731*9880d681SAndroid Build Coastguard Worker : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1732*9880d681SAndroid Build Coastguard Worker GEP.getName());
1733*9880d681SAndroid Build Coastguard Worker
1734*9880d681SAndroid Build Coastguard Worker // The NewGEP must be pointer typed, so must the old one -> BitCast
1735*9880d681SAndroid Build Coastguard Worker return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1736*9880d681SAndroid Build Coastguard Worker GEP.getType());
1737*9880d681SAndroid Build Coastguard Worker }
1738*9880d681SAndroid Build Coastguard Worker }
1739*9880d681SAndroid Build Coastguard Worker }
1740*9880d681SAndroid Build Coastguard Worker
1741*9880d681SAndroid Build Coastguard Worker // Similarly, transform things like:
1742*9880d681SAndroid Build Coastguard Worker // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1743*9880d681SAndroid Build Coastguard Worker // (where tmp = 8*tmp2) into:
1744*9880d681SAndroid Build Coastguard Worker // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1745*9880d681SAndroid Build Coastguard Worker if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1746*9880d681SAndroid Build Coastguard Worker // Check that changing to the array element type amounts to dividing the
1747*9880d681SAndroid Build Coastguard Worker // index by a scale factor.
1748*9880d681SAndroid Build Coastguard Worker uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1749*9880d681SAndroid Build Coastguard Worker uint64_t ArrayEltSize =
1750*9880d681SAndroid Build Coastguard Worker DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1751*9880d681SAndroid Build Coastguard Worker if (ResSize && ArrayEltSize % ResSize == 0) {
1752*9880d681SAndroid Build Coastguard Worker Value *Idx = GEP.getOperand(1);
1753*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1754*9880d681SAndroid Build Coastguard Worker uint64_t Scale = ArrayEltSize / ResSize;
1755*9880d681SAndroid Build Coastguard Worker
1756*9880d681SAndroid Build Coastguard Worker // Earlier transforms ensure that the index has type IntPtrType, which
1757*9880d681SAndroid Build Coastguard Worker // considerably simplifies the logic by eliminating implicit casts.
1758*9880d681SAndroid Build Coastguard Worker assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1759*9880d681SAndroid Build Coastguard Worker "Index not cast to pointer width?");
1760*9880d681SAndroid Build Coastguard Worker
1761*9880d681SAndroid Build Coastguard Worker bool NSW;
1762*9880d681SAndroid Build Coastguard Worker if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1763*9880d681SAndroid Build Coastguard Worker // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1764*9880d681SAndroid Build Coastguard Worker // If the multiplication NewIdx * Scale may overflow then the new
1765*9880d681SAndroid Build Coastguard Worker // GEP may not be "inbounds".
1766*9880d681SAndroid Build Coastguard Worker Value *Off[2] = {
1767*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1768*9880d681SAndroid Build Coastguard Worker NewIdx};
1769*9880d681SAndroid Build Coastguard Worker
1770*9880d681SAndroid Build Coastguard Worker Value *NewGEP = GEP.isInBounds() && NSW
1771*9880d681SAndroid Build Coastguard Worker ? Builder->CreateInBoundsGEP(
1772*9880d681SAndroid Build Coastguard Worker SrcElTy, StrippedPtr, Off, GEP.getName())
1773*9880d681SAndroid Build Coastguard Worker : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1774*9880d681SAndroid Build Coastguard Worker GEP.getName());
1775*9880d681SAndroid Build Coastguard Worker // The NewGEP must be pointer typed, so must the old one -> BitCast
1776*9880d681SAndroid Build Coastguard Worker return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1777*9880d681SAndroid Build Coastguard Worker GEP.getType());
1778*9880d681SAndroid Build Coastguard Worker }
1779*9880d681SAndroid Build Coastguard Worker }
1780*9880d681SAndroid Build Coastguard Worker }
1781*9880d681SAndroid Build Coastguard Worker }
1782*9880d681SAndroid Build Coastguard Worker }
1783*9880d681SAndroid Build Coastguard Worker
1784*9880d681SAndroid Build Coastguard Worker // addrspacecast between types is canonicalized as a bitcast, then an
1785*9880d681SAndroid Build Coastguard Worker // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1786*9880d681SAndroid Build Coastguard Worker // through the addrspacecast.
1787*9880d681SAndroid Build Coastguard Worker if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1788*9880d681SAndroid Build Coastguard Worker // X = bitcast A addrspace(1)* to B addrspace(1)*
1789*9880d681SAndroid Build Coastguard Worker // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1790*9880d681SAndroid Build Coastguard Worker // Z = gep Y, <...constant indices...>
1791*9880d681SAndroid Build Coastguard Worker // Into an addrspacecasted GEP of the struct.
1792*9880d681SAndroid Build Coastguard Worker if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1793*9880d681SAndroid Build Coastguard Worker PtrOp = BC;
1794*9880d681SAndroid Build Coastguard Worker }
1795*9880d681SAndroid Build Coastguard Worker
1796*9880d681SAndroid Build Coastguard Worker /// See if we can simplify:
1797*9880d681SAndroid Build Coastguard Worker /// X = bitcast A* to B*
1798*9880d681SAndroid Build Coastguard Worker /// Y = gep X, <...constant indices...>
1799*9880d681SAndroid Build Coastguard Worker /// into a gep of the original struct. This is important for SROA and alias
1800*9880d681SAndroid Build Coastguard Worker /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1801*9880d681SAndroid Build Coastguard Worker if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1802*9880d681SAndroid Build Coastguard Worker Value *Operand = BCI->getOperand(0);
1803*9880d681SAndroid Build Coastguard Worker PointerType *OpType = cast<PointerType>(Operand->getType());
1804*9880d681SAndroid Build Coastguard Worker unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1805*9880d681SAndroid Build Coastguard Worker APInt Offset(OffsetBits, 0);
1806*9880d681SAndroid Build Coastguard Worker if (!isa<BitCastInst>(Operand) &&
1807*9880d681SAndroid Build Coastguard Worker GEP.accumulateConstantOffset(DL, Offset)) {
1808*9880d681SAndroid Build Coastguard Worker
1809*9880d681SAndroid Build Coastguard Worker // If this GEP instruction doesn't move the pointer, just replace the GEP
1810*9880d681SAndroid Build Coastguard Worker // with a bitcast of the real input to the dest type.
1811*9880d681SAndroid Build Coastguard Worker if (!Offset) {
1812*9880d681SAndroid Build Coastguard Worker // If the bitcast is of an allocation, and the allocation will be
1813*9880d681SAndroid Build Coastguard Worker // converted to match the type of the cast, don't touch this.
1814*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1815*9880d681SAndroid Build Coastguard Worker // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1816*9880d681SAndroid Build Coastguard Worker if (Instruction *I = visitBitCast(*BCI)) {
1817*9880d681SAndroid Build Coastguard Worker if (I != BCI) {
1818*9880d681SAndroid Build Coastguard Worker I->takeName(BCI);
1819*9880d681SAndroid Build Coastguard Worker BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1820*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*BCI, I);
1821*9880d681SAndroid Build Coastguard Worker }
1822*9880d681SAndroid Build Coastguard Worker return &GEP;
1823*9880d681SAndroid Build Coastguard Worker }
1824*9880d681SAndroid Build Coastguard Worker }
1825*9880d681SAndroid Build Coastguard Worker
1826*9880d681SAndroid Build Coastguard Worker if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1827*9880d681SAndroid Build Coastguard Worker return new AddrSpaceCastInst(Operand, GEP.getType());
1828*9880d681SAndroid Build Coastguard Worker return new BitCastInst(Operand, GEP.getType());
1829*9880d681SAndroid Build Coastguard Worker }
1830*9880d681SAndroid Build Coastguard Worker
1831*9880d681SAndroid Build Coastguard Worker // Otherwise, if the offset is non-zero, we need to find out if there is a
1832*9880d681SAndroid Build Coastguard Worker // field at Offset in 'A's type. If so, we can pull the cast through the
1833*9880d681SAndroid Build Coastguard Worker // GEP.
1834*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 8> NewIndices;
1835*9880d681SAndroid Build Coastguard Worker if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1836*9880d681SAndroid Build Coastguard Worker Value *NGEP =
1837*9880d681SAndroid Build Coastguard Worker GEP.isInBounds()
1838*9880d681SAndroid Build Coastguard Worker ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1839*9880d681SAndroid Build Coastguard Worker : Builder->CreateGEP(nullptr, Operand, NewIndices);
1840*9880d681SAndroid Build Coastguard Worker
1841*9880d681SAndroid Build Coastguard Worker if (NGEP->getType() == GEP.getType())
1842*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(GEP, NGEP);
1843*9880d681SAndroid Build Coastguard Worker NGEP->takeName(&GEP);
1844*9880d681SAndroid Build Coastguard Worker
1845*9880d681SAndroid Build Coastguard Worker if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1846*9880d681SAndroid Build Coastguard Worker return new AddrSpaceCastInst(NGEP, GEP.getType());
1847*9880d681SAndroid Build Coastguard Worker return new BitCastInst(NGEP, GEP.getType());
1848*9880d681SAndroid Build Coastguard Worker }
1849*9880d681SAndroid Build Coastguard Worker }
1850*9880d681SAndroid Build Coastguard Worker }
1851*9880d681SAndroid Build Coastguard Worker
1852*9880d681SAndroid Build Coastguard Worker return nullptr;
1853*9880d681SAndroid Build Coastguard Worker }
1854*9880d681SAndroid Build Coastguard Worker
isNeverEqualToUnescapedAlloc(Value * V,const TargetLibraryInfo * TLI,Instruction * AI)1855*9880d681SAndroid Build Coastguard Worker static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
1856*9880d681SAndroid Build Coastguard Worker Instruction *AI) {
1857*9880d681SAndroid Build Coastguard Worker if (isa<ConstantPointerNull>(V))
1858*9880d681SAndroid Build Coastguard Worker return true;
1859*9880d681SAndroid Build Coastguard Worker if (auto *LI = dyn_cast<LoadInst>(V))
1860*9880d681SAndroid Build Coastguard Worker return isa<GlobalVariable>(LI->getPointerOperand());
1861*9880d681SAndroid Build Coastguard Worker // Two distinct allocations will never be equal.
1862*9880d681SAndroid Build Coastguard Worker // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
1863*9880d681SAndroid Build Coastguard Worker // through bitcasts of V can cause
1864*9880d681SAndroid Build Coastguard Worker // the result statement below to be true, even when AI and V (ex:
1865*9880d681SAndroid Build Coastguard Worker // i8* ->i32* ->i8* of AI) are the same allocations.
1866*9880d681SAndroid Build Coastguard Worker return isAllocLikeFn(V, TLI) && V != AI;
1867*9880d681SAndroid Build Coastguard Worker }
1868*9880d681SAndroid Build Coastguard Worker
1869*9880d681SAndroid Build Coastguard Worker static bool
isAllocSiteRemovable(Instruction * AI,SmallVectorImpl<WeakVH> & Users,const TargetLibraryInfo * TLI)1870*9880d681SAndroid Build Coastguard Worker isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1871*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
1872*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction*, 4> Worklist;
1873*9880d681SAndroid Build Coastguard Worker Worklist.push_back(AI);
1874*9880d681SAndroid Build Coastguard Worker
1875*9880d681SAndroid Build Coastguard Worker do {
1876*9880d681SAndroid Build Coastguard Worker Instruction *PI = Worklist.pop_back_val();
1877*9880d681SAndroid Build Coastguard Worker for (User *U : PI->users()) {
1878*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(U);
1879*9880d681SAndroid Build Coastguard Worker switch (I->getOpcode()) {
1880*9880d681SAndroid Build Coastguard Worker default:
1881*9880d681SAndroid Build Coastguard Worker // Give up the moment we see something we can't handle.
1882*9880d681SAndroid Build Coastguard Worker return false;
1883*9880d681SAndroid Build Coastguard Worker
1884*9880d681SAndroid Build Coastguard Worker case Instruction::BitCast:
1885*9880d681SAndroid Build Coastguard Worker case Instruction::GetElementPtr:
1886*9880d681SAndroid Build Coastguard Worker Users.emplace_back(I);
1887*9880d681SAndroid Build Coastguard Worker Worklist.push_back(I);
1888*9880d681SAndroid Build Coastguard Worker continue;
1889*9880d681SAndroid Build Coastguard Worker
1890*9880d681SAndroid Build Coastguard Worker case Instruction::ICmp: {
1891*9880d681SAndroid Build Coastguard Worker ICmpInst *ICI = cast<ICmpInst>(I);
1892*9880d681SAndroid Build Coastguard Worker // We can fold eq/ne comparisons with null to false/true, respectively.
1893*9880d681SAndroid Build Coastguard Worker // We also fold comparisons in some conditions provided the alloc has
1894*9880d681SAndroid Build Coastguard Worker // not escaped (see isNeverEqualToUnescapedAlloc).
1895*9880d681SAndroid Build Coastguard Worker if (!ICI->isEquality())
1896*9880d681SAndroid Build Coastguard Worker return false;
1897*9880d681SAndroid Build Coastguard Worker unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
1898*9880d681SAndroid Build Coastguard Worker if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
1899*9880d681SAndroid Build Coastguard Worker return false;
1900*9880d681SAndroid Build Coastguard Worker Users.emplace_back(I);
1901*9880d681SAndroid Build Coastguard Worker continue;
1902*9880d681SAndroid Build Coastguard Worker }
1903*9880d681SAndroid Build Coastguard Worker
1904*9880d681SAndroid Build Coastguard Worker case Instruction::Call:
1905*9880d681SAndroid Build Coastguard Worker // Ignore no-op and store intrinsics.
1906*9880d681SAndroid Build Coastguard Worker if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1907*9880d681SAndroid Build Coastguard Worker switch (II->getIntrinsicID()) {
1908*9880d681SAndroid Build Coastguard Worker default:
1909*9880d681SAndroid Build Coastguard Worker return false;
1910*9880d681SAndroid Build Coastguard Worker
1911*9880d681SAndroid Build Coastguard Worker case Intrinsic::memmove:
1912*9880d681SAndroid Build Coastguard Worker case Intrinsic::memcpy:
1913*9880d681SAndroid Build Coastguard Worker case Intrinsic::memset: {
1914*9880d681SAndroid Build Coastguard Worker MemIntrinsic *MI = cast<MemIntrinsic>(II);
1915*9880d681SAndroid Build Coastguard Worker if (MI->isVolatile() || MI->getRawDest() != PI)
1916*9880d681SAndroid Build Coastguard Worker return false;
1917*9880d681SAndroid Build Coastguard Worker }
1918*9880d681SAndroid Build Coastguard Worker // fall through
1919*9880d681SAndroid Build Coastguard Worker case Intrinsic::dbg_declare:
1920*9880d681SAndroid Build Coastguard Worker case Intrinsic::dbg_value:
1921*9880d681SAndroid Build Coastguard Worker case Intrinsic::invariant_start:
1922*9880d681SAndroid Build Coastguard Worker case Intrinsic::invariant_end:
1923*9880d681SAndroid Build Coastguard Worker case Intrinsic::lifetime_start:
1924*9880d681SAndroid Build Coastguard Worker case Intrinsic::lifetime_end:
1925*9880d681SAndroid Build Coastguard Worker case Intrinsic::objectsize:
1926*9880d681SAndroid Build Coastguard Worker Users.emplace_back(I);
1927*9880d681SAndroid Build Coastguard Worker continue;
1928*9880d681SAndroid Build Coastguard Worker }
1929*9880d681SAndroid Build Coastguard Worker }
1930*9880d681SAndroid Build Coastguard Worker
1931*9880d681SAndroid Build Coastguard Worker if (isFreeCall(I, TLI)) {
1932*9880d681SAndroid Build Coastguard Worker Users.emplace_back(I);
1933*9880d681SAndroid Build Coastguard Worker continue;
1934*9880d681SAndroid Build Coastguard Worker }
1935*9880d681SAndroid Build Coastguard Worker return false;
1936*9880d681SAndroid Build Coastguard Worker
1937*9880d681SAndroid Build Coastguard Worker case Instruction::Store: {
1938*9880d681SAndroid Build Coastguard Worker StoreInst *SI = cast<StoreInst>(I);
1939*9880d681SAndroid Build Coastguard Worker if (SI->isVolatile() || SI->getPointerOperand() != PI)
1940*9880d681SAndroid Build Coastguard Worker return false;
1941*9880d681SAndroid Build Coastguard Worker Users.emplace_back(I);
1942*9880d681SAndroid Build Coastguard Worker continue;
1943*9880d681SAndroid Build Coastguard Worker }
1944*9880d681SAndroid Build Coastguard Worker }
1945*9880d681SAndroid Build Coastguard Worker llvm_unreachable("missing a return?");
1946*9880d681SAndroid Build Coastguard Worker }
1947*9880d681SAndroid Build Coastguard Worker } while (!Worklist.empty());
1948*9880d681SAndroid Build Coastguard Worker return true;
1949*9880d681SAndroid Build Coastguard Worker }
1950*9880d681SAndroid Build Coastguard Worker
visitAllocSite(Instruction & MI)1951*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1952*9880d681SAndroid Build Coastguard Worker // If we have a malloc call which is only used in any amount of comparisons
1953*9880d681SAndroid Build Coastguard Worker // to null and free calls, delete the calls and replace the comparisons with
1954*9880d681SAndroid Build Coastguard Worker // true or false as appropriate.
1955*9880d681SAndroid Build Coastguard Worker SmallVector<WeakVH, 64> Users;
1956*9880d681SAndroid Build Coastguard Worker if (isAllocSiteRemovable(&MI, Users, TLI)) {
1957*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1958*9880d681SAndroid Build Coastguard Worker // Lowering all @llvm.objectsize calls first because they may
1959*9880d681SAndroid Build Coastguard Worker // use a bitcast/GEP of the alloca we are removing.
1960*9880d681SAndroid Build Coastguard Worker if (!Users[i])
1961*9880d681SAndroid Build Coastguard Worker continue;
1962*9880d681SAndroid Build Coastguard Worker
1963*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(&*Users[i]);
1964*9880d681SAndroid Build Coastguard Worker
1965*9880d681SAndroid Build Coastguard Worker if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1966*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::objectsize) {
1967*9880d681SAndroid Build Coastguard Worker uint64_t Size;
1968*9880d681SAndroid Build Coastguard Worker if (!getObjectSize(II->getArgOperand(0), Size, DL, TLI)) {
1969*9880d681SAndroid Build Coastguard Worker ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1970*9880d681SAndroid Build Coastguard Worker Size = CI->isZero() ? -1ULL : 0;
1971*9880d681SAndroid Build Coastguard Worker }
1972*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*I, ConstantInt::get(I->getType(), Size));
1973*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*I);
1974*9880d681SAndroid Build Coastguard Worker Users[i] = nullptr; // Skip examining in the next loop.
1975*9880d681SAndroid Build Coastguard Worker }
1976*9880d681SAndroid Build Coastguard Worker }
1977*9880d681SAndroid Build Coastguard Worker }
1978*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1979*9880d681SAndroid Build Coastguard Worker if (!Users[i])
1980*9880d681SAndroid Build Coastguard Worker continue;
1981*9880d681SAndroid Build Coastguard Worker
1982*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(&*Users[i]);
1983*9880d681SAndroid Build Coastguard Worker
1984*9880d681SAndroid Build Coastguard Worker if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1985*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*C,
1986*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt1Ty(C->getContext()),
1987*9880d681SAndroid Build Coastguard Worker C->isFalseWhenEqual()));
1988*9880d681SAndroid Build Coastguard Worker } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1989*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*I, UndefValue::get(I->getType()));
1990*9880d681SAndroid Build Coastguard Worker }
1991*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*I);
1992*9880d681SAndroid Build Coastguard Worker }
1993*9880d681SAndroid Build Coastguard Worker
1994*9880d681SAndroid Build Coastguard Worker if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1995*9880d681SAndroid Build Coastguard Worker // Replace invoke with a NOP intrinsic to maintain the original CFG
1996*9880d681SAndroid Build Coastguard Worker Module *M = II->getModule();
1997*9880d681SAndroid Build Coastguard Worker Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1998*9880d681SAndroid Build Coastguard Worker InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1999*9880d681SAndroid Build Coastguard Worker None, "", II->getParent());
2000*9880d681SAndroid Build Coastguard Worker }
2001*9880d681SAndroid Build Coastguard Worker return eraseInstFromFunction(MI);
2002*9880d681SAndroid Build Coastguard Worker }
2003*9880d681SAndroid Build Coastguard Worker return nullptr;
2004*9880d681SAndroid Build Coastguard Worker }
2005*9880d681SAndroid Build Coastguard Worker
2006*9880d681SAndroid Build Coastguard Worker /// \brief Move the call to free before a NULL test.
2007*9880d681SAndroid Build Coastguard Worker ///
2008*9880d681SAndroid Build Coastguard Worker /// Check if this free is accessed after its argument has been test
2009*9880d681SAndroid Build Coastguard Worker /// against NULL (property 0).
2010*9880d681SAndroid Build Coastguard Worker /// If yes, it is legal to move this call in its predecessor block.
2011*9880d681SAndroid Build Coastguard Worker ///
2012*9880d681SAndroid Build Coastguard Worker /// The move is performed only if the block containing the call to free
2013*9880d681SAndroid Build Coastguard Worker /// will be removed, i.e.:
2014*9880d681SAndroid Build Coastguard Worker /// 1. it has only one predecessor P, and P has two successors
2015*9880d681SAndroid Build Coastguard Worker /// 2. it contains the call and an unconditional branch
2016*9880d681SAndroid Build Coastguard Worker /// 3. its successor is the same as its predecessor's successor
2017*9880d681SAndroid Build Coastguard Worker ///
2018*9880d681SAndroid Build Coastguard Worker /// The profitability is out-of concern here and this function should
2019*9880d681SAndroid Build Coastguard Worker /// be called only if the caller knows this transformation would be
2020*9880d681SAndroid Build Coastguard Worker /// profitable (e.g., for code size).
2021*9880d681SAndroid Build Coastguard Worker static Instruction *
tryToMoveFreeBeforeNullTest(CallInst & FI)2022*9880d681SAndroid Build Coastguard Worker tryToMoveFreeBeforeNullTest(CallInst &FI) {
2023*9880d681SAndroid Build Coastguard Worker Value *Op = FI.getArgOperand(0);
2024*9880d681SAndroid Build Coastguard Worker BasicBlock *FreeInstrBB = FI.getParent();
2025*9880d681SAndroid Build Coastguard Worker BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2026*9880d681SAndroid Build Coastguard Worker
2027*9880d681SAndroid Build Coastguard Worker // Validate part of constraint #1: Only one predecessor
2028*9880d681SAndroid Build Coastguard Worker // FIXME: We can extend the number of predecessor, but in that case, we
2029*9880d681SAndroid Build Coastguard Worker // would duplicate the call to free in each predecessor and it may
2030*9880d681SAndroid Build Coastguard Worker // not be profitable even for code size.
2031*9880d681SAndroid Build Coastguard Worker if (!PredBB)
2032*9880d681SAndroid Build Coastguard Worker return nullptr;
2033*9880d681SAndroid Build Coastguard Worker
2034*9880d681SAndroid Build Coastguard Worker // Validate constraint #2: Does this block contains only the call to
2035*9880d681SAndroid Build Coastguard Worker // free and an unconditional branch?
2036*9880d681SAndroid Build Coastguard Worker // FIXME: We could check if we can speculate everything in the
2037*9880d681SAndroid Build Coastguard Worker // predecessor block
2038*9880d681SAndroid Build Coastguard Worker if (FreeInstrBB->size() != 2)
2039*9880d681SAndroid Build Coastguard Worker return nullptr;
2040*9880d681SAndroid Build Coastguard Worker BasicBlock *SuccBB;
2041*9880d681SAndroid Build Coastguard Worker if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2042*9880d681SAndroid Build Coastguard Worker return nullptr;
2043*9880d681SAndroid Build Coastguard Worker
2044*9880d681SAndroid Build Coastguard Worker // Validate the rest of constraint #1 by matching on the pred branch.
2045*9880d681SAndroid Build Coastguard Worker TerminatorInst *TI = PredBB->getTerminator();
2046*9880d681SAndroid Build Coastguard Worker BasicBlock *TrueBB, *FalseBB;
2047*9880d681SAndroid Build Coastguard Worker ICmpInst::Predicate Pred;
2048*9880d681SAndroid Build Coastguard Worker if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2049*9880d681SAndroid Build Coastguard Worker return nullptr;
2050*9880d681SAndroid Build Coastguard Worker if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2051*9880d681SAndroid Build Coastguard Worker return nullptr;
2052*9880d681SAndroid Build Coastguard Worker
2053*9880d681SAndroid Build Coastguard Worker // Validate constraint #3: Ensure the null case just falls through.
2054*9880d681SAndroid Build Coastguard Worker if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2055*9880d681SAndroid Build Coastguard Worker return nullptr;
2056*9880d681SAndroid Build Coastguard Worker assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2057*9880d681SAndroid Build Coastguard Worker "Broken CFG: missing edge from predecessor to successor");
2058*9880d681SAndroid Build Coastguard Worker
2059*9880d681SAndroid Build Coastguard Worker FI.moveBefore(TI);
2060*9880d681SAndroid Build Coastguard Worker return &FI;
2061*9880d681SAndroid Build Coastguard Worker }
2062*9880d681SAndroid Build Coastguard Worker
2063*9880d681SAndroid Build Coastguard Worker
visitFree(CallInst & FI)2064*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitFree(CallInst &FI) {
2065*9880d681SAndroid Build Coastguard Worker Value *Op = FI.getArgOperand(0);
2066*9880d681SAndroid Build Coastguard Worker
2067*9880d681SAndroid Build Coastguard Worker // free undef -> unreachable.
2068*9880d681SAndroid Build Coastguard Worker if (isa<UndefValue>(Op)) {
2069*9880d681SAndroid Build Coastguard Worker // Insert a new store to null because we cannot modify the CFG here.
2070*9880d681SAndroid Build Coastguard Worker Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2071*9880d681SAndroid Build Coastguard Worker UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2072*9880d681SAndroid Build Coastguard Worker return eraseInstFromFunction(FI);
2073*9880d681SAndroid Build Coastguard Worker }
2074*9880d681SAndroid Build Coastguard Worker
2075*9880d681SAndroid Build Coastguard Worker // If we have 'free null' delete the instruction. This can happen in stl code
2076*9880d681SAndroid Build Coastguard Worker // when lots of inlining happens.
2077*9880d681SAndroid Build Coastguard Worker if (isa<ConstantPointerNull>(Op))
2078*9880d681SAndroid Build Coastguard Worker return eraseInstFromFunction(FI);
2079*9880d681SAndroid Build Coastguard Worker
2080*9880d681SAndroid Build Coastguard Worker // If we optimize for code size, try to move the call to free before the null
2081*9880d681SAndroid Build Coastguard Worker // test so that simplify cfg can remove the empty block and dead code
2082*9880d681SAndroid Build Coastguard Worker // elimination the branch. I.e., helps to turn something like:
2083*9880d681SAndroid Build Coastguard Worker // if (foo) free(foo);
2084*9880d681SAndroid Build Coastguard Worker // into
2085*9880d681SAndroid Build Coastguard Worker // free(foo);
2086*9880d681SAndroid Build Coastguard Worker if (MinimizeSize)
2087*9880d681SAndroid Build Coastguard Worker if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2088*9880d681SAndroid Build Coastguard Worker return I;
2089*9880d681SAndroid Build Coastguard Worker
2090*9880d681SAndroid Build Coastguard Worker return nullptr;
2091*9880d681SAndroid Build Coastguard Worker }
2092*9880d681SAndroid Build Coastguard Worker
visitReturnInst(ReturnInst & RI)2093*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2094*9880d681SAndroid Build Coastguard Worker if (RI.getNumOperands() == 0) // ret void
2095*9880d681SAndroid Build Coastguard Worker return nullptr;
2096*9880d681SAndroid Build Coastguard Worker
2097*9880d681SAndroid Build Coastguard Worker Value *ResultOp = RI.getOperand(0);
2098*9880d681SAndroid Build Coastguard Worker Type *VTy = ResultOp->getType();
2099*9880d681SAndroid Build Coastguard Worker if (!VTy->isIntegerTy())
2100*9880d681SAndroid Build Coastguard Worker return nullptr;
2101*9880d681SAndroid Build Coastguard Worker
2102*9880d681SAndroid Build Coastguard Worker // There might be assume intrinsics dominating this return that completely
2103*9880d681SAndroid Build Coastguard Worker // determine the value. If so, constant fold it.
2104*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2105*9880d681SAndroid Build Coastguard Worker APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2106*9880d681SAndroid Build Coastguard Worker computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2107*9880d681SAndroid Build Coastguard Worker if ((KnownZero|KnownOne).isAllOnesValue())
2108*9880d681SAndroid Build Coastguard Worker RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2109*9880d681SAndroid Build Coastguard Worker
2110*9880d681SAndroid Build Coastguard Worker return nullptr;
2111*9880d681SAndroid Build Coastguard Worker }
2112*9880d681SAndroid Build Coastguard Worker
visitBranchInst(BranchInst & BI)2113*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2114*9880d681SAndroid Build Coastguard Worker // Change br (not X), label True, label False to: br X, label False, True
2115*9880d681SAndroid Build Coastguard Worker Value *X = nullptr;
2116*9880d681SAndroid Build Coastguard Worker BasicBlock *TrueDest;
2117*9880d681SAndroid Build Coastguard Worker BasicBlock *FalseDest;
2118*9880d681SAndroid Build Coastguard Worker if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2119*9880d681SAndroid Build Coastguard Worker !isa<Constant>(X)) {
2120*9880d681SAndroid Build Coastguard Worker // Swap Destinations and condition...
2121*9880d681SAndroid Build Coastguard Worker BI.setCondition(X);
2122*9880d681SAndroid Build Coastguard Worker BI.swapSuccessors();
2123*9880d681SAndroid Build Coastguard Worker return &BI;
2124*9880d681SAndroid Build Coastguard Worker }
2125*9880d681SAndroid Build Coastguard Worker
2126*9880d681SAndroid Build Coastguard Worker // If the condition is irrelevant, remove the use so that other
2127*9880d681SAndroid Build Coastguard Worker // transforms on the condition become more effective.
2128*9880d681SAndroid Build Coastguard Worker if (BI.isConditional() &&
2129*9880d681SAndroid Build Coastguard Worker BI.getSuccessor(0) == BI.getSuccessor(1) &&
2130*9880d681SAndroid Build Coastguard Worker !isa<UndefValue>(BI.getCondition())) {
2131*9880d681SAndroid Build Coastguard Worker BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2132*9880d681SAndroid Build Coastguard Worker return &BI;
2133*9880d681SAndroid Build Coastguard Worker }
2134*9880d681SAndroid Build Coastguard Worker
2135*9880d681SAndroid Build Coastguard Worker // Canonicalize fcmp_one -> fcmp_oeq
2136*9880d681SAndroid Build Coastguard Worker FCmpInst::Predicate FPred; Value *Y;
2137*9880d681SAndroid Build Coastguard Worker if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2138*9880d681SAndroid Build Coastguard Worker TrueDest, FalseDest)) &&
2139*9880d681SAndroid Build Coastguard Worker BI.getCondition()->hasOneUse())
2140*9880d681SAndroid Build Coastguard Worker if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2141*9880d681SAndroid Build Coastguard Worker FPred == FCmpInst::FCMP_OGE) {
2142*9880d681SAndroid Build Coastguard Worker FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2143*9880d681SAndroid Build Coastguard Worker Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2144*9880d681SAndroid Build Coastguard Worker
2145*9880d681SAndroid Build Coastguard Worker // Swap Destinations and condition.
2146*9880d681SAndroid Build Coastguard Worker BI.swapSuccessors();
2147*9880d681SAndroid Build Coastguard Worker Worklist.Add(Cond);
2148*9880d681SAndroid Build Coastguard Worker return &BI;
2149*9880d681SAndroid Build Coastguard Worker }
2150*9880d681SAndroid Build Coastguard Worker
2151*9880d681SAndroid Build Coastguard Worker // Canonicalize icmp_ne -> icmp_eq
2152*9880d681SAndroid Build Coastguard Worker ICmpInst::Predicate IPred;
2153*9880d681SAndroid Build Coastguard Worker if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2154*9880d681SAndroid Build Coastguard Worker TrueDest, FalseDest)) &&
2155*9880d681SAndroid Build Coastguard Worker BI.getCondition()->hasOneUse())
2156*9880d681SAndroid Build Coastguard Worker if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2157*9880d681SAndroid Build Coastguard Worker IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2158*9880d681SAndroid Build Coastguard Worker IPred == ICmpInst::ICMP_SGE) {
2159*9880d681SAndroid Build Coastguard Worker ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2160*9880d681SAndroid Build Coastguard Worker Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2161*9880d681SAndroid Build Coastguard Worker // Swap Destinations and condition.
2162*9880d681SAndroid Build Coastguard Worker BI.swapSuccessors();
2163*9880d681SAndroid Build Coastguard Worker Worklist.Add(Cond);
2164*9880d681SAndroid Build Coastguard Worker return &BI;
2165*9880d681SAndroid Build Coastguard Worker }
2166*9880d681SAndroid Build Coastguard Worker
2167*9880d681SAndroid Build Coastguard Worker return nullptr;
2168*9880d681SAndroid Build Coastguard Worker }
2169*9880d681SAndroid Build Coastguard Worker
visitSwitchInst(SwitchInst & SI)2170*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2171*9880d681SAndroid Build Coastguard Worker Value *Cond = SI.getCondition();
2172*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2173*9880d681SAndroid Build Coastguard Worker APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2174*9880d681SAndroid Build Coastguard Worker computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
2175*9880d681SAndroid Build Coastguard Worker unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2176*9880d681SAndroid Build Coastguard Worker unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2177*9880d681SAndroid Build Coastguard Worker
2178*9880d681SAndroid Build Coastguard Worker // Compute the number of leading bits we can ignore.
2179*9880d681SAndroid Build Coastguard Worker // TODO: A better way to determine this would use ComputeNumSignBits().
2180*9880d681SAndroid Build Coastguard Worker for (auto &C : SI.cases()) {
2181*9880d681SAndroid Build Coastguard Worker LeadingKnownZeros = std::min(
2182*9880d681SAndroid Build Coastguard Worker LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2183*9880d681SAndroid Build Coastguard Worker LeadingKnownOnes = std::min(
2184*9880d681SAndroid Build Coastguard Worker LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2185*9880d681SAndroid Build Coastguard Worker }
2186*9880d681SAndroid Build Coastguard Worker
2187*9880d681SAndroid Build Coastguard Worker unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2188*9880d681SAndroid Build Coastguard Worker
2189*9880d681SAndroid Build Coastguard Worker // Shrink the condition operand if the new type is smaller than the old type.
2190*9880d681SAndroid Build Coastguard Worker // This may produce a non-standard type for the switch, but that's ok because
2191*9880d681SAndroid Build Coastguard Worker // the backend should extend back to a legal type for the target.
2192*9880d681SAndroid Build Coastguard Worker bool TruncCond = false;
2193*9880d681SAndroid Build Coastguard Worker if (NewWidth > 0 && NewWidth < BitWidth) {
2194*9880d681SAndroid Build Coastguard Worker TruncCond = true;
2195*9880d681SAndroid Build Coastguard Worker IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2196*9880d681SAndroid Build Coastguard Worker Builder->SetInsertPoint(&SI);
2197*9880d681SAndroid Build Coastguard Worker Value *NewCond = Builder->CreateTrunc(Cond, Ty, "trunc");
2198*9880d681SAndroid Build Coastguard Worker SI.setCondition(NewCond);
2199*9880d681SAndroid Build Coastguard Worker
2200*9880d681SAndroid Build Coastguard Worker for (auto &C : SI.cases())
2201*9880d681SAndroid Build Coastguard Worker static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2202*9880d681SAndroid Build Coastguard Worker SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2203*9880d681SAndroid Build Coastguard Worker }
2204*9880d681SAndroid Build Coastguard Worker
2205*9880d681SAndroid Build Coastguard Worker ConstantInt *AddRHS = nullptr;
2206*9880d681SAndroid Build Coastguard Worker if (match(Cond, m_Add(m_Value(), m_ConstantInt(AddRHS)))) {
2207*9880d681SAndroid Build Coastguard Worker Instruction *I = cast<Instruction>(Cond);
2208*9880d681SAndroid Build Coastguard Worker // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2209*9880d681SAndroid Build Coastguard Worker for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e;
2210*9880d681SAndroid Build Coastguard Worker ++i) {
2211*9880d681SAndroid Build Coastguard Worker ConstantInt *CaseVal = i.getCaseValue();
2212*9880d681SAndroid Build Coastguard Worker Constant *LHS = CaseVal;
2213*9880d681SAndroid Build Coastguard Worker if (TruncCond) {
2214*9880d681SAndroid Build Coastguard Worker LHS = LeadingKnownZeros
2215*9880d681SAndroid Build Coastguard Worker ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2216*9880d681SAndroid Build Coastguard Worker : ConstantExpr::getSExt(CaseVal, Cond->getType());
2217*9880d681SAndroid Build Coastguard Worker }
2218*9880d681SAndroid Build Coastguard Worker Constant *NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2219*9880d681SAndroid Build Coastguard Worker assert(isa<ConstantInt>(NewCaseVal) &&
2220*9880d681SAndroid Build Coastguard Worker "Result of expression should be constant");
2221*9880d681SAndroid Build Coastguard Worker i.setValue(cast<ConstantInt>(NewCaseVal));
2222*9880d681SAndroid Build Coastguard Worker }
2223*9880d681SAndroid Build Coastguard Worker SI.setCondition(I->getOperand(0));
2224*9880d681SAndroid Build Coastguard Worker Worklist.Add(I);
2225*9880d681SAndroid Build Coastguard Worker return &SI;
2226*9880d681SAndroid Build Coastguard Worker }
2227*9880d681SAndroid Build Coastguard Worker
2228*9880d681SAndroid Build Coastguard Worker return TruncCond ? &SI : nullptr;
2229*9880d681SAndroid Build Coastguard Worker }
2230*9880d681SAndroid Build Coastguard Worker
visitExtractValueInst(ExtractValueInst & EV)2231*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2232*9880d681SAndroid Build Coastguard Worker Value *Agg = EV.getAggregateOperand();
2233*9880d681SAndroid Build Coastguard Worker
2234*9880d681SAndroid Build Coastguard Worker if (!EV.hasIndices())
2235*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(EV, Agg);
2236*9880d681SAndroid Build Coastguard Worker
2237*9880d681SAndroid Build Coastguard Worker if (Value *V =
2238*9880d681SAndroid Build Coastguard Worker SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
2239*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(EV, V);
2240*9880d681SAndroid Build Coastguard Worker
2241*9880d681SAndroid Build Coastguard Worker if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2242*9880d681SAndroid Build Coastguard Worker // We're extracting from an insertvalue instruction, compare the indices
2243*9880d681SAndroid Build Coastguard Worker const unsigned *exti, *exte, *insi, *inse;
2244*9880d681SAndroid Build Coastguard Worker for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2245*9880d681SAndroid Build Coastguard Worker exte = EV.idx_end(), inse = IV->idx_end();
2246*9880d681SAndroid Build Coastguard Worker exti != exte && insi != inse;
2247*9880d681SAndroid Build Coastguard Worker ++exti, ++insi) {
2248*9880d681SAndroid Build Coastguard Worker if (*insi != *exti)
2249*9880d681SAndroid Build Coastguard Worker // The insert and extract both reference distinctly different elements.
2250*9880d681SAndroid Build Coastguard Worker // This means the extract is not influenced by the insert, and we can
2251*9880d681SAndroid Build Coastguard Worker // replace the aggregate operand of the extract with the aggregate
2252*9880d681SAndroid Build Coastguard Worker // operand of the insert. i.e., replace
2253*9880d681SAndroid Build Coastguard Worker // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2254*9880d681SAndroid Build Coastguard Worker // %E = extractvalue { i32, { i32 } } %I, 0
2255*9880d681SAndroid Build Coastguard Worker // with
2256*9880d681SAndroid Build Coastguard Worker // %E = extractvalue { i32, { i32 } } %A, 0
2257*9880d681SAndroid Build Coastguard Worker return ExtractValueInst::Create(IV->getAggregateOperand(),
2258*9880d681SAndroid Build Coastguard Worker EV.getIndices());
2259*9880d681SAndroid Build Coastguard Worker }
2260*9880d681SAndroid Build Coastguard Worker if (exti == exte && insi == inse)
2261*9880d681SAndroid Build Coastguard Worker // Both iterators are at the end: Index lists are identical. Replace
2262*9880d681SAndroid Build Coastguard Worker // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2263*9880d681SAndroid Build Coastguard Worker // %C = extractvalue { i32, { i32 } } %B, 1, 0
2264*9880d681SAndroid Build Coastguard Worker // with "i32 42"
2265*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2266*9880d681SAndroid Build Coastguard Worker if (exti == exte) {
2267*9880d681SAndroid Build Coastguard Worker // The extract list is a prefix of the insert list. i.e. replace
2268*9880d681SAndroid Build Coastguard Worker // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2269*9880d681SAndroid Build Coastguard Worker // %E = extractvalue { i32, { i32 } } %I, 1
2270*9880d681SAndroid Build Coastguard Worker // with
2271*9880d681SAndroid Build Coastguard Worker // %X = extractvalue { i32, { i32 } } %A, 1
2272*9880d681SAndroid Build Coastguard Worker // %E = insertvalue { i32 } %X, i32 42, 0
2273*9880d681SAndroid Build Coastguard Worker // by switching the order of the insert and extract (though the
2274*9880d681SAndroid Build Coastguard Worker // insertvalue should be left in, since it may have other uses).
2275*9880d681SAndroid Build Coastguard Worker Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2276*9880d681SAndroid Build Coastguard Worker EV.getIndices());
2277*9880d681SAndroid Build Coastguard Worker return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2278*9880d681SAndroid Build Coastguard Worker makeArrayRef(insi, inse));
2279*9880d681SAndroid Build Coastguard Worker }
2280*9880d681SAndroid Build Coastguard Worker if (insi == inse)
2281*9880d681SAndroid Build Coastguard Worker // The insert list is a prefix of the extract list
2282*9880d681SAndroid Build Coastguard Worker // We can simply remove the common indices from the extract and make it
2283*9880d681SAndroid Build Coastguard Worker // operate on the inserted value instead of the insertvalue result.
2284*9880d681SAndroid Build Coastguard Worker // i.e., replace
2285*9880d681SAndroid Build Coastguard Worker // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2286*9880d681SAndroid Build Coastguard Worker // %E = extractvalue { i32, { i32 } } %I, 1, 0
2287*9880d681SAndroid Build Coastguard Worker // with
2288*9880d681SAndroid Build Coastguard Worker // %E extractvalue { i32 } { i32 42 }, 0
2289*9880d681SAndroid Build Coastguard Worker return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2290*9880d681SAndroid Build Coastguard Worker makeArrayRef(exti, exte));
2291*9880d681SAndroid Build Coastguard Worker }
2292*9880d681SAndroid Build Coastguard Worker if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2293*9880d681SAndroid Build Coastguard Worker // We're extracting from an intrinsic, see if we're the only user, which
2294*9880d681SAndroid Build Coastguard Worker // allows us to simplify multiple result intrinsics to simpler things that
2295*9880d681SAndroid Build Coastguard Worker // just get one value.
2296*9880d681SAndroid Build Coastguard Worker if (II->hasOneUse()) {
2297*9880d681SAndroid Build Coastguard Worker // Check if we're grabbing the overflow bit or the result of a 'with
2298*9880d681SAndroid Build Coastguard Worker // overflow' intrinsic. If it's the latter we can remove the intrinsic
2299*9880d681SAndroid Build Coastguard Worker // and replace it with a traditional binary instruction.
2300*9880d681SAndroid Build Coastguard Worker switch (II->getIntrinsicID()) {
2301*9880d681SAndroid Build Coastguard Worker case Intrinsic::uadd_with_overflow:
2302*9880d681SAndroid Build Coastguard Worker case Intrinsic::sadd_with_overflow:
2303*9880d681SAndroid Build Coastguard Worker if (*EV.idx_begin() == 0) { // Normal result.
2304*9880d681SAndroid Build Coastguard Worker Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2305*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2306*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*II);
2307*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateAdd(LHS, RHS);
2308*9880d681SAndroid Build Coastguard Worker }
2309*9880d681SAndroid Build Coastguard Worker
2310*9880d681SAndroid Build Coastguard Worker // If the normal result of the add is dead, and the RHS is a constant,
2311*9880d681SAndroid Build Coastguard Worker // we can transform this into a range comparison.
2312*9880d681SAndroid Build Coastguard Worker // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2313*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2314*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2315*9880d681SAndroid Build Coastguard Worker return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2316*9880d681SAndroid Build Coastguard Worker ConstantExpr::getNot(CI));
2317*9880d681SAndroid Build Coastguard Worker break;
2318*9880d681SAndroid Build Coastguard Worker case Intrinsic::usub_with_overflow:
2319*9880d681SAndroid Build Coastguard Worker case Intrinsic::ssub_with_overflow:
2320*9880d681SAndroid Build Coastguard Worker if (*EV.idx_begin() == 0) { // Normal result.
2321*9880d681SAndroid Build Coastguard Worker Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2322*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2323*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*II);
2324*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateSub(LHS, RHS);
2325*9880d681SAndroid Build Coastguard Worker }
2326*9880d681SAndroid Build Coastguard Worker break;
2327*9880d681SAndroid Build Coastguard Worker case Intrinsic::umul_with_overflow:
2328*9880d681SAndroid Build Coastguard Worker case Intrinsic::smul_with_overflow:
2329*9880d681SAndroid Build Coastguard Worker if (*EV.idx_begin() == 0) { // Normal result.
2330*9880d681SAndroid Build Coastguard Worker Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2331*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2332*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*II);
2333*9880d681SAndroid Build Coastguard Worker return BinaryOperator::CreateMul(LHS, RHS);
2334*9880d681SAndroid Build Coastguard Worker }
2335*9880d681SAndroid Build Coastguard Worker break;
2336*9880d681SAndroid Build Coastguard Worker default:
2337*9880d681SAndroid Build Coastguard Worker break;
2338*9880d681SAndroid Build Coastguard Worker }
2339*9880d681SAndroid Build Coastguard Worker }
2340*9880d681SAndroid Build Coastguard Worker }
2341*9880d681SAndroid Build Coastguard Worker if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2342*9880d681SAndroid Build Coastguard Worker // If the (non-volatile) load only has one use, we can rewrite this to a
2343*9880d681SAndroid Build Coastguard Worker // load from a GEP. This reduces the size of the load. If a load is used
2344*9880d681SAndroid Build Coastguard Worker // only by extractvalue instructions then this either must have been
2345*9880d681SAndroid Build Coastguard Worker // optimized before, or it is a struct with padding, in which case we
2346*9880d681SAndroid Build Coastguard Worker // don't want to do the transformation as it loses padding knowledge.
2347*9880d681SAndroid Build Coastguard Worker if (L->isSimple() && L->hasOneUse()) {
2348*9880d681SAndroid Build Coastguard Worker // extractvalue has integer indices, getelementptr has Value*s. Convert.
2349*9880d681SAndroid Build Coastguard Worker SmallVector<Value*, 4> Indices;
2350*9880d681SAndroid Build Coastguard Worker // Prefix an i32 0 since we need the first element.
2351*9880d681SAndroid Build Coastguard Worker Indices.push_back(Builder->getInt32(0));
2352*9880d681SAndroid Build Coastguard Worker for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2353*9880d681SAndroid Build Coastguard Worker I != E; ++I)
2354*9880d681SAndroid Build Coastguard Worker Indices.push_back(Builder->getInt32(*I));
2355*9880d681SAndroid Build Coastguard Worker
2356*9880d681SAndroid Build Coastguard Worker // We need to insert these at the location of the old load, not at that of
2357*9880d681SAndroid Build Coastguard Worker // the extractvalue.
2358*9880d681SAndroid Build Coastguard Worker Builder->SetInsertPoint(L);
2359*9880d681SAndroid Build Coastguard Worker Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2360*9880d681SAndroid Build Coastguard Worker L->getPointerOperand(), Indices);
2361*9880d681SAndroid Build Coastguard Worker // Returning the load directly will cause the main loop to insert it in
2362*9880d681SAndroid Build Coastguard Worker // the wrong spot, so use replaceInstUsesWith().
2363*9880d681SAndroid Build Coastguard Worker return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2364*9880d681SAndroid Build Coastguard Worker }
2365*9880d681SAndroid Build Coastguard Worker // We could simplify extracts from other values. Note that nested extracts may
2366*9880d681SAndroid Build Coastguard Worker // already be simplified implicitly by the above: extract (extract (insert) )
2367*9880d681SAndroid Build Coastguard Worker // will be translated into extract ( insert ( extract ) ) first and then just
2368*9880d681SAndroid Build Coastguard Worker // the value inserted, if appropriate. Similarly for extracts from single-use
2369*9880d681SAndroid Build Coastguard Worker // loads: extract (extract (load)) will be translated to extract (load (gep))
2370*9880d681SAndroid Build Coastguard Worker // and if again single-use then via load (gep (gep)) to load (gep).
2371*9880d681SAndroid Build Coastguard Worker // However, double extracts from e.g. function arguments or return values
2372*9880d681SAndroid Build Coastguard Worker // aren't handled yet.
2373*9880d681SAndroid Build Coastguard Worker return nullptr;
2374*9880d681SAndroid Build Coastguard Worker }
2375*9880d681SAndroid Build Coastguard Worker
2376*9880d681SAndroid Build Coastguard Worker /// Return 'true' if the given typeinfo will match anything.
isCatchAll(EHPersonality Personality,Constant * TypeInfo)2377*9880d681SAndroid Build Coastguard Worker static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2378*9880d681SAndroid Build Coastguard Worker switch (Personality) {
2379*9880d681SAndroid Build Coastguard Worker case EHPersonality::GNU_C:
2380*9880d681SAndroid Build Coastguard Worker case EHPersonality::GNU_C_SjLj:
2381*9880d681SAndroid Build Coastguard Worker case EHPersonality::Rust:
2382*9880d681SAndroid Build Coastguard Worker // The GCC C EH and Rust personality only exists to support cleanups, so
2383*9880d681SAndroid Build Coastguard Worker // it's not clear what the semantics of catch clauses are.
2384*9880d681SAndroid Build Coastguard Worker return false;
2385*9880d681SAndroid Build Coastguard Worker case EHPersonality::Unknown:
2386*9880d681SAndroid Build Coastguard Worker return false;
2387*9880d681SAndroid Build Coastguard Worker case EHPersonality::GNU_Ada:
2388*9880d681SAndroid Build Coastguard Worker // While __gnat_all_others_value will match any Ada exception, it doesn't
2389*9880d681SAndroid Build Coastguard Worker // match foreign exceptions (or didn't, before gcc-4.7).
2390*9880d681SAndroid Build Coastguard Worker return false;
2391*9880d681SAndroid Build Coastguard Worker case EHPersonality::GNU_CXX:
2392*9880d681SAndroid Build Coastguard Worker case EHPersonality::GNU_CXX_SjLj:
2393*9880d681SAndroid Build Coastguard Worker case EHPersonality::GNU_ObjC:
2394*9880d681SAndroid Build Coastguard Worker case EHPersonality::MSVC_X86SEH:
2395*9880d681SAndroid Build Coastguard Worker case EHPersonality::MSVC_Win64SEH:
2396*9880d681SAndroid Build Coastguard Worker case EHPersonality::MSVC_CXX:
2397*9880d681SAndroid Build Coastguard Worker case EHPersonality::CoreCLR:
2398*9880d681SAndroid Build Coastguard Worker return TypeInfo->isNullValue();
2399*9880d681SAndroid Build Coastguard Worker }
2400*9880d681SAndroid Build Coastguard Worker llvm_unreachable("invalid enum");
2401*9880d681SAndroid Build Coastguard Worker }
2402*9880d681SAndroid Build Coastguard Worker
shorter_filter(const Value * LHS,const Value * RHS)2403*9880d681SAndroid Build Coastguard Worker static bool shorter_filter(const Value *LHS, const Value *RHS) {
2404*9880d681SAndroid Build Coastguard Worker return
2405*9880d681SAndroid Build Coastguard Worker cast<ArrayType>(LHS->getType())->getNumElements()
2406*9880d681SAndroid Build Coastguard Worker <
2407*9880d681SAndroid Build Coastguard Worker cast<ArrayType>(RHS->getType())->getNumElements();
2408*9880d681SAndroid Build Coastguard Worker }
2409*9880d681SAndroid Build Coastguard Worker
visitLandingPadInst(LandingPadInst & LI)2410*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2411*9880d681SAndroid Build Coastguard Worker // The logic here should be correct for any real-world personality function.
2412*9880d681SAndroid Build Coastguard Worker // However if that turns out not to be true, the offending logic can always
2413*9880d681SAndroid Build Coastguard Worker // be conditioned on the personality function, like the catch-all logic is.
2414*9880d681SAndroid Build Coastguard Worker EHPersonality Personality =
2415*9880d681SAndroid Build Coastguard Worker classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2416*9880d681SAndroid Build Coastguard Worker
2417*9880d681SAndroid Build Coastguard Worker // Simplify the list of clauses, eg by removing repeated catch clauses
2418*9880d681SAndroid Build Coastguard Worker // (these are often created by inlining).
2419*9880d681SAndroid Build Coastguard Worker bool MakeNewInstruction = false; // If true, recreate using the following:
2420*9880d681SAndroid Build Coastguard Worker SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2421*9880d681SAndroid Build Coastguard Worker bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2422*9880d681SAndroid Build Coastguard Worker
2423*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2424*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2425*9880d681SAndroid Build Coastguard Worker bool isLastClause = i + 1 == e;
2426*9880d681SAndroid Build Coastguard Worker if (LI.isCatch(i)) {
2427*9880d681SAndroid Build Coastguard Worker // A catch clause.
2428*9880d681SAndroid Build Coastguard Worker Constant *CatchClause = LI.getClause(i);
2429*9880d681SAndroid Build Coastguard Worker Constant *TypeInfo = CatchClause->stripPointerCasts();
2430*9880d681SAndroid Build Coastguard Worker
2431*9880d681SAndroid Build Coastguard Worker // If we already saw this clause, there is no point in having a second
2432*9880d681SAndroid Build Coastguard Worker // copy of it.
2433*9880d681SAndroid Build Coastguard Worker if (AlreadyCaught.insert(TypeInfo).second) {
2434*9880d681SAndroid Build Coastguard Worker // This catch clause was not already seen.
2435*9880d681SAndroid Build Coastguard Worker NewClauses.push_back(CatchClause);
2436*9880d681SAndroid Build Coastguard Worker } else {
2437*9880d681SAndroid Build Coastguard Worker // Repeated catch clause - drop the redundant copy.
2438*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2439*9880d681SAndroid Build Coastguard Worker }
2440*9880d681SAndroid Build Coastguard Worker
2441*9880d681SAndroid Build Coastguard Worker // If this is a catch-all then there is no point in keeping any following
2442*9880d681SAndroid Build Coastguard Worker // clauses or marking the landingpad as having a cleanup.
2443*9880d681SAndroid Build Coastguard Worker if (isCatchAll(Personality, TypeInfo)) {
2444*9880d681SAndroid Build Coastguard Worker if (!isLastClause)
2445*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2446*9880d681SAndroid Build Coastguard Worker CleanupFlag = false;
2447*9880d681SAndroid Build Coastguard Worker break;
2448*9880d681SAndroid Build Coastguard Worker }
2449*9880d681SAndroid Build Coastguard Worker } else {
2450*9880d681SAndroid Build Coastguard Worker // A filter clause. If any of the filter elements were already caught
2451*9880d681SAndroid Build Coastguard Worker // then they can be dropped from the filter. It is tempting to try to
2452*9880d681SAndroid Build Coastguard Worker // exploit the filter further by saying that any typeinfo that does not
2453*9880d681SAndroid Build Coastguard Worker // occur in the filter can't be caught later (and thus can be dropped).
2454*9880d681SAndroid Build Coastguard Worker // However this would be wrong, since typeinfos can match without being
2455*9880d681SAndroid Build Coastguard Worker // equal (for example if one represents a C++ class, and the other some
2456*9880d681SAndroid Build Coastguard Worker // class derived from it).
2457*9880d681SAndroid Build Coastguard Worker assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2458*9880d681SAndroid Build Coastguard Worker Constant *FilterClause = LI.getClause(i);
2459*9880d681SAndroid Build Coastguard Worker ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2460*9880d681SAndroid Build Coastguard Worker unsigned NumTypeInfos = FilterType->getNumElements();
2461*9880d681SAndroid Build Coastguard Worker
2462*9880d681SAndroid Build Coastguard Worker // An empty filter catches everything, so there is no point in keeping any
2463*9880d681SAndroid Build Coastguard Worker // following clauses or marking the landingpad as having a cleanup. By
2464*9880d681SAndroid Build Coastguard Worker // dealing with this case here the following code is made a bit simpler.
2465*9880d681SAndroid Build Coastguard Worker if (!NumTypeInfos) {
2466*9880d681SAndroid Build Coastguard Worker NewClauses.push_back(FilterClause);
2467*9880d681SAndroid Build Coastguard Worker if (!isLastClause)
2468*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2469*9880d681SAndroid Build Coastguard Worker CleanupFlag = false;
2470*9880d681SAndroid Build Coastguard Worker break;
2471*9880d681SAndroid Build Coastguard Worker }
2472*9880d681SAndroid Build Coastguard Worker
2473*9880d681SAndroid Build Coastguard Worker bool MakeNewFilter = false; // If true, make a new filter.
2474*9880d681SAndroid Build Coastguard Worker SmallVector<Constant *, 16> NewFilterElts; // New elements.
2475*9880d681SAndroid Build Coastguard Worker if (isa<ConstantAggregateZero>(FilterClause)) {
2476*9880d681SAndroid Build Coastguard Worker // Not an empty filter - it contains at least one null typeinfo.
2477*9880d681SAndroid Build Coastguard Worker assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2478*9880d681SAndroid Build Coastguard Worker Constant *TypeInfo =
2479*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(FilterType->getElementType());
2480*9880d681SAndroid Build Coastguard Worker // If this typeinfo is a catch-all then the filter can never match.
2481*9880d681SAndroid Build Coastguard Worker if (isCatchAll(Personality, TypeInfo)) {
2482*9880d681SAndroid Build Coastguard Worker // Throw the filter away.
2483*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2484*9880d681SAndroid Build Coastguard Worker continue;
2485*9880d681SAndroid Build Coastguard Worker }
2486*9880d681SAndroid Build Coastguard Worker
2487*9880d681SAndroid Build Coastguard Worker // There is no point in having multiple copies of this typeinfo, so
2488*9880d681SAndroid Build Coastguard Worker // discard all but the first copy if there is more than one.
2489*9880d681SAndroid Build Coastguard Worker NewFilterElts.push_back(TypeInfo);
2490*9880d681SAndroid Build Coastguard Worker if (NumTypeInfos > 1)
2491*9880d681SAndroid Build Coastguard Worker MakeNewFilter = true;
2492*9880d681SAndroid Build Coastguard Worker } else {
2493*9880d681SAndroid Build Coastguard Worker ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2494*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2495*9880d681SAndroid Build Coastguard Worker NewFilterElts.reserve(NumTypeInfos);
2496*9880d681SAndroid Build Coastguard Worker
2497*9880d681SAndroid Build Coastguard Worker // Remove any filter elements that were already caught or that already
2498*9880d681SAndroid Build Coastguard Worker // occurred in the filter. While there, see if any of the elements are
2499*9880d681SAndroid Build Coastguard Worker // catch-alls. If so, the filter can be discarded.
2500*9880d681SAndroid Build Coastguard Worker bool SawCatchAll = false;
2501*9880d681SAndroid Build Coastguard Worker for (unsigned j = 0; j != NumTypeInfos; ++j) {
2502*9880d681SAndroid Build Coastguard Worker Constant *Elt = Filter->getOperand(j);
2503*9880d681SAndroid Build Coastguard Worker Constant *TypeInfo = Elt->stripPointerCasts();
2504*9880d681SAndroid Build Coastguard Worker if (isCatchAll(Personality, TypeInfo)) {
2505*9880d681SAndroid Build Coastguard Worker // This element is a catch-all. Bail out, noting this fact.
2506*9880d681SAndroid Build Coastguard Worker SawCatchAll = true;
2507*9880d681SAndroid Build Coastguard Worker break;
2508*9880d681SAndroid Build Coastguard Worker }
2509*9880d681SAndroid Build Coastguard Worker
2510*9880d681SAndroid Build Coastguard Worker // Even if we've seen a type in a catch clause, we don't want to
2511*9880d681SAndroid Build Coastguard Worker // remove it from the filter. An unexpected type handler may be
2512*9880d681SAndroid Build Coastguard Worker // set up for a call site which throws an exception of the same
2513*9880d681SAndroid Build Coastguard Worker // type caught. In order for the exception thrown by the unexpected
2514*9880d681SAndroid Build Coastguard Worker // handler to propogate correctly, the filter must be correctly
2515*9880d681SAndroid Build Coastguard Worker // described for the call site.
2516*9880d681SAndroid Build Coastguard Worker //
2517*9880d681SAndroid Build Coastguard Worker // Example:
2518*9880d681SAndroid Build Coastguard Worker //
2519*9880d681SAndroid Build Coastguard Worker // void unexpected() { throw 1;}
2520*9880d681SAndroid Build Coastguard Worker // void foo() throw (int) {
2521*9880d681SAndroid Build Coastguard Worker // std::set_unexpected(unexpected);
2522*9880d681SAndroid Build Coastguard Worker // try {
2523*9880d681SAndroid Build Coastguard Worker // throw 2.0;
2524*9880d681SAndroid Build Coastguard Worker // } catch (int i) {}
2525*9880d681SAndroid Build Coastguard Worker // }
2526*9880d681SAndroid Build Coastguard Worker
2527*9880d681SAndroid Build Coastguard Worker // There is no point in having multiple copies of the same typeinfo in
2528*9880d681SAndroid Build Coastguard Worker // a filter, so only add it if we didn't already.
2529*9880d681SAndroid Build Coastguard Worker if (SeenInFilter.insert(TypeInfo).second)
2530*9880d681SAndroid Build Coastguard Worker NewFilterElts.push_back(cast<Constant>(Elt));
2531*9880d681SAndroid Build Coastguard Worker }
2532*9880d681SAndroid Build Coastguard Worker // A filter containing a catch-all cannot match anything by definition.
2533*9880d681SAndroid Build Coastguard Worker if (SawCatchAll) {
2534*9880d681SAndroid Build Coastguard Worker // Throw the filter away.
2535*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2536*9880d681SAndroid Build Coastguard Worker continue;
2537*9880d681SAndroid Build Coastguard Worker }
2538*9880d681SAndroid Build Coastguard Worker
2539*9880d681SAndroid Build Coastguard Worker // If we dropped something from the filter, make a new one.
2540*9880d681SAndroid Build Coastguard Worker if (NewFilterElts.size() < NumTypeInfos)
2541*9880d681SAndroid Build Coastguard Worker MakeNewFilter = true;
2542*9880d681SAndroid Build Coastguard Worker }
2543*9880d681SAndroid Build Coastguard Worker if (MakeNewFilter) {
2544*9880d681SAndroid Build Coastguard Worker FilterType = ArrayType::get(FilterType->getElementType(),
2545*9880d681SAndroid Build Coastguard Worker NewFilterElts.size());
2546*9880d681SAndroid Build Coastguard Worker FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2547*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2548*9880d681SAndroid Build Coastguard Worker }
2549*9880d681SAndroid Build Coastguard Worker
2550*9880d681SAndroid Build Coastguard Worker NewClauses.push_back(FilterClause);
2551*9880d681SAndroid Build Coastguard Worker
2552*9880d681SAndroid Build Coastguard Worker // If the new filter is empty then it will catch everything so there is
2553*9880d681SAndroid Build Coastguard Worker // no point in keeping any following clauses or marking the landingpad
2554*9880d681SAndroid Build Coastguard Worker // as having a cleanup. The case of the original filter being empty was
2555*9880d681SAndroid Build Coastguard Worker // already handled above.
2556*9880d681SAndroid Build Coastguard Worker if (MakeNewFilter && !NewFilterElts.size()) {
2557*9880d681SAndroid Build Coastguard Worker assert(MakeNewInstruction && "New filter but not a new instruction!");
2558*9880d681SAndroid Build Coastguard Worker CleanupFlag = false;
2559*9880d681SAndroid Build Coastguard Worker break;
2560*9880d681SAndroid Build Coastguard Worker }
2561*9880d681SAndroid Build Coastguard Worker }
2562*9880d681SAndroid Build Coastguard Worker }
2563*9880d681SAndroid Build Coastguard Worker
2564*9880d681SAndroid Build Coastguard Worker // If several filters occur in a row then reorder them so that the shortest
2565*9880d681SAndroid Build Coastguard Worker // filters come first (those with the smallest number of elements). This is
2566*9880d681SAndroid Build Coastguard Worker // advantageous because shorter filters are more likely to match, speeding up
2567*9880d681SAndroid Build Coastguard Worker // unwinding, but mostly because it increases the effectiveness of the other
2568*9880d681SAndroid Build Coastguard Worker // filter optimizations below.
2569*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2570*9880d681SAndroid Build Coastguard Worker unsigned j;
2571*9880d681SAndroid Build Coastguard Worker // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2572*9880d681SAndroid Build Coastguard Worker for (j = i; j != e; ++j)
2573*9880d681SAndroid Build Coastguard Worker if (!isa<ArrayType>(NewClauses[j]->getType()))
2574*9880d681SAndroid Build Coastguard Worker break;
2575*9880d681SAndroid Build Coastguard Worker
2576*9880d681SAndroid Build Coastguard Worker // Check whether the filters are already sorted by length. We need to know
2577*9880d681SAndroid Build Coastguard Worker // if sorting them is actually going to do anything so that we only make a
2578*9880d681SAndroid Build Coastguard Worker // new landingpad instruction if it does.
2579*9880d681SAndroid Build Coastguard Worker for (unsigned k = i; k + 1 < j; ++k)
2580*9880d681SAndroid Build Coastguard Worker if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2581*9880d681SAndroid Build Coastguard Worker // Not sorted, so sort the filters now. Doing an unstable sort would be
2582*9880d681SAndroid Build Coastguard Worker // correct too but reordering filters pointlessly might confuse users.
2583*9880d681SAndroid Build Coastguard Worker std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2584*9880d681SAndroid Build Coastguard Worker shorter_filter);
2585*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2586*9880d681SAndroid Build Coastguard Worker break;
2587*9880d681SAndroid Build Coastguard Worker }
2588*9880d681SAndroid Build Coastguard Worker
2589*9880d681SAndroid Build Coastguard Worker // Look for the next batch of filters.
2590*9880d681SAndroid Build Coastguard Worker i = j + 1;
2591*9880d681SAndroid Build Coastguard Worker }
2592*9880d681SAndroid Build Coastguard Worker
2593*9880d681SAndroid Build Coastguard Worker // If typeinfos matched if and only if equal, then the elements of a filter L
2594*9880d681SAndroid Build Coastguard Worker // that occurs later than a filter F could be replaced by the intersection of
2595*9880d681SAndroid Build Coastguard Worker // the elements of F and L. In reality two typeinfos can match without being
2596*9880d681SAndroid Build Coastguard Worker // equal (for example if one represents a C++ class, and the other some class
2597*9880d681SAndroid Build Coastguard Worker // derived from it) so it would be wrong to perform this transform in general.
2598*9880d681SAndroid Build Coastguard Worker // However the transform is correct and useful if F is a subset of L. In that
2599*9880d681SAndroid Build Coastguard Worker // case L can be replaced by F, and thus removed altogether since repeating a
2600*9880d681SAndroid Build Coastguard Worker // filter is pointless. So here we look at all pairs of filters F and L where
2601*9880d681SAndroid Build Coastguard Worker // L follows F in the list of clauses, and remove L if every element of F is
2602*9880d681SAndroid Build Coastguard Worker // an element of L. This can occur when inlining C++ functions with exception
2603*9880d681SAndroid Build Coastguard Worker // specifications.
2604*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2605*9880d681SAndroid Build Coastguard Worker // Examine each filter in turn.
2606*9880d681SAndroid Build Coastguard Worker Value *Filter = NewClauses[i];
2607*9880d681SAndroid Build Coastguard Worker ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2608*9880d681SAndroid Build Coastguard Worker if (!FTy)
2609*9880d681SAndroid Build Coastguard Worker // Not a filter - skip it.
2610*9880d681SAndroid Build Coastguard Worker continue;
2611*9880d681SAndroid Build Coastguard Worker unsigned FElts = FTy->getNumElements();
2612*9880d681SAndroid Build Coastguard Worker // Examine each filter following this one. Doing this backwards means that
2613*9880d681SAndroid Build Coastguard Worker // we don't have to worry about filters disappearing under us when removed.
2614*9880d681SAndroid Build Coastguard Worker for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2615*9880d681SAndroid Build Coastguard Worker Value *LFilter = NewClauses[j];
2616*9880d681SAndroid Build Coastguard Worker ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2617*9880d681SAndroid Build Coastguard Worker if (!LTy)
2618*9880d681SAndroid Build Coastguard Worker // Not a filter - skip it.
2619*9880d681SAndroid Build Coastguard Worker continue;
2620*9880d681SAndroid Build Coastguard Worker // If Filter is a subset of LFilter, i.e. every element of Filter is also
2621*9880d681SAndroid Build Coastguard Worker // an element of LFilter, then discard LFilter.
2622*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2623*9880d681SAndroid Build Coastguard Worker // If Filter is empty then it is a subset of LFilter.
2624*9880d681SAndroid Build Coastguard Worker if (!FElts) {
2625*9880d681SAndroid Build Coastguard Worker // Discard LFilter.
2626*9880d681SAndroid Build Coastguard Worker NewClauses.erase(J);
2627*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2628*9880d681SAndroid Build Coastguard Worker // Move on to the next filter.
2629*9880d681SAndroid Build Coastguard Worker continue;
2630*9880d681SAndroid Build Coastguard Worker }
2631*9880d681SAndroid Build Coastguard Worker unsigned LElts = LTy->getNumElements();
2632*9880d681SAndroid Build Coastguard Worker // If Filter is longer than LFilter then it cannot be a subset of it.
2633*9880d681SAndroid Build Coastguard Worker if (FElts > LElts)
2634*9880d681SAndroid Build Coastguard Worker // Move on to the next filter.
2635*9880d681SAndroid Build Coastguard Worker continue;
2636*9880d681SAndroid Build Coastguard Worker // At this point we know that LFilter has at least one element.
2637*9880d681SAndroid Build Coastguard Worker if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2638*9880d681SAndroid Build Coastguard Worker // Filter is a subset of LFilter iff Filter contains only zeros (as we
2639*9880d681SAndroid Build Coastguard Worker // already know that Filter is not longer than LFilter).
2640*9880d681SAndroid Build Coastguard Worker if (isa<ConstantAggregateZero>(Filter)) {
2641*9880d681SAndroid Build Coastguard Worker assert(FElts <= LElts && "Should have handled this case earlier!");
2642*9880d681SAndroid Build Coastguard Worker // Discard LFilter.
2643*9880d681SAndroid Build Coastguard Worker NewClauses.erase(J);
2644*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2645*9880d681SAndroid Build Coastguard Worker }
2646*9880d681SAndroid Build Coastguard Worker // Move on to the next filter.
2647*9880d681SAndroid Build Coastguard Worker continue;
2648*9880d681SAndroid Build Coastguard Worker }
2649*9880d681SAndroid Build Coastguard Worker ConstantArray *LArray = cast<ConstantArray>(LFilter);
2650*9880d681SAndroid Build Coastguard Worker if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2651*9880d681SAndroid Build Coastguard Worker // Since Filter is non-empty and contains only zeros, it is a subset of
2652*9880d681SAndroid Build Coastguard Worker // LFilter iff LFilter contains a zero.
2653*9880d681SAndroid Build Coastguard Worker assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2654*9880d681SAndroid Build Coastguard Worker for (unsigned l = 0; l != LElts; ++l)
2655*9880d681SAndroid Build Coastguard Worker if (LArray->getOperand(l)->isNullValue()) {
2656*9880d681SAndroid Build Coastguard Worker // LFilter contains a zero - discard it.
2657*9880d681SAndroid Build Coastguard Worker NewClauses.erase(J);
2658*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2659*9880d681SAndroid Build Coastguard Worker break;
2660*9880d681SAndroid Build Coastguard Worker }
2661*9880d681SAndroid Build Coastguard Worker // Move on to the next filter.
2662*9880d681SAndroid Build Coastguard Worker continue;
2663*9880d681SAndroid Build Coastguard Worker }
2664*9880d681SAndroid Build Coastguard Worker // At this point we know that both filters are ConstantArrays. Loop over
2665*9880d681SAndroid Build Coastguard Worker // operands to see whether every element of Filter is also an element of
2666*9880d681SAndroid Build Coastguard Worker // LFilter. Since filters tend to be short this is probably faster than
2667*9880d681SAndroid Build Coastguard Worker // using a method that scales nicely.
2668*9880d681SAndroid Build Coastguard Worker ConstantArray *FArray = cast<ConstantArray>(Filter);
2669*9880d681SAndroid Build Coastguard Worker bool AllFound = true;
2670*9880d681SAndroid Build Coastguard Worker for (unsigned f = 0; f != FElts; ++f) {
2671*9880d681SAndroid Build Coastguard Worker Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2672*9880d681SAndroid Build Coastguard Worker AllFound = false;
2673*9880d681SAndroid Build Coastguard Worker for (unsigned l = 0; l != LElts; ++l) {
2674*9880d681SAndroid Build Coastguard Worker Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2675*9880d681SAndroid Build Coastguard Worker if (LTypeInfo == FTypeInfo) {
2676*9880d681SAndroid Build Coastguard Worker AllFound = true;
2677*9880d681SAndroid Build Coastguard Worker break;
2678*9880d681SAndroid Build Coastguard Worker }
2679*9880d681SAndroid Build Coastguard Worker }
2680*9880d681SAndroid Build Coastguard Worker if (!AllFound)
2681*9880d681SAndroid Build Coastguard Worker break;
2682*9880d681SAndroid Build Coastguard Worker }
2683*9880d681SAndroid Build Coastguard Worker if (AllFound) {
2684*9880d681SAndroid Build Coastguard Worker // Discard LFilter.
2685*9880d681SAndroid Build Coastguard Worker NewClauses.erase(J);
2686*9880d681SAndroid Build Coastguard Worker MakeNewInstruction = true;
2687*9880d681SAndroid Build Coastguard Worker }
2688*9880d681SAndroid Build Coastguard Worker // Move on to the next filter.
2689*9880d681SAndroid Build Coastguard Worker }
2690*9880d681SAndroid Build Coastguard Worker }
2691*9880d681SAndroid Build Coastguard Worker
2692*9880d681SAndroid Build Coastguard Worker // If we changed any of the clauses, replace the old landingpad instruction
2693*9880d681SAndroid Build Coastguard Worker // with a new one.
2694*9880d681SAndroid Build Coastguard Worker if (MakeNewInstruction) {
2695*9880d681SAndroid Build Coastguard Worker LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2696*9880d681SAndroid Build Coastguard Worker NewClauses.size());
2697*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2698*9880d681SAndroid Build Coastguard Worker NLI->addClause(NewClauses[i]);
2699*9880d681SAndroid Build Coastguard Worker // A landing pad with no clauses must have the cleanup flag set. It is
2700*9880d681SAndroid Build Coastguard Worker // theoretically possible, though highly unlikely, that we eliminated all
2701*9880d681SAndroid Build Coastguard Worker // clauses. If so, force the cleanup flag to true.
2702*9880d681SAndroid Build Coastguard Worker if (NewClauses.empty())
2703*9880d681SAndroid Build Coastguard Worker CleanupFlag = true;
2704*9880d681SAndroid Build Coastguard Worker NLI->setCleanup(CleanupFlag);
2705*9880d681SAndroid Build Coastguard Worker return NLI;
2706*9880d681SAndroid Build Coastguard Worker }
2707*9880d681SAndroid Build Coastguard Worker
2708*9880d681SAndroid Build Coastguard Worker // Even if none of the clauses changed, we may nonetheless have understood
2709*9880d681SAndroid Build Coastguard Worker // that the cleanup flag is pointless. Clear it if so.
2710*9880d681SAndroid Build Coastguard Worker if (LI.isCleanup() != CleanupFlag) {
2711*9880d681SAndroid Build Coastguard Worker assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2712*9880d681SAndroid Build Coastguard Worker LI.setCleanup(CleanupFlag);
2713*9880d681SAndroid Build Coastguard Worker return &LI;
2714*9880d681SAndroid Build Coastguard Worker }
2715*9880d681SAndroid Build Coastguard Worker
2716*9880d681SAndroid Build Coastguard Worker return nullptr;
2717*9880d681SAndroid Build Coastguard Worker }
2718*9880d681SAndroid Build Coastguard Worker
2719*9880d681SAndroid Build Coastguard Worker /// Try to move the specified instruction from its current block into the
2720*9880d681SAndroid Build Coastguard Worker /// beginning of DestBlock, which can only happen if it's safe to move the
2721*9880d681SAndroid Build Coastguard Worker /// instruction past all of the instructions between it and the end of its
2722*9880d681SAndroid Build Coastguard Worker /// block.
TryToSinkInstruction(Instruction * I,BasicBlock * DestBlock)2723*9880d681SAndroid Build Coastguard Worker static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2724*9880d681SAndroid Build Coastguard Worker assert(I->hasOneUse() && "Invariants didn't hold!");
2725*9880d681SAndroid Build Coastguard Worker
2726*9880d681SAndroid Build Coastguard Worker // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2727*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2728*9880d681SAndroid Build Coastguard Worker isa<TerminatorInst>(I))
2729*9880d681SAndroid Build Coastguard Worker return false;
2730*9880d681SAndroid Build Coastguard Worker
2731*9880d681SAndroid Build Coastguard Worker // Do not sink alloca instructions out of the entry block.
2732*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(I) && I->getParent() ==
2733*9880d681SAndroid Build Coastguard Worker &DestBlock->getParent()->getEntryBlock())
2734*9880d681SAndroid Build Coastguard Worker return false;
2735*9880d681SAndroid Build Coastguard Worker
2736*9880d681SAndroid Build Coastguard Worker // Do not sink into catchswitch blocks.
2737*9880d681SAndroid Build Coastguard Worker if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2738*9880d681SAndroid Build Coastguard Worker return false;
2739*9880d681SAndroid Build Coastguard Worker
2740*9880d681SAndroid Build Coastguard Worker // Do not sink convergent call instructions.
2741*9880d681SAndroid Build Coastguard Worker if (auto *CI = dyn_cast<CallInst>(I)) {
2742*9880d681SAndroid Build Coastguard Worker if (CI->isConvergent())
2743*9880d681SAndroid Build Coastguard Worker return false;
2744*9880d681SAndroid Build Coastguard Worker }
2745*9880d681SAndroid Build Coastguard Worker // We can only sink load instructions if there is nothing between the load and
2746*9880d681SAndroid Build Coastguard Worker // the end of block that could change the value.
2747*9880d681SAndroid Build Coastguard Worker if (I->mayReadFromMemory()) {
2748*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator Scan = I->getIterator(),
2749*9880d681SAndroid Build Coastguard Worker E = I->getParent()->end();
2750*9880d681SAndroid Build Coastguard Worker Scan != E; ++Scan)
2751*9880d681SAndroid Build Coastguard Worker if (Scan->mayWriteToMemory())
2752*9880d681SAndroid Build Coastguard Worker return false;
2753*9880d681SAndroid Build Coastguard Worker }
2754*9880d681SAndroid Build Coastguard Worker
2755*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2756*9880d681SAndroid Build Coastguard Worker I->moveBefore(&*InsertPos);
2757*9880d681SAndroid Build Coastguard Worker ++NumSunkInst;
2758*9880d681SAndroid Build Coastguard Worker return true;
2759*9880d681SAndroid Build Coastguard Worker }
2760*9880d681SAndroid Build Coastguard Worker
run()2761*9880d681SAndroid Build Coastguard Worker bool InstCombiner::run() {
2762*9880d681SAndroid Build Coastguard Worker while (!Worklist.isEmpty()) {
2763*9880d681SAndroid Build Coastguard Worker Instruction *I = Worklist.RemoveOne();
2764*9880d681SAndroid Build Coastguard Worker if (I == nullptr) continue; // skip null values.
2765*9880d681SAndroid Build Coastguard Worker
2766*9880d681SAndroid Build Coastguard Worker // Check to see if we can DCE the instruction.
2767*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(I, TLI)) {
2768*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2769*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*I);
2770*9880d681SAndroid Build Coastguard Worker ++NumDeadInst;
2771*9880d681SAndroid Build Coastguard Worker MadeIRChange = true;
2772*9880d681SAndroid Build Coastguard Worker continue;
2773*9880d681SAndroid Build Coastguard Worker }
2774*9880d681SAndroid Build Coastguard Worker
2775*9880d681SAndroid Build Coastguard Worker // Instruction isn't dead, see if we can constant propagate it.
2776*9880d681SAndroid Build Coastguard Worker if (!I->use_empty() &&
2777*9880d681SAndroid Build Coastguard Worker (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2778*9880d681SAndroid Build Coastguard Worker if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2779*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2780*9880d681SAndroid Build Coastguard Worker
2781*9880d681SAndroid Build Coastguard Worker // Add operands to the worklist.
2782*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*I, C);
2783*9880d681SAndroid Build Coastguard Worker ++NumConstProp;
2784*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*I);
2785*9880d681SAndroid Build Coastguard Worker MadeIRChange = true;
2786*9880d681SAndroid Build Coastguard Worker continue;
2787*9880d681SAndroid Build Coastguard Worker }
2788*9880d681SAndroid Build Coastguard Worker }
2789*9880d681SAndroid Build Coastguard Worker
2790*9880d681SAndroid Build Coastguard Worker // In general, it is possible for computeKnownBits to determine all bits in
2791*9880d681SAndroid Build Coastguard Worker // a value even when the operands are not all constants.
2792*9880d681SAndroid Build Coastguard Worker if (ExpensiveCombines && !I->use_empty() && I->getType()->isIntegerTy()) {
2793*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = I->getType()->getScalarSizeInBits();
2794*9880d681SAndroid Build Coastguard Worker APInt KnownZero(BitWidth, 0);
2795*9880d681SAndroid Build Coastguard Worker APInt KnownOne(BitWidth, 0);
2796*9880d681SAndroid Build Coastguard Worker computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2797*9880d681SAndroid Build Coastguard Worker if ((KnownZero | KnownOne).isAllOnesValue()) {
2798*9880d681SAndroid Build Coastguard Worker Constant *C = ConstantInt::get(I->getContext(), KnownOne);
2799*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2800*9880d681SAndroid Build Coastguard Worker " from: " << *I << '\n');
2801*9880d681SAndroid Build Coastguard Worker
2802*9880d681SAndroid Build Coastguard Worker // Add operands to the worklist.
2803*9880d681SAndroid Build Coastguard Worker replaceInstUsesWith(*I, C);
2804*9880d681SAndroid Build Coastguard Worker ++NumConstProp;
2805*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*I);
2806*9880d681SAndroid Build Coastguard Worker MadeIRChange = true;
2807*9880d681SAndroid Build Coastguard Worker continue;
2808*9880d681SAndroid Build Coastguard Worker }
2809*9880d681SAndroid Build Coastguard Worker }
2810*9880d681SAndroid Build Coastguard Worker
2811*9880d681SAndroid Build Coastguard Worker // See if we can trivially sink this instruction to a successor basic block.
2812*9880d681SAndroid Build Coastguard Worker if (I->hasOneUse()) {
2813*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = I->getParent();
2814*9880d681SAndroid Build Coastguard Worker Instruction *UserInst = cast<Instruction>(*I->user_begin());
2815*9880d681SAndroid Build Coastguard Worker BasicBlock *UserParent;
2816*9880d681SAndroid Build Coastguard Worker
2817*9880d681SAndroid Build Coastguard Worker // Get the block the use occurs in.
2818*9880d681SAndroid Build Coastguard Worker if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2819*9880d681SAndroid Build Coastguard Worker UserParent = PN->getIncomingBlock(*I->use_begin());
2820*9880d681SAndroid Build Coastguard Worker else
2821*9880d681SAndroid Build Coastguard Worker UserParent = UserInst->getParent();
2822*9880d681SAndroid Build Coastguard Worker
2823*9880d681SAndroid Build Coastguard Worker if (UserParent != BB) {
2824*9880d681SAndroid Build Coastguard Worker bool UserIsSuccessor = false;
2825*9880d681SAndroid Build Coastguard Worker // See if the user is one of our successors.
2826*9880d681SAndroid Build Coastguard Worker for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2827*9880d681SAndroid Build Coastguard Worker if (*SI == UserParent) {
2828*9880d681SAndroid Build Coastguard Worker UserIsSuccessor = true;
2829*9880d681SAndroid Build Coastguard Worker break;
2830*9880d681SAndroid Build Coastguard Worker }
2831*9880d681SAndroid Build Coastguard Worker
2832*9880d681SAndroid Build Coastguard Worker // If the user is one of our immediate successors, and if that successor
2833*9880d681SAndroid Build Coastguard Worker // only has us as a predecessors (we'd have to split the critical edge
2834*9880d681SAndroid Build Coastguard Worker // otherwise), we can keep going.
2835*9880d681SAndroid Build Coastguard Worker if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2836*9880d681SAndroid Build Coastguard Worker // Okay, the CFG is simple enough, try to sink this instruction.
2837*9880d681SAndroid Build Coastguard Worker if (TryToSinkInstruction(I, UserParent)) {
2838*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
2839*9880d681SAndroid Build Coastguard Worker MadeIRChange = true;
2840*9880d681SAndroid Build Coastguard Worker // We'll add uses of the sunk instruction below, but since sinking
2841*9880d681SAndroid Build Coastguard Worker // can expose opportunities for it's *operands* add them to the
2842*9880d681SAndroid Build Coastguard Worker // worklist
2843*9880d681SAndroid Build Coastguard Worker for (Use &U : I->operands())
2844*9880d681SAndroid Build Coastguard Worker if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2845*9880d681SAndroid Build Coastguard Worker Worklist.Add(OpI);
2846*9880d681SAndroid Build Coastguard Worker }
2847*9880d681SAndroid Build Coastguard Worker }
2848*9880d681SAndroid Build Coastguard Worker }
2849*9880d681SAndroid Build Coastguard Worker }
2850*9880d681SAndroid Build Coastguard Worker
2851*9880d681SAndroid Build Coastguard Worker // Now that we have an instruction, try combining it to simplify it.
2852*9880d681SAndroid Build Coastguard Worker Builder->SetInsertPoint(I);
2853*9880d681SAndroid Build Coastguard Worker Builder->SetCurrentDebugLocation(I->getDebugLoc());
2854*9880d681SAndroid Build Coastguard Worker
2855*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
2856*9880d681SAndroid Build Coastguard Worker std::string OrigI;
2857*9880d681SAndroid Build Coastguard Worker #endif
2858*9880d681SAndroid Build Coastguard Worker DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2859*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2860*9880d681SAndroid Build Coastguard Worker
2861*9880d681SAndroid Build Coastguard Worker if (Instruction *Result = visit(*I)) {
2862*9880d681SAndroid Build Coastguard Worker ++NumCombined;
2863*9880d681SAndroid Build Coastguard Worker // Should we replace the old instruction with a new one?
2864*9880d681SAndroid Build Coastguard Worker if (Result != I) {
2865*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2866*9880d681SAndroid Build Coastguard Worker << " New = " << *Result << '\n');
2867*9880d681SAndroid Build Coastguard Worker
2868*9880d681SAndroid Build Coastguard Worker if (I->getDebugLoc())
2869*9880d681SAndroid Build Coastguard Worker Result->setDebugLoc(I->getDebugLoc());
2870*9880d681SAndroid Build Coastguard Worker // Everything uses the new instruction now.
2871*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(Result);
2872*9880d681SAndroid Build Coastguard Worker
2873*9880d681SAndroid Build Coastguard Worker // Move the name to the new instruction first.
2874*9880d681SAndroid Build Coastguard Worker Result->takeName(I);
2875*9880d681SAndroid Build Coastguard Worker
2876*9880d681SAndroid Build Coastguard Worker // Push the new instruction and any users onto the worklist.
2877*9880d681SAndroid Build Coastguard Worker Worklist.Add(Result);
2878*9880d681SAndroid Build Coastguard Worker Worklist.AddUsersToWorkList(*Result);
2879*9880d681SAndroid Build Coastguard Worker
2880*9880d681SAndroid Build Coastguard Worker // Insert the new instruction into the basic block...
2881*9880d681SAndroid Build Coastguard Worker BasicBlock *InstParent = I->getParent();
2882*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator InsertPos = I->getIterator();
2883*9880d681SAndroid Build Coastguard Worker
2884*9880d681SAndroid Build Coastguard Worker // If we replace a PHI with something that isn't a PHI, fix up the
2885*9880d681SAndroid Build Coastguard Worker // insertion point.
2886*9880d681SAndroid Build Coastguard Worker if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2887*9880d681SAndroid Build Coastguard Worker InsertPos = InstParent->getFirstInsertionPt();
2888*9880d681SAndroid Build Coastguard Worker
2889*9880d681SAndroid Build Coastguard Worker InstParent->getInstList().insert(InsertPos, Result);
2890*9880d681SAndroid Build Coastguard Worker
2891*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*I);
2892*9880d681SAndroid Build Coastguard Worker } else {
2893*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
2894*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2895*9880d681SAndroid Build Coastguard Worker << " New = " << *I << '\n');
2896*9880d681SAndroid Build Coastguard Worker #endif
2897*9880d681SAndroid Build Coastguard Worker
2898*9880d681SAndroid Build Coastguard Worker // If the instruction was modified, it's possible that it is now dead.
2899*9880d681SAndroid Build Coastguard Worker // if so, remove it.
2900*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(I, TLI)) {
2901*9880d681SAndroid Build Coastguard Worker eraseInstFromFunction(*I);
2902*9880d681SAndroid Build Coastguard Worker } else {
2903*9880d681SAndroid Build Coastguard Worker Worklist.Add(I);
2904*9880d681SAndroid Build Coastguard Worker Worklist.AddUsersToWorkList(*I);
2905*9880d681SAndroid Build Coastguard Worker }
2906*9880d681SAndroid Build Coastguard Worker }
2907*9880d681SAndroid Build Coastguard Worker MadeIRChange = true;
2908*9880d681SAndroid Build Coastguard Worker }
2909*9880d681SAndroid Build Coastguard Worker }
2910*9880d681SAndroid Build Coastguard Worker
2911*9880d681SAndroid Build Coastguard Worker Worklist.Zap();
2912*9880d681SAndroid Build Coastguard Worker return MadeIRChange;
2913*9880d681SAndroid Build Coastguard Worker }
2914*9880d681SAndroid Build Coastguard Worker
2915*9880d681SAndroid Build Coastguard Worker /// Walk the function in depth-first order, adding all reachable code to the
2916*9880d681SAndroid Build Coastguard Worker /// worklist.
2917*9880d681SAndroid Build Coastguard Worker ///
2918*9880d681SAndroid Build Coastguard Worker /// This has a couple of tricks to make the code faster and more powerful. In
2919*9880d681SAndroid Build Coastguard Worker /// particular, we constant fold and DCE instructions as we go, to avoid adding
2920*9880d681SAndroid Build Coastguard Worker /// them to the worklist (this significantly speeds up instcombine on code where
2921*9880d681SAndroid Build Coastguard Worker /// many instructions are dead or constant). Additionally, if we find a branch
2922*9880d681SAndroid Build Coastguard Worker /// whose condition is a known constant, we only visit the reachable successors.
2923*9880d681SAndroid Build Coastguard Worker ///
AddReachableCodeToWorklist(BasicBlock * BB,const DataLayout & DL,SmallPtrSetImpl<BasicBlock * > & Visited,InstCombineWorklist & ICWorklist,const TargetLibraryInfo * TLI)2924*9880d681SAndroid Build Coastguard Worker static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2925*9880d681SAndroid Build Coastguard Worker SmallPtrSetImpl<BasicBlock *> &Visited,
2926*9880d681SAndroid Build Coastguard Worker InstCombineWorklist &ICWorklist,
2927*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo *TLI) {
2928*9880d681SAndroid Build Coastguard Worker bool MadeIRChange = false;
2929*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock*, 256> Worklist;
2930*9880d681SAndroid Build Coastguard Worker Worklist.push_back(BB);
2931*9880d681SAndroid Build Coastguard Worker
2932*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2933*9880d681SAndroid Build Coastguard Worker DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2934*9880d681SAndroid Build Coastguard Worker
2935*9880d681SAndroid Build Coastguard Worker do {
2936*9880d681SAndroid Build Coastguard Worker BB = Worklist.pop_back_val();
2937*9880d681SAndroid Build Coastguard Worker
2938*9880d681SAndroid Build Coastguard Worker // We have now visited this block! If we've already been here, ignore it.
2939*9880d681SAndroid Build Coastguard Worker if (!Visited.insert(BB).second)
2940*9880d681SAndroid Build Coastguard Worker continue;
2941*9880d681SAndroid Build Coastguard Worker
2942*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2943*9880d681SAndroid Build Coastguard Worker Instruction *Inst = &*BBI++;
2944*9880d681SAndroid Build Coastguard Worker
2945*9880d681SAndroid Build Coastguard Worker // DCE instruction if trivially dead.
2946*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(Inst, TLI)) {
2947*9880d681SAndroid Build Coastguard Worker ++NumDeadInst;
2948*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2949*9880d681SAndroid Build Coastguard Worker Inst->eraseFromParent();
2950*9880d681SAndroid Build Coastguard Worker continue;
2951*9880d681SAndroid Build Coastguard Worker }
2952*9880d681SAndroid Build Coastguard Worker
2953*9880d681SAndroid Build Coastguard Worker // ConstantProp instruction if trivially constant.
2954*9880d681SAndroid Build Coastguard Worker if (!Inst->use_empty() &&
2955*9880d681SAndroid Build Coastguard Worker (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
2956*9880d681SAndroid Build Coastguard Worker if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2957*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2958*9880d681SAndroid Build Coastguard Worker << *Inst << '\n');
2959*9880d681SAndroid Build Coastguard Worker Inst->replaceAllUsesWith(C);
2960*9880d681SAndroid Build Coastguard Worker ++NumConstProp;
2961*9880d681SAndroid Build Coastguard Worker Inst->eraseFromParent();
2962*9880d681SAndroid Build Coastguard Worker continue;
2963*9880d681SAndroid Build Coastguard Worker }
2964*9880d681SAndroid Build Coastguard Worker
2965*9880d681SAndroid Build Coastguard Worker // See if we can constant fold its operands.
2966*9880d681SAndroid Build Coastguard Worker for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2967*9880d681SAndroid Build Coastguard Worker ++i) {
2968*9880d681SAndroid Build Coastguard Worker ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2969*9880d681SAndroid Build Coastguard Worker if (CE == nullptr)
2970*9880d681SAndroid Build Coastguard Worker continue;
2971*9880d681SAndroid Build Coastguard Worker
2972*9880d681SAndroid Build Coastguard Worker Constant *&FoldRes = FoldedConstants[CE];
2973*9880d681SAndroid Build Coastguard Worker if (!FoldRes)
2974*9880d681SAndroid Build Coastguard Worker FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2975*9880d681SAndroid Build Coastguard Worker if (!FoldRes)
2976*9880d681SAndroid Build Coastguard Worker FoldRes = CE;
2977*9880d681SAndroid Build Coastguard Worker
2978*9880d681SAndroid Build Coastguard Worker if (FoldRes != CE) {
2979*9880d681SAndroid Build Coastguard Worker *i = FoldRes;
2980*9880d681SAndroid Build Coastguard Worker MadeIRChange = true;
2981*9880d681SAndroid Build Coastguard Worker }
2982*9880d681SAndroid Build Coastguard Worker }
2983*9880d681SAndroid Build Coastguard Worker
2984*9880d681SAndroid Build Coastguard Worker InstrsForInstCombineWorklist.push_back(Inst);
2985*9880d681SAndroid Build Coastguard Worker }
2986*9880d681SAndroid Build Coastguard Worker
2987*9880d681SAndroid Build Coastguard Worker // Recursively visit successors. If this is a branch or switch on a
2988*9880d681SAndroid Build Coastguard Worker // constant, only visit the reachable successor.
2989*9880d681SAndroid Build Coastguard Worker TerminatorInst *TI = BB->getTerminator();
2990*9880d681SAndroid Build Coastguard Worker if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2991*9880d681SAndroid Build Coastguard Worker if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2992*9880d681SAndroid Build Coastguard Worker bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2993*9880d681SAndroid Build Coastguard Worker BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2994*9880d681SAndroid Build Coastguard Worker Worklist.push_back(ReachableBB);
2995*9880d681SAndroid Build Coastguard Worker continue;
2996*9880d681SAndroid Build Coastguard Worker }
2997*9880d681SAndroid Build Coastguard Worker } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2998*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2999*9880d681SAndroid Build Coastguard Worker // See if this is an explicit destination.
3000*9880d681SAndroid Build Coastguard Worker for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3001*9880d681SAndroid Build Coastguard Worker i != e; ++i)
3002*9880d681SAndroid Build Coastguard Worker if (i.getCaseValue() == Cond) {
3003*9880d681SAndroid Build Coastguard Worker BasicBlock *ReachableBB = i.getCaseSuccessor();
3004*9880d681SAndroid Build Coastguard Worker Worklist.push_back(ReachableBB);
3005*9880d681SAndroid Build Coastguard Worker continue;
3006*9880d681SAndroid Build Coastguard Worker }
3007*9880d681SAndroid Build Coastguard Worker
3008*9880d681SAndroid Build Coastguard Worker // Otherwise it is the default destination.
3009*9880d681SAndroid Build Coastguard Worker Worklist.push_back(SI->getDefaultDest());
3010*9880d681SAndroid Build Coastguard Worker continue;
3011*9880d681SAndroid Build Coastguard Worker }
3012*9880d681SAndroid Build Coastguard Worker }
3013*9880d681SAndroid Build Coastguard Worker
3014*9880d681SAndroid Build Coastguard Worker for (BasicBlock *SuccBB : TI->successors())
3015*9880d681SAndroid Build Coastguard Worker Worklist.push_back(SuccBB);
3016*9880d681SAndroid Build Coastguard Worker } while (!Worklist.empty());
3017*9880d681SAndroid Build Coastguard Worker
3018*9880d681SAndroid Build Coastguard Worker // Once we've found all of the instructions to add to instcombine's worklist,
3019*9880d681SAndroid Build Coastguard Worker // add them in reverse order. This way instcombine will visit from the top
3020*9880d681SAndroid Build Coastguard Worker // of the function down. This jives well with the way that it adds all uses
3021*9880d681SAndroid Build Coastguard Worker // of instructions to the worklist after doing a transformation, thus avoiding
3022*9880d681SAndroid Build Coastguard Worker // some N^2 behavior in pathological cases.
3023*9880d681SAndroid Build Coastguard Worker ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3024*9880d681SAndroid Build Coastguard Worker
3025*9880d681SAndroid Build Coastguard Worker return MadeIRChange;
3026*9880d681SAndroid Build Coastguard Worker }
3027*9880d681SAndroid Build Coastguard Worker
3028*9880d681SAndroid Build Coastguard Worker /// \brief Populate the IC worklist from a function, and prune any dead basic
3029*9880d681SAndroid Build Coastguard Worker /// blocks discovered in the process.
3030*9880d681SAndroid Build Coastguard Worker ///
3031*9880d681SAndroid Build Coastguard Worker /// This also does basic constant propagation and other forward fixing to make
3032*9880d681SAndroid Build Coastguard Worker /// the combiner itself run much faster.
prepareICWorklistFromFunction(Function & F,const DataLayout & DL,TargetLibraryInfo * TLI,InstCombineWorklist & ICWorklist)3033*9880d681SAndroid Build Coastguard Worker static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3034*9880d681SAndroid Build Coastguard Worker TargetLibraryInfo *TLI,
3035*9880d681SAndroid Build Coastguard Worker InstCombineWorklist &ICWorklist) {
3036*9880d681SAndroid Build Coastguard Worker bool MadeIRChange = false;
3037*9880d681SAndroid Build Coastguard Worker
3038*9880d681SAndroid Build Coastguard Worker // Do a depth-first traversal of the function, populate the worklist with
3039*9880d681SAndroid Build Coastguard Worker // the reachable instructions. Ignore blocks that are not reachable. Keep
3040*9880d681SAndroid Build Coastguard Worker // track of which blocks we visit.
3041*9880d681SAndroid Build Coastguard Worker SmallPtrSet<BasicBlock *, 32> Visited;
3042*9880d681SAndroid Build Coastguard Worker MadeIRChange |=
3043*9880d681SAndroid Build Coastguard Worker AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3044*9880d681SAndroid Build Coastguard Worker
3045*9880d681SAndroid Build Coastguard Worker // Do a quick scan over the function. If we find any blocks that are
3046*9880d681SAndroid Build Coastguard Worker // unreachable, remove any instructions inside of them. This prevents
3047*9880d681SAndroid Build Coastguard Worker // the instcombine code from having to deal with some bad special cases.
3048*9880d681SAndroid Build Coastguard Worker for (BasicBlock &BB : F) {
3049*9880d681SAndroid Build Coastguard Worker if (Visited.count(&BB))
3050*9880d681SAndroid Build Coastguard Worker continue;
3051*9880d681SAndroid Build Coastguard Worker
3052*9880d681SAndroid Build Coastguard Worker unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3053*9880d681SAndroid Build Coastguard Worker MadeIRChange |= NumDeadInstInBB > 0;
3054*9880d681SAndroid Build Coastguard Worker NumDeadInst += NumDeadInstInBB;
3055*9880d681SAndroid Build Coastguard Worker }
3056*9880d681SAndroid Build Coastguard Worker
3057*9880d681SAndroid Build Coastguard Worker return MadeIRChange;
3058*9880d681SAndroid Build Coastguard Worker }
3059*9880d681SAndroid Build Coastguard Worker
3060*9880d681SAndroid Build Coastguard Worker static bool
combineInstructionsOverFunction(Function & F,InstCombineWorklist & Worklist,AliasAnalysis * AA,AssumptionCache & AC,TargetLibraryInfo & TLI,DominatorTree & DT,bool ExpensiveCombines=true,LoopInfo * LI=nullptr)3061*9880d681SAndroid Build Coastguard Worker combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
3062*9880d681SAndroid Build Coastguard Worker AliasAnalysis *AA, AssumptionCache &AC,
3063*9880d681SAndroid Build Coastguard Worker TargetLibraryInfo &TLI, DominatorTree &DT,
3064*9880d681SAndroid Build Coastguard Worker bool ExpensiveCombines = true,
3065*9880d681SAndroid Build Coastguard Worker LoopInfo *LI = nullptr) {
3066*9880d681SAndroid Build Coastguard Worker auto &DL = F.getParent()->getDataLayout();
3067*9880d681SAndroid Build Coastguard Worker ExpensiveCombines |= EnableExpensiveCombines;
3068*9880d681SAndroid Build Coastguard Worker
3069*9880d681SAndroid Build Coastguard Worker /// Builder - This is an IRBuilder that automatically inserts new
3070*9880d681SAndroid Build Coastguard Worker /// instructions into the worklist when they are created.
3071*9880d681SAndroid Build Coastguard Worker IRBuilder<TargetFolder, InstCombineIRInserter> Builder(
3072*9880d681SAndroid Build Coastguard Worker F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
3073*9880d681SAndroid Build Coastguard Worker
3074*9880d681SAndroid Build Coastguard Worker // Lower dbg.declare intrinsics otherwise their value may be clobbered
3075*9880d681SAndroid Build Coastguard Worker // by instcombiner.
3076*9880d681SAndroid Build Coastguard Worker bool DbgDeclaresChanged = LowerDbgDeclare(F);
3077*9880d681SAndroid Build Coastguard Worker
3078*9880d681SAndroid Build Coastguard Worker // Iterate while there is work to do.
3079*9880d681SAndroid Build Coastguard Worker int Iteration = 0;
3080*9880d681SAndroid Build Coastguard Worker for (;;) {
3081*9880d681SAndroid Build Coastguard Worker ++Iteration;
3082*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3083*9880d681SAndroid Build Coastguard Worker << F.getName() << "\n");
3084*9880d681SAndroid Build Coastguard Worker
3085*9880d681SAndroid Build Coastguard Worker bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3086*9880d681SAndroid Build Coastguard Worker
3087*9880d681SAndroid Build Coastguard Worker InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines,
3088*9880d681SAndroid Build Coastguard Worker AA, &AC, &TLI, &DT, DL, LI);
3089*9880d681SAndroid Build Coastguard Worker Changed |= IC.run();
3090*9880d681SAndroid Build Coastguard Worker
3091*9880d681SAndroid Build Coastguard Worker if (!Changed)
3092*9880d681SAndroid Build Coastguard Worker break;
3093*9880d681SAndroid Build Coastguard Worker }
3094*9880d681SAndroid Build Coastguard Worker
3095*9880d681SAndroid Build Coastguard Worker return DbgDeclaresChanged || Iteration > 1;
3096*9880d681SAndroid Build Coastguard Worker }
3097*9880d681SAndroid Build Coastguard Worker
run(Function & F,AnalysisManager<Function> & AM)3098*9880d681SAndroid Build Coastguard Worker PreservedAnalyses InstCombinePass::run(Function &F,
3099*9880d681SAndroid Build Coastguard Worker AnalysisManager<Function> &AM) {
3100*9880d681SAndroid Build Coastguard Worker auto &AC = AM.getResult<AssumptionAnalysis>(F);
3101*9880d681SAndroid Build Coastguard Worker auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3102*9880d681SAndroid Build Coastguard Worker auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3103*9880d681SAndroid Build Coastguard Worker
3104*9880d681SAndroid Build Coastguard Worker auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3105*9880d681SAndroid Build Coastguard Worker
3106*9880d681SAndroid Build Coastguard Worker // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3107*9880d681SAndroid Build Coastguard Worker if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT,
3108*9880d681SAndroid Build Coastguard Worker ExpensiveCombines, LI))
3109*9880d681SAndroid Build Coastguard Worker // No changes, all analyses are preserved.
3110*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::all();
3111*9880d681SAndroid Build Coastguard Worker
3112*9880d681SAndroid Build Coastguard Worker // Mark all the analyses that instcombine updates as preserved.
3113*9880d681SAndroid Build Coastguard Worker // FIXME: This should also 'preserve the CFG'.
3114*9880d681SAndroid Build Coastguard Worker PreservedAnalyses PA;
3115*9880d681SAndroid Build Coastguard Worker PA.preserve<DominatorTreeAnalysis>();
3116*9880d681SAndroid Build Coastguard Worker return PA;
3117*9880d681SAndroid Build Coastguard Worker }
3118*9880d681SAndroid Build Coastguard Worker
getAnalysisUsage(AnalysisUsage & AU) const3119*9880d681SAndroid Build Coastguard Worker void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3120*9880d681SAndroid Build Coastguard Worker AU.setPreservesCFG();
3121*9880d681SAndroid Build Coastguard Worker AU.addRequired<AAResultsWrapperPass>();
3122*9880d681SAndroid Build Coastguard Worker AU.addRequired<AssumptionCacheTracker>();
3123*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetLibraryInfoWrapperPass>();
3124*9880d681SAndroid Build Coastguard Worker AU.addRequired<DominatorTreeWrapperPass>();
3125*9880d681SAndroid Build Coastguard Worker AU.addPreserved<DominatorTreeWrapperPass>();
3126*9880d681SAndroid Build Coastguard Worker AU.addPreserved<AAResultsWrapperPass>();
3127*9880d681SAndroid Build Coastguard Worker AU.addPreserved<BasicAAWrapperPass>();
3128*9880d681SAndroid Build Coastguard Worker AU.addPreserved<GlobalsAAWrapperPass>();
3129*9880d681SAndroid Build Coastguard Worker }
3130*9880d681SAndroid Build Coastguard Worker
runOnFunction(Function & F)3131*9880d681SAndroid Build Coastguard Worker bool InstructionCombiningPass::runOnFunction(Function &F) {
3132*9880d681SAndroid Build Coastguard Worker if (skipFunction(F))
3133*9880d681SAndroid Build Coastguard Worker return false;
3134*9880d681SAndroid Build Coastguard Worker
3135*9880d681SAndroid Build Coastguard Worker // Required analyses.
3136*9880d681SAndroid Build Coastguard Worker auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3137*9880d681SAndroid Build Coastguard Worker auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3138*9880d681SAndroid Build Coastguard Worker auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3139*9880d681SAndroid Build Coastguard Worker auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3140*9880d681SAndroid Build Coastguard Worker
3141*9880d681SAndroid Build Coastguard Worker // Optional analyses.
3142*9880d681SAndroid Build Coastguard Worker auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3143*9880d681SAndroid Build Coastguard Worker auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3144*9880d681SAndroid Build Coastguard Worker
3145*9880d681SAndroid Build Coastguard Worker return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT,
3146*9880d681SAndroid Build Coastguard Worker ExpensiveCombines, LI);
3147*9880d681SAndroid Build Coastguard Worker }
3148*9880d681SAndroid Build Coastguard Worker
3149*9880d681SAndroid Build Coastguard Worker char InstructionCombiningPass::ID = 0;
3150*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3151*9880d681SAndroid Build Coastguard Worker "Combine redundant instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)3152*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3153*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3154*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3155*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3156*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3157*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3158*9880d681SAndroid Build Coastguard Worker "Combine redundant instructions", false, false)
3159*9880d681SAndroid Build Coastguard Worker
3160*9880d681SAndroid Build Coastguard Worker // Initialization Routines
3161*9880d681SAndroid Build Coastguard Worker void llvm::initializeInstCombine(PassRegistry &Registry) {
3162*9880d681SAndroid Build Coastguard Worker initializeInstructionCombiningPassPass(Registry);
3163*9880d681SAndroid Build Coastguard Worker }
3164*9880d681SAndroid Build Coastguard Worker
LLVMInitializeInstCombine(LLVMPassRegistryRef R)3165*9880d681SAndroid Build Coastguard Worker void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3166*9880d681SAndroid Build Coastguard Worker initializeInstructionCombiningPassPass(*unwrap(R));
3167*9880d681SAndroid Build Coastguard Worker }
3168*9880d681SAndroid Build Coastguard Worker
createInstructionCombiningPass(bool ExpensiveCombines)3169*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3170*9880d681SAndroid Build Coastguard Worker return new InstructionCombiningPass(ExpensiveCombines);
3171*9880d681SAndroid Build Coastguard Worker }
3172