1*9880d681SAndroid Build Coastguard Worker //===-- SeparateConstOffsetFromGEP.cpp - ------------------------*- C++ -*-===//
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 // Loop unrolling may create many similar GEPs for array accesses.
11*9880d681SAndroid Build Coastguard Worker // e.g., a 2-level loop
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker // float a[32][32]; // global variable
14*9880d681SAndroid Build Coastguard Worker //
15*9880d681SAndroid Build Coastguard Worker // for (int i = 0; i < 2; ++i) {
16*9880d681SAndroid Build Coastguard Worker // for (int j = 0; j < 2; ++j) {
17*9880d681SAndroid Build Coastguard Worker // ...
18*9880d681SAndroid Build Coastguard Worker // ... = a[x + i][y + j];
19*9880d681SAndroid Build Coastguard Worker // ...
20*9880d681SAndroid Build Coastguard Worker // }
21*9880d681SAndroid Build Coastguard Worker // }
22*9880d681SAndroid Build Coastguard Worker //
23*9880d681SAndroid Build Coastguard Worker // will probably be unrolled to:
24*9880d681SAndroid Build Coastguard Worker //
25*9880d681SAndroid Build Coastguard Worker // gep %a, 0, %x, %y; load
26*9880d681SAndroid Build Coastguard Worker // gep %a, 0, %x, %y + 1; load
27*9880d681SAndroid Build Coastguard Worker // gep %a, 0, %x + 1, %y; load
28*9880d681SAndroid Build Coastguard Worker // gep %a, 0, %x + 1, %y + 1; load
29*9880d681SAndroid Build Coastguard Worker //
30*9880d681SAndroid Build Coastguard Worker // LLVM's GVN does not use partial redundancy elimination yet, and is thus
31*9880d681SAndroid Build Coastguard Worker // unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs
32*9880d681SAndroid Build Coastguard Worker // significant slowdown in targets with limited addressing modes. For instance,
33*9880d681SAndroid Build Coastguard Worker // because the PTX target does not support the reg+reg addressing mode, the
34*9880d681SAndroid Build Coastguard Worker // NVPTX backend emits PTX code that literally computes the pointer address of
35*9880d681SAndroid Build Coastguard Worker // each GEP, wasting tons of registers. It emits the following PTX for the
36*9880d681SAndroid Build Coastguard Worker // first load and similar PTX for other loads.
37*9880d681SAndroid Build Coastguard Worker //
38*9880d681SAndroid Build Coastguard Worker // mov.u32 %r1, %x;
39*9880d681SAndroid Build Coastguard Worker // mov.u32 %r2, %y;
40*9880d681SAndroid Build Coastguard Worker // mul.wide.u32 %rl2, %r1, 128;
41*9880d681SAndroid Build Coastguard Worker // mov.u64 %rl3, a;
42*9880d681SAndroid Build Coastguard Worker // add.s64 %rl4, %rl3, %rl2;
43*9880d681SAndroid Build Coastguard Worker // mul.wide.u32 %rl5, %r2, 4;
44*9880d681SAndroid Build Coastguard Worker // add.s64 %rl6, %rl4, %rl5;
45*9880d681SAndroid Build Coastguard Worker // ld.global.f32 %f1, [%rl6];
46*9880d681SAndroid Build Coastguard Worker //
47*9880d681SAndroid Build Coastguard Worker // To reduce the register pressure, the optimization implemented in this file
48*9880d681SAndroid Build Coastguard Worker // merges the common part of a group of GEPs, so we can compute each pointer
49*9880d681SAndroid Build Coastguard Worker // address by adding a simple offset to the common part, saving many registers.
50*9880d681SAndroid Build Coastguard Worker //
51*9880d681SAndroid Build Coastguard Worker // It works by splitting each GEP into a variadic base and a constant offset.
52*9880d681SAndroid Build Coastguard Worker // The variadic base can be computed once and reused by multiple GEPs, and the
53*9880d681SAndroid Build Coastguard Worker // constant offsets can be nicely folded into the reg+immediate addressing mode
54*9880d681SAndroid Build Coastguard Worker // (supported by most targets) without using any extra register.
55*9880d681SAndroid Build Coastguard Worker //
56*9880d681SAndroid Build Coastguard Worker // For instance, we transform the four GEPs and four loads in the above example
57*9880d681SAndroid Build Coastguard Worker // into:
58*9880d681SAndroid Build Coastguard Worker //
59*9880d681SAndroid Build Coastguard Worker // base = gep a, 0, x, y
60*9880d681SAndroid Build Coastguard Worker // load base
61*9880d681SAndroid Build Coastguard Worker // laod base + 1 * sizeof(float)
62*9880d681SAndroid Build Coastguard Worker // load base + 32 * sizeof(float)
63*9880d681SAndroid Build Coastguard Worker // load base + 33 * sizeof(float)
64*9880d681SAndroid Build Coastguard Worker //
65*9880d681SAndroid Build Coastguard Worker // Given the transformed IR, a backend that supports the reg+immediate
66*9880d681SAndroid Build Coastguard Worker // addressing mode can easily fold the pointer arithmetics into the loads. For
67*9880d681SAndroid Build Coastguard Worker // example, the NVPTX backend can easily fold the pointer arithmetics into the
68*9880d681SAndroid Build Coastguard Worker // ld.global.f32 instructions, and the resultant PTX uses much fewer registers.
69*9880d681SAndroid Build Coastguard Worker //
70*9880d681SAndroid Build Coastguard Worker // mov.u32 %r1, %tid.x;
71*9880d681SAndroid Build Coastguard Worker // mov.u32 %r2, %tid.y;
72*9880d681SAndroid Build Coastguard Worker // mul.wide.u32 %rl2, %r1, 128;
73*9880d681SAndroid Build Coastguard Worker // mov.u64 %rl3, a;
74*9880d681SAndroid Build Coastguard Worker // add.s64 %rl4, %rl3, %rl2;
75*9880d681SAndroid Build Coastguard Worker // mul.wide.u32 %rl5, %r2, 4;
76*9880d681SAndroid Build Coastguard Worker // add.s64 %rl6, %rl4, %rl5;
77*9880d681SAndroid Build Coastguard Worker // ld.global.f32 %f1, [%rl6]; // so far the same as unoptimized PTX
78*9880d681SAndroid Build Coastguard Worker // ld.global.f32 %f2, [%rl6+4]; // much better
79*9880d681SAndroid Build Coastguard Worker // ld.global.f32 %f3, [%rl6+128]; // much better
80*9880d681SAndroid Build Coastguard Worker // ld.global.f32 %f4, [%rl6+132]; // much better
81*9880d681SAndroid Build Coastguard Worker //
82*9880d681SAndroid Build Coastguard Worker // Another improvement enabled by the LowerGEP flag is to lower a GEP with
83*9880d681SAndroid Build Coastguard Worker // multiple indices to either multiple GEPs with a single index or arithmetic
84*9880d681SAndroid Build Coastguard Worker // operations (depending on whether the target uses alias analysis in codegen).
85*9880d681SAndroid Build Coastguard Worker // Such transformation can have following benefits:
86*9880d681SAndroid Build Coastguard Worker // (1) It can always extract constants in the indices of structure type.
87*9880d681SAndroid Build Coastguard Worker // (2) After such Lowering, there are more optimization opportunities such as
88*9880d681SAndroid Build Coastguard Worker // CSE, LICM and CGP.
89*9880d681SAndroid Build Coastguard Worker //
90*9880d681SAndroid Build Coastguard Worker // E.g. The following GEPs have multiple indices:
91*9880d681SAndroid Build Coastguard Worker // BB1:
92*9880d681SAndroid Build Coastguard Worker // %p = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 3
93*9880d681SAndroid Build Coastguard Worker // load %p
94*9880d681SAndroid Build Coastguard Worker // ...
95*9880d681SAndroid Build Coastguard Worker // BB2:
96*9880d681SAndroid Build Coastguard Worker // %p2 = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 2
97*9880d681SAndroid Build Coastguard Worker // load %p2
98*9880d681SAndroid Build Coastguard Worker // ...
99*9880d681SAndroid Build Coastguard Worker //
100*9880d681SAndroid Build Coastguard Worker // We can not do CSE for to the common part related to index "i64 %i". Lowering
101*9880d681SAndroid Build Coastguard Worker // GEPs can achieve such goals.
102*9880d681SAndroid Build Coastguard Worker // If the target does not use alias analysis in codegen, this pass will
103*9880d681SAndroid Build Coastguard Worker // lower a GEP with multiple indices into arithmetic operations:
104*9880d681SAndroid Build Coastguard Worker // BB1:
105*9880d681SAndroid Build Coastguard Worker // %1 = ptrtoint [10 x %struct]* %ptr to i64 ; CSE opportunity
106*9880d681SAndroid Build Coastguard Worker // %2 = mul i64 %i, length_of_10xstruct ; CSE opportunity
107*9880d681SAndroid Build Coastguard Worker // %3 = add i64 %1, %2 ; CSE opportunity
108*9880d681SAndroid Build Coastguard Worker // %4 = mul i64 %j1, length_of_struct
109*9880d681SAndroid Build Coastguard Worker // %5 = add i64 %3, %4
110*9880d681SAndroid Build Coastguard Worker // %6 = add i64 %3, struct_field_3 ; Constant offset
111*9880d681SAndroid Build Coastguard Worker // %p = inttoptr i64 %6 to i32*
112*9880d681SAndroid Build Coastguard Worker // load %p
113*9880d681SAndroid Build Coastguard Worker // ...
114*9880d681SAndroid Build Coastguard Worker // BB2:
115*9880d681SAndroid Build Coastguard Worker // %7 = ptrtoint [10 x %struct]* %ptr to i64 ; CSE opportunity
116*9880d681SAndroid Build Coastguard Worker // %8 = mul i64 %i, length_of_10xstruct ; CSE opportunity
117*9880d681SAndroid Build Coastguard Worker // %9 = add i64 %7, %8 ; CSE opportunity
118*9880d681SAndroid Build Coastguard Worker // %10 = mul i64 %j2, length_of_struct
119*9880d681SAndroid Build Coastguard Worker // %11 = add i64 %9, %10
120*9880d681SAndroid Build Coastguard Worker // %12 = add i64 %11, struct_field_2 ; Constant offset
121*9880d681SAndroid Build Coastguard Worker // %p = inttoptr i64 %12 to i32*
122*9880d681SAndroid Build Coastguard Worker // load %p2
123*9880d681SAndroid Build Coastguard Worker // ...
124*9880d681SAndroid Build Coastguard Worker //
125*9880d681SAndroid Build Coastguard Worker // If the target uses alias analysis in codegen, this pass will lower a GEP
126*9880d681SAndroid Build Coastguard Worker // with multiple indices into multiple GEPs with a single index:
127*9880d681SAndroid Build Coastguard Worker // BB1:
128*9880d681SAndroid Build Coastguard Worker // %1 = bitcast [10 x %struct]* %ptr to i8* ; CSE opportunity
129*9880d681SAndroid Build Coastguard Worker // %2 = mul i64 %i, length_of_10xstruct ; CSE opportunity
130*9880d681SAndroid Build Coastguard Worker // %3 = getelementptr i8* %1, i64 %2 ; CSE opportunity
131*9880d681SAndroid Build Coastguard Worker // %4 = mul i64 %j1, length_of_struct
132*9880d681SAndroid Build Coastguard Worker // %5 = getelementptr i8* %3, i64 %4
133*9880d681SAndroid Build Coastguard Worker // %6 = getelementptr i8* %5, struct_field_3 ; Constant offset
134*9880d681SAndroid Build Coastguard Worker // %p = bitcast i8* %6 to i32*
135*9880d681SAndroid Build Coastguard Worker // load %p
136*9880d681SAndroid Build Coastguard Worker // ...
137*9880d681SAndroid Build Coastguard Worker // BB2:
138*9880d681SAndroid Build Coastguard Worker // %7 = bitcast [10 x %struct]* %ptr to i8* ; CSE opportunity
139*9880d681SAndroid Build Coastguard Worker // %8 = mul i64 %i, length_of_10xstruct ; CSE opportunity
140*9880d681SAndroid Build Coastguard Worker // %9 = getelementptr i8* %7, i64 %8 ; CSE opportunity
141*9880d681SAndroid Build Coastguard Worker // %10 = mul i64 %j2, length_of_struct
142*9880d681SAndroid Build Coastguard Worker // %11 = getelementptr i8* %9, i64 %10
143*9880d681SAndroid Build Coastguard Worker // %12 = getelementptr i8* %11, struct_field_2 ; Constant offset
144*9880d681SAndroid Build Coastguard Worker // %p2 = bitcast i8* %12 to i32*
145*9880d681SAndroid Build Coastguard Worker // load %p2
146*9880d681SAndroid Build Coastguard Worker // ...
147*9880d681SAndroid Build Coastguard Worker //
148*9880d681SAndroid Build Coastguard Worker // Lowering GEPs can also benefit other passes such as LICM and CGP.
149*9880d681SAndroid Build Coastguard Worker // LICM (Loop Invariant Code Motion) can not hoist/sink a GEP of multiple
150*9880d681SAndroid Build Coastguard Worker // indices if one of the index is variant. If we lower such GEP into invariant
151*9880d681SAndroid Build Coastguard Worker // parts and variant parts, LICM can hoist/sink those invariant parts.
152*9880d681SAndroid Build Coastguard Worker // CGP (CodeGen Prepare) tries to sink address calculations that match the
153*9880d681SAndroid Build Coastguard Worker // target's addressing modes. A GEP with multiple indices may not match and will
154*9880d681SAndroid Build Coastguard Worker // not be sunk. If we lower such GEP into smaller parts, CGP may sink some of
155*9880d681SAndroid Build Coastguard Worker // them. So we end up with a better addressing mode.
156*9880d681SAndroid Build Coastguard Worker //
157*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
158*9880d681SAndroid Build Coastguard Worker
159*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolution.h"
160*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
161*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
162*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
163*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
164*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
165*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
166*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
167*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
168*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
169*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
170*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
171*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
172*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Operator.h"
173*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
174*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
175*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
176*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
177*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetMachine.h"
178*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetSubtargetInfo.h"
179*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
180*9880d681SAndroid Build Coastguard Worker
181*9880d681SAndroid Build Coastguard Worker using namespace llvm;
182*9880d681SAndroid Build Coastguard Worker using namespace llvm::PatternMatch;
183*9880d681SAndroid Build Coastguard Worker
184*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableSeparateConstOffsetFromGEP(
185*9880d681SAndroid Build Coastguard Worker "disable-separate-const-offset-from-gep", cl::init(false),
186*9880d681SAndroid Build Coastguard Worker cl::desc("Do not separate the constant offset from a GEP instruction"),
187*9880d681SAndroid Build Coastguard Worker cl::Hidden);
188*9880d681SAndroid Build Coastguard Worker // Setting this flag may emit false positives when the input module already
189*9880d681SAndroid Build Coastguard Worker // contains dead instructions. Therefore, we set it only in unit tests that are
190*9880d681SAndroid Build Coastguard Worker // free of dead code.
191*9880d681SAndroid Build Coastguard Worker static cl::opt<bool>
192*9880d681SAndroid Build Coastguard Worker VerifyNoDeadCode("reassociate-geps-verify-no-dead-code", cl::init(false),
193*9880d681SAndroid Build Coastguard Worker cl::desc("Verify this pass produces no dead code"),
194*9880d681SAndroid Build Coastguard Worker cl::Hidden);
195*9880d681SAndroid Build Coastguard Worker
196*9880d681SAndroid Build Coastguard Worker namespace {
197*9880d681SAndroid Build Coastguard Worker
198*9880d681SAndroid Build Coastguard Worker /// \brief A helper class for separating a constant offset from a GEP index.
199*9880d681SAndroid Build Coastguard Worker ///
200*9880d681SAndroid Build Coastguard Worker /// In real programs, a GEP index may be more complicated than a simple addition
201*9880d681SAndroid Build Coastguard Worker /// of something and a constant integer which can be trivially splitted. For
202*9880d681SAndroid Build Coastguard Worker /// example, to split ((a << 3) | 5) + b, we need to search deeper for the
203*9880d681SAndroid Build Coastguard Worker /// constant offset, so that we can separate the index to (a << 3) + b and 5.
204*9880d681SAndroid Build Coastguard Worker ///
205*9880d681SAndroid Build Coastguard Worker /// Therefore, this class looks into the expression that computes a given GEP
206*9880d681SAndroid Build Coastguard Worker /// index, and tries to find a constant integer that can be hoisted to the
207*9880d681SAndroid Build Coastguard Worker /// outermost level of the expression as an addition. Not every constant in an
208*9880d681SAndroid Build Coastguard Worker /// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
209*9880d681SAndroid Build Coastguard Worker /// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
210*9880d681SAndroid Build Coastguard Worker /// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
211*9880d681SAndroid Build Coastguard Worker class ConstantOffsetExtractor {
212*9880d681SAndroid Build Coastguard Worker public:
213*9880d681SAndroid Build Coastguard Worker /// Extracts a constant offset from the given GEP index. It returns the
214*9880d681SAndroid Build Coastguard Worker /// new index representing the remainder (equal to the original index minus
215*9880d681SAndroid Build Coastguard Worker /// the constant offset), or nullptr if we cannot extract a constant offset.
216*9880d681SAndroid Build Coastguard Worker /// \p Idx The given GEP index
217*9880d681SAndroid Build Coastguard Worker /// \p GEP The given GEP
218*9880d681SAndroid Build Coastguard Worker /// \p UserChainTail Outputs the tail of UserChain so that we can
219*9880d681SAndroid Build Coastguard Worker /// garbage-collect unused instructions in UserChain.
220*9880d681SAndroid Build Coastguard Worker static Value *Extract(Value *Idx, GetElementPtrInst *GEP,
221*9880d681SAndroid Build Coastguard Worker User *&UserChainTail, const DominatorTree *DT);
222*9880d681SAndroid Build Coastguard Worker /// Looks for a constant offset from the given GEP index without extracting
223*9880d681SAndroid Build Coastguard Worker /// it. It returns the numeric value of the extracted constant offset (0 if
224*9880d681SAndroid Build Coastguard Worker /// failed). The meaning of the arguments are the same as Extract.
225*9880d681SAndroid Build Coastguard Worker static int64_t Find(Value *Idx, GetElementPtrInst *GEP,
226*9880d681SAndroid Build Coastguard Worker const DominatorTree *DT);
227*9880d681SAndroid Build Coastguard Worker
228*9880d681SAndroid Build Coastguard Worker private:
ConstantOffsetExtractor(Instruction * InsertionPt,const DominatorTree * DT)229*9880d681SAndroid Build Coastguard Worker ConstantOffsetExtractor(Instruction *InsertionPt, const DominatorTree *DT)
230*9880d681SAndroid Build Coastguard Worker : IP(InsertionPt), DL(InsertionPt->getModule()->getDataLayout()), DT(DT) {
231*9880d681SAndroid Build Coastguard Worker }
232*9880d681SAndroid Build Coastguard Worker /// Searches the expression that computes V for a non-zero constant C s.t.
233*9880d681SAndroid Build Coastguard Worker /// V can be reassociated into the form V' + C. If the searching is
234*9880d681SAndroid Build Coastguard Worker /// successful, returns C and update UserChain as a def-use chain from C to V;
235*9880d681SAndroid Build Coastguard Worker /// otherwise, UserChain is empty.
236*9880d681SAndroid Build Coastguard Worker ///
237*9880d681SAndroid Build Coastguard Worker /// \p V The given expression
238*9880d681SAndroid Build Coastguard Worker /// \p SignExtended Whether V will be sign-extended in the computation of the
239*9880d681SAndroid Build Coastguard Worker /// GEP index
240*9880d681SAndroid Build Coastguard Worker /// \p ZeroExtended Whether V will be zero-extended in the computation of the
241*9880d681SAndroid Build Coastguard Worker /// GEP index
242*9880d681SAndroid Build Coastguard Worker /// \p NonNegative Whether V is guaranteed to be non-negative. For example,
243*9880d681SAndroid Build Coastguard Worker /// an index of an inbounds GEP is guaranteed to be
244*9880d681SAndroid Build Coastguard Worker /// non-negative. Levaraging this, we can better split
245*9880d681SAndroid Build Coastguard Worker /// inbounds GEPs.
246*9880d681SAndroid Build Coastguard Worker APInt find(Value *V, bool SignExtended, bool ZeroExtended, bool NonNegative);
247*9880d681SAndroid Build Coastguard Worker /// A helper function to look into both operands of a binary operator.
248*9880d681SAndroid Build Coastguard Worker APInt findInEitherOperand(BinaryOperator *BO, bool SignExtended,
249*9880d681SAndroid Build Coastguard Worker bool ZeroExtended);
250*9880d681SAndroid Build Coastguard Worker /// After finding the constant offset C from the GEP index I, we build a new
251*9880d681SAndroid Build Coastguard Worker /// index I' s.t. I' + C = I. This function builds and returns the new
252*9880d681SAndroid Build Coastguard Worker /// index I' according to UserChain produced by function "find".
253*9880d681SAndroid Build Coastguard Worker ///
254*9880d681SAndroid Build Coastguard Worker /// The building conceptually takes two steps:
255*9880d681SAndroid Build Coastguard Worker /// 1) iteratively distribute s/zext towards the leaves of the expression tree
256*9880d681SAndroid Build Coastguard Worker /// that computes I
257*9880d681SAndroid Build Coastguard Worker /// 2) reassociate the expression tree to the form I' + C.
258*9880d681SAndroid Build Coastguard Worker ///
259*9880d681SAndroid Build Coastguard Worker /// For example, to extract the 5 from sext(a + (b + 5)), we first distribute
260*9880d681SAndroid Build Coastguard Worker /// sext to a, b and 5 so that we have
261*9880d681SAndroid Build Coastguard Worker /// sext(a) + (sext(b) + 5).
262*9880d681SAndroid Build Coastguard Worker /// Then, we reassociate it to
263*9880d681SAndroid Build Coastguard Worker /// (sext(a) + sext(b)) + 5.
264*9880d681SAndroid Build Coastguard Worker /// Given this form, we know I' is sext(a) + sext(b).
265*9880d681SAndroid Build Coastguard Worker Value *rebuildWithoutConstOffset();
266*9880d681SAndroid Build Coastguard Worker /// After the first step of rebuilding the GEP index without the constant
267*9880d681SAndroid Build Coastguard Worker /// offset, distribute s/zext to the operands of all operators in UserChain.
268*9880d681SAndroid Build Coastguard Worker /// e.g., zext(sext(a + (b + 5)) (assuming no overflow) =>
269*9880d681SAndroid Build Coastguard Worker /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))).
270*9880d681SAndroid Build Coastguard Worker ///
271*9880d681SAndroid Build Coastguard Worker /// The function also updates UserChain to point to new subexpressions after
272*9880d681SAndroid Build Coastguard Worker /// distributing s/zext. e.g., the old UserChain of the above example is
273*9880d681SAndroid Build Coastguard Worker /// 5 -> b + 5 -> a + (b + 5) -> sext(...) -> zext(sext(...)),
274*9880d681SAndroid Build Coastguard Worker /// and the new UserChain is
275*9880d681SAndroid Build Coastguard Worker /// zext(sext(5)) -> zext(sext(b)) + zext(sext(5)) ->
276*9880d681SAndroid Build Coastguard Worker /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))
277*9880d681SAndroid Build Coastguard Worker ///
278*9880d681SAndroid Build Coastguard Worker /// \p ChainIndex The index to UserChain. ChainIndex is initially
279*9880d681SAndroid Build Coastguard Worker /// UserChain.size() - 1, and is decremented during
280*9880d681SAndroid Build Coastguard Worker /// the recursion.
281*9880d681SAndroid Build Coastguard Worker Value *distributeExtsAndCloneChain(unsigned ChainIndex);
282*9880d681SAndroid Build Coastguard Worker /// Reassociates the GEP index to the form I' + C and returns I'.
283*9880d681SAndroid Build Coastguard Worker Value *removeConstOffset(unsigned ChainIndex);
284*9880d681SAndroid Build Coastguard Worker /// A helper function to apply ExtInsts, a list of s/zext, to value V.
285*9880d681SAndroid Build Coastguard Worker /// e.g., if ExtInsts = [sext i32 to i64, zext i16 to i32], this function
286*9880d681SAndroid Build Coastguard Worker /// returns "sext i32 (zext i16 V to i32) to i64".
287*9880d681SAndroid Build Coastguard Worker Value *applyExts(Value *V);
288*9880d681SAndroid Build Coastguard Worker
289*9880d681SAndroid Build Coastguard Worker /// A helper function that returns whether we can trace into the operands
290*9880d681SAndroid Build Coastguard Worker /// of binary operator BO for a constant offset.
291*9880d681SAndroid Build Coastguard Worker ///
292*9880d681SAndroid Build Coastguard Worker /// \p SignExtended Whether BO is surrounded by sext
293*9880d681SAndroid Build Coastguard Worker /// \p ZeroExtended Whether BO is surrounded by zext
294*9880d681SAndroid Build Coastguard Worker /// \p NonNegative Whether BO is known to be non-negative, e.g., an in-bound
295*9880d681SAndroid Build Coastguard Worker /// array index.
296*9880d681SAndroid Build Coastguard Worker bool CanTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
297*9880d681SAndroid Build Coastguard Worker bool NonNegative);
298*9880d681SAndroid Build Coastguard Worker
299*9880d681SAndroid Build Coastguard Worker /// The path from the constant offset to the old GEP index. e.g., if the GEP
300*9880d681SAndroid Build Coastguard Worker /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
301*9880d681SAndroid Build Coastguard Worker /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
302*9880d681SAndroid Build Coastguard Worker /// UserChain[2] will be the entire expression "a * b + (c + 5)".
303*9880d681SAndroid Build Coastguard Worker ///
304*9880d681SAndroid Build Coastguard Worker /// This path helps to rebuild the new GEP index.
305*9880d681SAndroid Build Coastguard Worker SmallVector<User *, 8> UserChain;
306*9880d681SAndroid Build Coastguard Worker /// A data structure used in rebuildWithoutConstOffset. Contains all
307*9880d681SAndroid Build Coastguard Worker /// sext/zext instructions along UserChain.
308*9880d681SAndroid Build Coastguard Worker SmallVector<CastInst *, 16> ExtInsts;
309*9880d681SAndroid Build Coastguard Worker Instruction *IP; /// Insertion position of cloned instructions.
310*9880d681SAndroid Build Coastguard Worker const DataLayout &DL;
311*9880d681SAndroid Build Coastguard Worker const DominatorTree *DT;
312*9880d681SAndroid Build Coastguard Worker };
313*9880d681SAndroid Build Coastguard Worker
314*9880d681SAndroid Build Coastguard Worker /// \brief A pass that tries to split every GEP in the function into a variadic
315*9880d681SAndroid Build Coastguard Worker /// base and a constant offset. It is a FunctionPass because searching for the
316*9880d681SAndroid Build Coastguard Worker /// constant offset may inspect other basic blocks.
317*9880d681SAndroid Build Coastguard Worker class SeparateConstOffsetFromGEP : public FunctionPass {
318*9880d681SAndroid Build Coastguard Worker public:
319*9880d681SAndroid Build Coastguard Worker static char ID;
SeparateConstOffsetFromGEP(const TargetMachine * TM=nullptr,bool LowerGEP=false)320*9880d681SAndroid Build Coastguard Worker SeparateConstOffsetFromGEP(const TargetMachine *TM = nullptr,
321*9880d681SAndroid Build Coastguard Worker bool LowerGEP = false)
322*9880d681SAndroid Build Coastguard Worker : FunctionPass(ID), DL(nullptr), DT(nullptr), TM(TM), LowerGEP(LowerGEP) {
323*9880d681SAndroid Build Coastguard Worker initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry());
324*9880d681SAndroid Build Coastguard Worker }
325*9880d681SAndroid Build Coastguard Worker
getAnalysisUsage(AnalysisUsage & AU) const326*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
327*9880d681SAndroid Build Coastguard Worker AU.addRequired<DominatorTreeWrapperPass>();
328*9880d681SAndroid Build Coastguard Worker AU.addRequired<ScalarEvolutionWrapperPass>();
329*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetTransformInfoWrapperPass>();
330*9880d681SAndroid Build Coastguard Worker AU.addRequired<LoopInfoWrapperPass>();
331*9880d681SAndroid Build Coastguard Worker AU.setPreservesCFG();
332*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetLibraryInfoWrapperPass>();
333*9880d681SAndroid Build Coastguard Worker }
334*9880d681SAndroid Build Coastguard Worker
doInitialization(Module & M)335*9880d681SAndroid Build Coastguard Worker bool doInitialization(Module &M) override {
336*9880d681SAndroid Build Coastguard Worker DL = &M.getDataLayout();
337*9880d681SAndroid Build Coastguard Worker return false;
338*9880d681SAndroid Build Coastguard Worker }
339*9880d681SAndroid Build Coastguard Worker bool runOnFunction(Function &F) override;
340*9880d681SAndroid Build Coastguard Worker
341*9880d681SAndroid Build Coastguard Worker private:
342*9880d681SAndroid Build Coastguard Worker /// Tries to split the given GEP into a variadic base and a constant offset,
343*9880d681SAndroid Build Coastguard Worker /// and returns true if the splitting succeeds.
344*9880d681SAndroid Build Coastguard Worker bool splitGEP(GetElementPtrInst *GEP);
345*9880d681SAndroid Build Coastguard Worker /// Lower a GEP with multiple indices into multiple GEPs with a single index.
346*9880d681SAndroid Build Coastguard Worker /// Function splitGEP already split the original GEP into a variadic part and
347*9880d681SAndroid Build Coastguard Worker /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
348*9880d681SAndroid Build Coastguard Worker /// variadic part into a set of GEPs with a single index and applies
349*9880d681SAndroid Build Coastguard Worker /// AccumulativeByteOffset to it.
350*9880d681SAndroid Build Coastguard Worker /// \p Variadic The variadic part of the original GEP.
351*9880d681SAndroid Build Coastguard Worker /// \p AccumulativeByteOffset The constant offset.
352*9880d681SAndroid Build Coastguard Worker void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
353*9880d681SAndroid Build Coastguard Worker int64_t AccumulativeByteOffset);
354*9880d681SAndroid Build Coastguard Worker /// Lower a GEP with multiple indices into ptrtoint+arithmetics+inttoptr form.
355*9880d681SAndroid Build Coastguard Worker /// Function splitGEP already split the original GEP into a variadic part and
356*9880d681SAndroid Build Coastguard Worker /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
357*9880d681SAndroid Build Coastguard Worker /// variadic part into a set of arithmetic operations and applies
358*9880d681SAndroid Build Coastguard Worker /// AccumulativeByteOffset to it.
359*9880d681SAndroid Build Coastguard Worker /// \p Variadic The variadic part of the original GEP.
360*9880d681SAndroid Build Coastguard Worker /// \p AccumulativeByteOffset The constant offset.
361*9880d681SAndroid Build Coastguard Worker void lowerToArithmetics(GetElementPtrInst *Variadic,
362*9880d681SAndroid Build Coastguard Worker int64_t AccumulativeByteOffset);
363*9880d681SAndroid Build Coastguard Worker /// Finds the constant offset within each index and accumulates them. If
364*9880d681SAndroid Build Coastguard Worker /// LowerGEP is true, it finds in indices of both sequential and structure
365*9880d681SAndroid Build Coastguard Worker /// types, otherwise it only finds in sequential indices. The output
366*9880d681SAndroid Build Coastguard Worker /// NeedsExtraction indicates whether we successfully find a non-zero constant
367*9880d681SAndroid Build Coastguard Worker /// offset.
368*9880d681SAndroid Build Coastguard Worker int64_t accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
369*9880d681SAndroid Build Coastguard Worker /// Canonicalize array indices to pointer-size integers. This helps to
370*9880d681SAndroid Build Coastguard Worker /// simplify the logic of splitting a GEP. For example, if a + b is a
371*9880d681SAndroid Build Coastguard Worker /// pointer-size integer, we have
372*9880d681SAndroid Build Coastguard Worker /// gep base, a + b = gep (gep base, a), b
373*9880d681SAndroid Build Coastguard Worker /// However, this equality may not hold if the size of a + b is smaller than
374*9880d681SAndroid Build Coastguard Worker /// the pointer size, because LLVM conceptually sign-extends GEP indices to
375*9880d681SAndroid Build Coastguard Worker /// pointer size before computing the address
376*9880d681SAndroid Build Coastguard Worker /// (http://llvm.org/docs/LangRef.html#id181).
377*9880d681SAndroid Build Coastguard Worker ///
378*9880d681SAndroid Build Coastguard Worker /// This canonicalization is very likely already done in clang and
379*9880d681SAndroid Build Coastguard Worker /// instcombine. Therefore, the program will probably remain the same.
380*9880d681SAndroid Build Coastguard Worker ///
381*9880d681SAndroid Build Coastguard Worker /// Returns true if the module changes.
382*9880d681SAndroid Build Coastguard Worker ///
383*9880d681SAndroid Build Coastguard Worker /// Verified in @i32_add in split-gep.ll
384*9880d681SAndroid Build Coastguard Worker bool canonicalizeArrayIndicesToPointerSize(GetElementPtrInst *GEP);
385*9880d681SAndroid Build Coastguard Worker /// Optimize sext(a)+sext(b) to sext(a+b) when a+b can't sign overflow.
386*9880d681SAndroid Build Coastguard Worker /// SeparateConstOffsetFromGEP distributes a sext to leaves before extracting
387*9880d681SAndroid Build Coastguard Worker /// the constant offset. After extraction, it becomes desirable to reunion the
388*9880d681SAndroid Build Coastguard Worker /// distributed sexts. For example,
389*9880d681SAndroid Build Coastguard Worker ///
390*9880d681SAndroid Build Coastguard Worker /// &a[sext(i +nsw (j +nsw 5)]
391*9880d681SAndroid Build Coastguard Worker /// => distribute &a[sext(i) +nsw (sext(j) +nsw 5)]
392*9880d681SAndroid Build Coastguard Worker /// => constant extraction &a[sext(i) + sext(j)] + 5
393*9880d681SAndroid Build Coastguard Worker /// => reunion &a[sext(i +nsw j)] + 5
394*9880d681SAndroid Build Coastguard Worker bool reuniteExts(Function &F);
395*9880d681SAndroid Build Coastguard Worker /// A helper that reunites sexts in an instruction.
396*9880d681SAndroid Build Coastguard Worker bool reuniteExts(Instruction *I);
397*9880d681SAndroid Build Coastguard Worker /// Find the closest dominator of <Dominatee> that is equivalent to <Key>.
398*9880d681SAndroid Build Coastguard Worker Instruction *findClosestMatchingDominator(const SCEV *Key,
399*9880d681SAndroid Build Coastguard Worker Instruction *Dominatee);
400*9880d681SAndroid Build Coastguard Worker /// Verify F is free of dead code.
401*9880d681SAndroid Build Coastguard Worker void verifyNoDeadCode(Function &F);
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker bool hasMoreThanOneUseInLoop(Value *v, Loop *L);
404*9880d681SAndroid Build Coastguard Worker // Swap the index operand of two GEP.
405*9880d681SAndroid Build Coastguard Worker void swapGEPOperand(GetElementPtrInst *First, GetElementPtrInst *Second);
406*9880d681SAndroid Build Coastguard Worker // Check if it is safe to swap operand of two GEP.
407*9880d681SAndroid Build Coastguard Worker bool isLegalToSwapOperand(GetElementPtrInst *First, GetElementPtrInst *Second,
408*9880d681SAndroid Build Coastguard Worker Loop *CurLoop);
409*9880d681SAndroid Build Coastguard Worker
410*9880d681SAndroid Build Coastguard Worker const DataLayout *DL;
411*9880d681SAndroid Build Coastguard Worker DominatorTree *DT;
412*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SE;
413*9880d681SAndroid Build Coastguard Worker const TargetMachine *TM;
414*9880d681SAndroid Build Coastguard Worker
415*9880d681SAndroid Build Coastguard Worker LoopInfo *LI;
416*9880d681SAndroid Build Coastguard Worker TargetLibraryInfo *TLI;
417*9880d681SAndroid Build Coastguard Worker /// Whether to lower a GEP with multiple indices into arithmetic operations or
418*9880d681SAndroid Build Coastguard Worker /// multiple GEPs with a single index.
419*9880d681SAndroid Build Coastguard Worker bool LowerGEP;
420*9880d681SAndroid Build Coastguard Worker DenseMap<const SCEV *, SmallVector<Instruction *, 2>> DominatingExprs;
421*9880d681SAndroid Build Coastguard Worker };
422*9880d681SAndroid Build Coastguard Worker } // anonymous namespace
423*9880d681SAndroid Build Coastguard Worker
424*9880d681SAndroid Build Coastguard Worker char SeparateConstOffsetFromGEP::ID = 0;
425*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(
426*9880d681SAndroid Build Coastguard Worker SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
427*9880d681SAndroid Build Coastguard Worker "Split GEPs to a variadic base and a constant offset for better CSE", false,
428*9880d681SAndroid Build Coastguard Worker false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)429*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
430*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
431*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
432*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
433*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
434*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(
435*9880d681SAndroid Build Coastguard Worker SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
436*9880d681SAndroid Build Coastguard Worker "Split GEPs to a variadic base and a constant offset for better CSE", false,
437*9880d681SAndroid Build Coastguard Worker false)
438*9880d681SAndroid Build Coastguard Worker
439*9880d681SAndroid Build Coastguard Worker FunctionPass *
440*9880d681SAndroid Build Coastguard Worker llvm::createSeparateConstOffsetFromGEPPass(const TargetMachine *TM,
441*9880d681SAndroid Build Coastguard Worker bool LowerGEP) {
442*9880d681SAndroid Build Coastguard Worker return new SeparateConstOffsetFromGEP(TM, LowerGEP);
443*9880d681SAndroid Build Coastguard Worker }
444*9880d681SAndroid Build Coastguard Worker
CanTraceInto(bool SignExtended,bool ZeroExtended,BinaryOperator * BO,bool NonNegative)445*9880d681SAndroid Build Coastguard Worker bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
446*9880d681SAndroid Build Coastguard Worker bool ZeroExtended,
447*9880d681SAndroid Build Coastguard Worker BinaryOperator *BO,
448*9880d681SAndroid Build Coastguard Worker bool NonNegative) {
449*9880d681SAndroid Build Coastguard Worker // We only consider ADD, SUB and OR, because a non-zero constant found in
450*9880d681SAndroid Build Coastguard Worker // expressions composed of these operations can be easily hoisted as a
451*9880d681SAndroid Build Coastguard Worker // constant offset by reassociation.
452*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() != Instruction::Add &&
453*9880d681SAndroid Build Coastguard Worker BO->getOpcode() != Instruction::Sub &&
454*9880d681SAndroid Build Coastguard Worker BO->getOpcode() != Instruction::Or) {
455*9880d681SAndroid Build Coastguard Worker return false;
456*9880d681SAndroid Build Coastguard Worker }
457*9880d681SAndroid Build Coastguard Worker
458*9880d681SAndroid Build Coastguard Worker Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
459*9880d681SAndroid Build Coastguard Worker // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
460*9880d681SAndroid Build Coastguard Worker // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
461*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() == Instruction::Or &&
462*9880d681SAndroid Build Coastguard Worker !haveNoCommonBitsSet(LHS, RHS, DL, nullptr, BO, DT))
463*9880d681SAndroid Build Coastguard Worker return false;
464*9880d681SAndroid Build Coastguard Worker
465*9880d681SAndroid Build Coastguard Worker // In addition, tracing into BO requires that its surrounding s/zext (if
466*9880d681SAndroid Build Coastguard Worker // any) is distributable to both operands.
467*9880d681SAndroid Build Coastguard Worker //
468*9880d681SAndroid Build Coastguard Worker // Suppose BO = A op B.
469*9880d681SAndroid Build Coastguard Worker // SignExtended | ZeroExtended | Distributable?
470*9880d681SAndroid Build Coastguard Worker // --------------+--------------+----------------------------------
471*9880d681SAndroid Build Coastguard Worker // 0 | 0 | true because no s/zext exists
472*9880d681SAndroid Build Coastguard Worker // 0 | 1 | zext(BO) == zext(A) op zext(B)
473*9880d681SAndroid Build Coastguard Worker // 1 | 0 | sext(BO) == sext(A) op sext(B)
474*9880d681SAndroid Build Coastguard Worker // 1 | 1 | zext(sext(BO)) ==
475*9880d681SAndroid Build Coastguard Worker // | | zext(sext(A)) op zext(sext(B))
476*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
477*9880d681SAndroid Build Coastguard Worker // If a + b >= 0 and (a >= 0 or b >= 0), then
478*9880d681SAndroid Build Coastguard Worker // sext(a + b) = sext(a) + sext(b)
479*9880d681SAndroid Build Coastguard Worker // even if the addition is not marked nsw.
480*9880d681SAndroid Build Coastguard Worker //
481*9880d681SAndroid Build Coastguard Worker // Leveraging this invarient, we can trace into an sext'ed inbound GEP
482*9880d681SAndroid Build Coastguard Worker // index if the constant offset is non-negative.
483*9880d681SAndroid Build Coastguard Worker //
484*9880d681SAndroid Build Coastguard Worker // Verified in @sext_add in split-gep.ll.
485*9880d681SAndroid Build Coastguard Worker if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
486*9880d681SAndroid Build Coastguard Worker if (!ConstLHS->isNegative())
487*9880d681SAndroid Build Coastguard Worker return true;
488*9880d681SAndroid Build Coastguard Worker }
489*9880d681SAndroid Build Coastguard Worker if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
490*9880d681SAndroid Build Coastguard Worker if (!ConstRHS->isNegative())
491*9880d681SAndroid Build Coastguard Worker return true;
492*9880d681SAndroid Build Coastguard Worker }
493*9880d681SAndroid Build Coastguard Worker }
494*9880d681SAndroid Build Coastguard Worker
495*9880d681SAndroid Build Coastguard Worker // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
496*9880d681SAndroid Build Coastguard Worker // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
497*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() == Instruction::Add ||
498*9880d681SAndroid Build Coastguard Worker BO->getOpcode() == Instruction::Sub) {
499*9880d681SAndroid Build Coastguard Worker if (SignExtended && !BO->hasNoSignedWrap())
500*9880d681SAndroid Build Coastguard Worker return false;
501*9880d681SAndroid Build Coastguard Worker if (ZeroExtended && !BO->hasNoUnsignedWrap())
502*9880d681SAndroid Build Coastguard Worker return false;
503*9880d681SAndroid Build Coastguard Worker }
504*9880d681SAndroid Build Coastguard Worker
505*9880d681SAndroid Build Coastguard Worker return true;
506*9880d681SAndroid Build Coastguard Worker }
507*9880d681SAndroid Build Coastguard Worker
findInEitherOperand(BinaryOperator * BO,bool SignExtended,bool ZeroExtended)508*9880d681SAndroid Build Coastguard Worker APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
509*9880d681SAndroid Build Coastguard Worker bool SignExtended,
510*9880d681SAndroid Build Coastguard Worker bool ZeroExtended) {
511*9880d681SAndroid Build Coastguard Worker // BO being non-negative does not shed light on whether its operands are
512*9880d681SAndroid Build Coastguard Worker // non-negative. Clear the NonNegative flag here.
513*9880d681SAndroid Build Coastguard Worker APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
514*9880d681SAndroid Build Coastguard Worker /* NonNegative */ false);
515*9880d681SAndroid Build Coastguard Worker // If we found a constant offset in the left operand, stop and return that.
516*9880d681SAndroid Build Coastguard Worker // This shortcut might cause us to miss opportunities of combining the
517*9880d681SAndroid Build Coastguard Worker // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
518*9880d681SAndroid Build Coastguard Worker // However, such cases are probably already handled by -instcombine,
519*9880d681SAndroid Build Coastguard Worker // given this pass runs after the standard optimizations.
520*9880d681SAndroid Build Coastguard Worker if (ConstantOffset != 0) return ConstantOffset;
521*9880d681SAndroid Build Coastguard Worker ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
522*9880d681SAndroid Build Coastguard Worker /* NonNegative */ false);
523*9880d681SAndroid Build Coastguard Worker // If U is a sub operator, negate the constant offset found in the right
524*9880d681SAndroid Build Coastguard Worker // operand.
525*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() == Instruction::Sub)
526*9880d681SAndroid Build Coastguard Worker ConstantOffset = -ConstantOffset;
527*9880d681SAndroid Build Coastguard Worker return ConstantOffset;
528*9880d681SAndroid Build Coastguard Worker }
529*9880d681SAndroid Build Coastguard Worker
find(Value * V,bool SignExtended,bool ZeroExtended,bool NonNegative)530*9880d681SAndroid Build Coastguard Worker APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
531*9880d681SAndroid Build Coastguard Worker bool ZeroExtended, bool NonNegative) {
532*9880d681SAndroid Build Coastguard Worker // TODO(jingyue): We could trace into integer/pointer casts, such as
533*9880d681SAndroid Build Coastguard Worker // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
534*9880d681SAndroid Build Coastguard Worker // integers because it gives good enough results for our benchmarks.
535*9880d681SAndroid Build Coastguard Worker unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
536*9880d681SAndroid Build Coastguard Worker
537*9880d681SAndroid Build Coastguard Worker // We cannot do much with Values that are not a User, such as an Argument.
538*9880d681SAndroid Build Coastguard Worker User *U = dyn_cast<User>(V);
539*9880d681SAndroid Build Coastguard Worker if (U == nullptr) return APInt(BitWidth, 0);
540*9880d681SAndroid Build Coastguard Worker
541*9880d681SAndroid Build Coastguard Worker APInt ConstantOffset(BitWidth, 0);
542*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
543*9880d681SAndroid Build Coastguard Worker // Hooray, we found it!
544*9880d681SAndroid Build Coastguard Worker ConstantOffset = CI->getValue();
545*9880d681SAndroid Build Coastguard Worker } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
546*9880d681SAndroid Build Coastguard Worker // Trace into subexpressions for more hoisting opportunities.
547*9880d681SAndroid Build Coastguard Worker if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative))
548*9880d681SAndroid Build Coastguard Worker ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
549*9880d681SAndroid Build Coastguard Worker } else if (isa<SExtInst>(V)) {
550*9880d681SAndroid Build Coastguard Worker ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
551*9880d681SAndroid Build Coastguard Worker ZeroExtended, NonNegative).sext(BitWidth);
552*9880d681SAndroid Build Coastguard Worker } else if (isa<ZExtInst>(V)) {
553*9880d681SAndroid Build Coastguard Worker // As an optimization, we can clear the SignExtended flag because
554*9880d681SAndroid Build Coastguard Worker // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
555*9880d681SAndroid Build Coastguard Worker //
556*9880d681SAndroid Build Coastguard Worker // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
557*9880d681SAndroid Build Coastguard Worker ConstantOffset =
558*9880d681SAndroid Build Coastguard Worker find(U->getOperand(0), /* SignExtended */ false,
559*9880d681SAndroid Build Coastguard Worker /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
560*9880d681SAndroid Build Coastguard Worker }
561*9880d681SAndroid Build Coastguard Worker
562*9880d681SAndroid Build Coastguard Worker // If we found a non-zero constant offset, add it to the path for
563*9880d681SAndroid Build Coastguard Worker // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
564*9880d681SAndroid Build Coastguard Worker // help this optimization.
565*9880d681SAndroid Build Coastguard Worker if (ConstantOffset != 0)
566*9880d681SAndroid Build Coastguard Worker UserChain.push_back(U);
567*9880d681SAndroid Build Coastguard Worker return ConstantOffset;
568*9880d681SAndroid Build Coastguard Worker }
569*9880d681SAndroid Build Coastguard Worker
applyExts(Value * V)570*9880d681SAndroid Build Coastguard Worker Value *ConstantOffsetExtractor::applyExts(Value *V) {
571*9880d681SAndroid Build Coastguard Worker Value *Current = V;
572*9880d681SAndroid Build Coastguard Worker // ExtInsts is built in the use-def order. Therefore, we apply them to V
573*9880d681SAndroid Build Coastguard Worker // in the reversed order.
574*9880d681SAndroid Build Coastguard Worker for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
575*9880d681SAndroid Build Coastguard Worker if (Constant *C = dyn_cast<Constant>(Current)) {
576*9880d681SAndroid Build Coastguard Worker // If Current is a constant, apply s/zext using ConstantExpr::getCast.
577*9880d681SAndroid Build Coastguard Worker // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
578*9880d681SAndroid Build Coastguard Worker Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
579*9880d681SAndroid Build Coastguard Worker } else {
580*9880d681SAndroid Build Coastguard Worker Instruction *Ext = (*I)->clone();
581*9880d681SAndroid Build Coastguard Worker Ext->setOperand(0, Current);
582*9880d681SAndroid Build Coastguard Worker Ext->insertBefore(IP);
583*9880d681SAndroid Build Coastguard Worker Current = Ext;
584*9880d681SAndroid Build Coastguard Worker }
585*9880d681SAndroid Build Coastguard Worker }
586*9880d681SAndroid Build Coastguard Worker return Current;
587*9880d681SAndroid Build Coastguard Worker }
588*9880d681SAndroid Build Coastguard Worker
rebuildWithoutConstOffset()589*9880d681SAndroid Build Coastguard Worker Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
590*9880d681SAndroid Build Coastguard Worker distributeExtsAndCloneChain(UserChain.size() - 1);
591*9880d681SAndroid Build Coastguard Worker // Remove all nullptrs (used to be s/zext) from UserChain.
592*9880d681SAndroid Build Coastguard Worker unsigned NewSize = 0;
593*9880d681SAndroid Build Coastguard Worker for (User *I : UserChain) {
594*9880d681SAndroid Build Coastguard Worker if (I != nullptr) {
595*9880d681SAndroid Build Coastguard Worker UserChain[NewSize] = I;
596*9880d681SAndroid Build Coastguard Worker NewSize++;
597*9880d681SAndroid Build Coastguard Worker }
598*9880d681SAndroid Build Coastguard Worker }
599*9880d681SAndroid Build Coastguard Worker UserChain.resize(NewSize);
600*9880d681SAndroid Build Coastguard Worker return removeConstOffset(UserChain.size() - 1);
601*9880d681SAndroid Build Coastguard Worker }
602*9880d681SAndroid Build Coastguard Worker
603*9880d681SAndroid Build Coastguard Worker Value *
distributeExtsAndCloneChain(unsigned ChainIndex)604*9880d681SAndroid Build Coastguard Worker ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
605*9880d681SAndroid Build Coastguard Worker User *U = UserChain[ChainIndex];
606*9880d681SAndroid Build Coastguard Worker if (ChainIndex == 0) {
607*9880d681SAndroid Build Coastguard Worker assert(isa<ConstantInt>(U));
608*9880d681SAndroid Build Coastguard Worker // If U is a ConstantInt, applyExts will return a ConstantInt as well.
609*9880d681SAndroid Build Coastguard Worker return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
610*9880d681SAndroid Build Coastguard Worker }
611*9880d681SAndroid Build Coastguard Worker
612*9880d681SAndroid Build Coastguard Worker if (CastInst *Cast = dyn_cast<CastInst>(U)) {
613*9880d681SAndroid Build Coastguard Worker assert((isa<SExtInst>(Cast) || isa<ZExtInst>(Cast)) &&
614*9880d681SAndroid Build Coastguard Worker "We only traced into two types of CastInst: sext and zext");
615*9880d681SAndroid Build Coastguard Worker ExtInsts.push_back(Cast);
616*9880d681SAndroid Build Coastguard Worker UserChain[ChainIndex] = nullptr;
617*9880d681SAndroid Build Coastguard Worker return distributeExtsAndCloneChain(ChainIndex - 1);
618*9880d681SAndroid Build Coastguard Worker }
619*9880d681SAndroid Build Coastguard Worker
620*9880d681SAndroid Build Coastguard Worker // Function find only trace into BinaryOperator and CastInst.
621*9880d681SAndroid Build Coastguard Worker BinaryOperator *BO = cast<BinaryOperator>(U);
622*9880d681SAndroid Build Coastguard Worker // OpNo = which operand of BO is UserChain[ChainIndex - 1]
623*9880d681SAndroid Build Coastguard Worker unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
624*9880d681SAndroid Build Coastguard Worker Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
625*9880d681SAndroid Build Coastguard Worker Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
626*9880d681SAndroid Build Coastguard Worker
627*9880d681SAndroid Build Coastguard Worker BinaryOperator *NewBO = nullptr;
628*9880d681SAndroid Build Coastguard Worker if (OpNo == 0) {
629*9880d681SAndroid Build Coastguard Worker NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
630*9880d681SAndroid Build Coastguard Worker BO->getName(), IP);
631*9880d681SAndroid Build Coastguard Worker } else {
632*9880d681SAndroid Build Coastguard Worker NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
633*9880d681SAndroid Build Coastguard Worker BO->getName(), IP);
634*9880d681SAndroid Build Coastguard Worker }
635*9880d681SAndroid Build Coastguard Worker return UserChain[ChainIndex] = NewBO;
636*9880d681SAndroid Build Coastguard Worker }
637*9880d681SAndroid Build Coastguard Worker
removeConstOffset(unsigned ChainIndex)638*9880d681SAndroid Build Coastguard Worker Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
639*9880d681SAndroid Build Coastguard Worker if (ChainIndex == 0) {
640*9880d681SAndroid Build Coastguard Worker assert(isa<ConstantInt>(UserChain[ChainIndex]));
641*9880d681SAndroid Build Coastguard Worker return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
642*9880d681SAndroid Build Coastguard Worker }
643*9880d681SAndroid Build Coastguard Worker
644*9880d681SAndroid Build Coastguard Worker BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
645*9880d681SAndroid Build Coastguard Worker assert(BO->getNumUses() <= 1 &&
646*9880d681SAndroid Build Coastguard Worker "distributeExtsAndCloneChain clones each BinaryOperator in "
647*9880d681SAndroid Build Coastguard Worker "UserChain, so no one should be used more than "
648*9880d681SAndroid Build Coastguard Worker "once");
649*9880d681SAndroid Build Coastguard Worker
650*9880d681SAndroid Build Coastguard Worker unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
651*9880d681SAndroid Build Coastguard Worker assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
652*9880d681SAndroid Build Coastguard Worker Value *NextInChain = removeConstOffset(ChainIndex - 1);
653*9880d681SAndroid Build Coastguard Worker Value *TheOther = BO->getOperand(1 - OpNo);
654*9880d681SAndroid Build Coastguard Worker
655*9880d681SAndroid Build Coastguard Worker // If NextInChain is 0 and not the LHS of a sub, we can simplify the
656*9880d681SAndroid Build Coastguard Worker // sub-expression to be just TheOther.
657*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
658*9880d681SAndroid Build Coastguard Worker if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
659*9880d681SAndroid Build Coastguard Worker return TheOther;
660*9880d681SAndroid Build Coastguard Worker }
661*9880d681SAndroid Build Coastguard Worker
662*9880d681SAndroid Build Coastguard Worker BinaryOperator::BinaryOps NewOp = BO->getOpcode();
663*9880d681SAndroid Build Coastguard Worker if (BO->getOpcode() == Instruction::Or) {
664*9880d681SAndroid Build Coastguard Worker // Rebuild "or" as "add", because "or" may be invalid for the new
665*9880d681SAndroid Build Coastguard Worker // epxression.
666*9880d681SAndroid Build Coastguard Worker //
667*9880d681SAndroid Build Coastguard Worker // For instance, given
668*9880d681SAndroid Build Coastguard Worker // a | (b + 5) where a and b + 5 have no common bits,
669*9880d681SAndroid Build Coastguard Worker // we can extract 5 as the constant offset.
670*9880d681SAndroid Build Coastguard Worker //
671*9880d681SAndroid Build Coastguard Worker // However, reusing the "or" in the new index would give us
672*9880d681SAndroid Build Coastguard Worker // (a | b) + 5
673*9880d681SAndroid Build Coastguard Worker // which does not equal a | (b + 5).
674*9880d681SAndroid Build Coastguard Worker //
675*9880d681SAndroid Build Coastguard Worker // Replacing the "or" with "add" is fine, because
676*9880d681SAndroid Build Coastguard Worker // a | (b + 5) = a + (b + 5) = (a + b) + 5
677*9880d681SAndroid Build Coastguard Worker NewOp = Instruction::Add;
678*9880d681SAndroid Build Coastguard Worker }
679*9880d681SAndroid Build Coastguard Worker
680*9880d681SAndroid Build Coastguard Worker BinaryOperator *NewBO;
681*9880d681SAndroid Build Coastguard Worker if (OpNo == 0) {
682*9880d681SAndroid Build Coastguard Worker NewBO = BinaryOperator::Create(NewOp, NextInChain, TheOther, "", IP);
683*9880d681SAndroid Build Coastguard Worker } else {
684*9880d681SAndroid Build Coastguard Worker NewBO = BinaryOperator::Create(NewOp, TheOther, NextInChain, "", IP);
685*9880d681SAndroid Build Coastguard Worker }
686*9880d681SAndroid Build Coastguard Worker NewBO->takeName(BO);
687*9880d681SAndroid Build Coastguard Worker return NewBO;
688*9880d681SAndroid Build Coastguard Worker }
689*9880d681SAndroid Build Coastguard Worker
Extract(Value * Idx,GetElementPtrInst * GEP,User * & UserChainTail,const DominatorTree * DT)690*9880d681SAndroid Build Coastguard Worker Value *ConstantOffsetExtractor::Extract(Value *Idx, GetElementPtrInst *GEP,
691*9880d681SAndroid Build Coastguard Worker User *&UserChainTail,
692*9880d681SAndroid Build Coastguard Worker const DominatorTree *DT) {
693*9880d681SAndroid Build Coastguard Worker ConstantOffsetExtractor Extractor(GEP, DT);
694*9880d681SAndroid Build Coastguard Worker // Find a non-zero constant offset first.
695*9880d681SAndroid Build Coastguard Worker APInt ConstantOffset =
696*9880d681SAndroid Build Coastguard Worker Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
697*9880d681SAndroid Build Coastguard Worker GEP->isInBounds());
698*9880d681SAndroid Build Coastguard Worker if (ConstantOffset == 0) {
699*9880d681SAndroid Build Coastguard Worker UserChainTail = nullptr;
700*9880d681SAndroid Build Coastguard Worker return nullptr;
701*9880d681SAndroid Build Coastguard Worker }
702*9880d681SAndroid Build Coastguard Worker // Separates the constant offset from the GEP index.
703*9880d681SAndroid Build Coastguard Worker Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
704*9880d681SAndroid Build Coastguard Worker UserChainTail = Extractor.UserChain.back();
705*9880d681SAndroid Build Coastguard Worker return IdxWithoutConstOffset;
706*9880d681SAndroid Build Coastguard Worker }
707*9880d681SAndroid Build Coastguard Worker
Find(Value * Idx,GetElementPtrInst * GEP,const DominatorTree * DT)708*9880d681SAndroid Build Coastguard Worker int64_t ConstantOffsetExtractor::Find(Value *Idx, GetElementPtrInst *GEP,
709*9880d681SAndroid Build Coastguard Worker const DominatorTree *DT) {
710*9880d681SAndroid Build Coastguard Worker // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
711*9880d681SAndroid Build Coastguard Worker return ConstantOffsetExtractor(GEP, DT)
712*9880d681SAndroid Build Coastguard Worker .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
713*9880d681SAndroid Build Coastguard Worker GEP->isInBounds())
714*9880d681SAndroid Build Coastguard Worker .getSExtValue();
715*9880d681SAndroid Build Coastguard Worker }
716*9880d681SAndroid Build Coastguard Worker
canonicalizeArrayIndicesToPointerSize(GetElementPtrInst * GEP)717*9880d681SAndroid Build Coastguard Worker bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
718*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *GEP) {
719*9880d681SAndroid Build Coastguard Worker bool Changed = false;
720*9880d681SAndroid Build Coastguard Worker Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
721*9880d681SAndroid Build Coastguard Worker gep_type_iterator GTI = gep_type_begin(*GEP);
722*9880d681SAndroid Build Coastguard Worker for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
723*9880d681SAndroid Build Coastguard Worker I != E; ++I, ++GTI) {
724*9880d681SAndroid Build Coastguard Worker // Skip struct member indices which must be i32.
725*9880d681SAndroid Build Coastguard Worker if (isa<SequentialType>(*GTI)) {
726*9880d681SAndroid Build Coastguard Worker if ((*I)->getType() != IntPtrTy) {
727*9880d681SAndroid Build Coastguard Worker *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
728*9880d681SAndroid Build Coastguard Worker Changed = true;
729*9880d681SAndroid Build Coastguard Worker }
730*9880d681SAndroid Build Coastguard Worker }
731*9880d681SAndroid Build Coastguard Worker }
732*9880d681SAndroid Build Coastguard Worker return Changed;
733*9880d681SAndroid Build Coastguard Worker }
734*9880d681SAndroid Build Coastguard Worker
735*9880d681SAndroid Build Coastguard Worker int64_t
accumulateByteOffset(GetElementPtrInst * GEP,bool & NeedsExtraction)736*9880d681SAndroid Build Coastguard Worker SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
737*9880d681SAndroid Build Coastguard Worker bool &NeedsExtraction) {
738*9880d681SAndroid Build Coastguard Worker NeedsExtraction = false;
739*9880d681SAndroid Build Coastguard Worker int64_t AccumulativeByteOffset = 0;
740*9880d681SAndroid Build Coastguard Worker gep_type_iterator GTI = gep_type_begin(*GEP);
741*9880d681SAndroid Build Coastguard Worker for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
742*9880d681SAndroid Build Coastguard Worker if (isa<SequentialType>(*GTI)) {
743*9880d681SAndroid Build Coastguard Worker // Tries to extract a constant offset from this GEP index.
744*9880d681SAndroid Build Coastguard Worker int64_t ConstantOffset =
745*9880d681SAndroid Build Coastguard Worker ConstantOffsetExtractor::Find(GEP->getOperand(I), GEP, DT);
746*9880d681SAndroid Build Coastguard Worker if (ConstantOffset != 0) {
747*9880d681SAndroid Build Coastguard Worker NeedsExtraction = true;
748*9880d681SAndroid Build Coastguard Worker // A GEP may have multiple indices. We accumulate the extracted
749*9880d681SAndroid Build Coastguard Worker // constant offset to a byte offset, and later offset the remainder of
750*9880d681SAndroid Build Coastguard Worker // the original GEP with this byte offset.
751*9880d681SAndroid Build Coastguard Worker AccumulativeByteOffset +=
752*9880d681SAndroid Build Coastguard Worker ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());
753*9880d681SAndroid Build Coastguard Worker }
754*9880d681SAndroid Build Coastguard Worker } else if (LowerGEP) {
755*9880d681SAndroid Build Coastguard Worker StructType *StTy = cast<StructType>(*GTI);
756*9880d681SAndroid Build Coastguard Worker uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
757*9880d681SAndroid Build Coastguard Worker // Skip field 0 as the offset is always 0.
758*9880d681SAndroid Build Coastguard Worker if (Field != 0) {
759*9880d681SAndroid Build Coastguard Worker NeedsExtraction = true;
760*9880d681SAndroid Build Coastguard Worker AccumulativeByteOffset +=
761*9880d681SAndroid Build Coastguard Worker DL->getStructLayout(StTy)->getElementOffset(Field);
762*9880d681SAndroid Build Coastguard Worker }
763*9880d681SAndroid Build Coastguard Worker }
764*9880d681SAndroid Build Coastguard Worker }
765*9880d681SAndroid Build Coastguard Worker return AccumulativeByteOffset;
766*9880d681SAndroid Build Coastguard Worker }
767*9880d681SAndroid Build Coastguard Worker
lowerToSingleIndexGEPs(GetElementPtrInst * Variadic,int64_t AccumulativeByteOffset)768*9880d681SAndroid Build Coastguard Worker void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
769*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *Variadic, int64_t AccumulativeByteOffset) {
770*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(Variadic);
771*9880d681SAndroid Build Coastguard Worker Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
772*9880d681SAndroid Build Coastguard Worker
773*9880d681SAndroid Build Coastguard Worker Type *I8PtrTy =
774*9880d681SAndroid Build Coastguard Worker Builder.getInt8PtrTy(Variadic->getType()->getPointerAddressSpace());
775*9880d681SAndroid Build Coastguard Worker Value *ResultPtr = Variadic->getOperand(0);
776*9880d681SAndroid Build Coastguard Worker Loop *L = LI->getLoopFor(Variadic->getParent());
777*9880d681SAndroid Build Coastguard Worker // Check if the base is not loop invariant or used more than once.
778*9880d681SAndroid Build Coastguard Worker bool isSwapCandidate =
779*9880d681SAndroid Build Coastguard Worker L && L->isLoopInvariant(ResultPtr) &&
780*9880d681SAndroid Build Coastguard Worker !hasMoreThanOneUseInLoop(ResultPtr, L);
781*9880d681SAndroid Build Coastguard Worker Value *FirstResult = nullptr;
782*9880d681SAndroid Build Coastguard Worker
783*9880d681SAndroid Build Coastguard Worker if (ResultPtr->getType() != I8PtrTy)
784*9880d681SAndroid Build Coastguard Worker ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
785*9880d681SAndroid Build Coastguard Worker
786*9880d681SAndroid Build Coastguard Worker gep_type_iterator GTI = gep_type_begin(*Variadic);
787*9880d681SAndroid Build Coastguard Worker // Create an ugly GEP for each sequential index. We don't create GEPs for
788*9880d681SAndroid Build Coastguard Worker // structure indices, as they are accumulated in the constant offset index.
789*9880d681SAndroid Build Coastguard Worker for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
790*9880d681SAndroid Build Coastguard Worker if (isa<SequentialType>(*GTI)) {
791*9880d681SAndroid Build Coastguard Worker Value *Idx = Variadic->getOperand(I);
792*9880d681SAndroid Build Coastguard Worker // Skip zero indices.
793*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
794*9880d681SAndroid Build Coastguard Worker if (CI->isZero())
795*9880d681SAndroid Build Coastguard Worker continue;
796*9880d681SAndroid Build Coastguard Worker
797*9880d681SAndroid Build Coastguard Worker APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
798*9880d681SAndroid Build Coastguard Worker DL->getTypeAllocSize(GTI.getIndexedType()));
799*9880d681SAndroid Build Coastguard Worker // Scale the index by element size.
800*9880d681SAndroid Build Coastguard Worker if (ElementSize != 1) {
801*9880d681SAndroid Build Coastguard Worker if (ElementSize.isPowerOf2()) {
802*9880d681SAndroid Build Coastguard Worker Idx = Builder.CreateShl(
803*9880d681SAndroid Build Coastguard Worker Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
804*9880d681SAndroid Build Coastguard Worker } else {
805*9880d681SAndroid Build Coastguard Worker Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
806*9880d681SAndroid Build Coastguard Worker }
807*9880d681SAndroid Build Coastguard Worker }
808*9880d681SAndroid Build Coastguard Worker // Create an ugly GEP with a single index for each index.
809*9880d681SAndroid Build Coastguard Worker ResultPtr =
810*9880d681SAndroid Build Coastguard Worker Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Idx, "uglygep");
811*9880d681SAndroid Build Coastguard Worker if (FirstResult == nullptr)
812*9880d681SAndroid Build Coastguard Worker FirstResult = ResultPtr;
813*9880d681SAndroid Build Coastguard Worker }
814*9880d681SAndroid Build Coastguard Worker }
815*9880d681SAndroid Build Coastguard Worker
816*9880d681SAndroid Build Coastguard Worker // Create a GEP with the constant offset index.
817*9880d681SAndroid Build Coastguard Worker if (AccumulativeByteOffset != 0) {
818*9880d681SAndroid Build Coastguard Worker Value *Offset = ConstantInt::get(IntPtrTy, AccumulativeByteOffset);
819*9880d681SAndroid Build Coastguard Worker ResultPtr =
820*9880d681SAndroid Build Coastguard Worker Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Offset, "uglygep");
821*9880d681SAndroid Build Coastguard Worker } else
822*9880d681SAndroid Build Coastguard Worker isSwapCandidate = false;
823*9880d681SAndroid Build Coastguard Worker
824*9880d681SAndroid Build Coastguard Worker // If we created a GEP with constant index, and the base is loop invariant,
825*9880d681SAndroid Build Coastguard Worker // then we swap the first one with it, so LICM can move constant GEP out
826*9880d681SAndroid Build Coastguard Worker // later.
827*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *FirstGEP = dyn_cast_or_null<GetElementPtrInst>(FirstResult);
828*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *SecondGEP = dyn_cast_or_null<GetElementPtrInst>(ResultPtr);
829*9880d681SAndroid Build Coastguard Worker if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
830*9880d681SAndroid Build Coastguard Worker swapGEPOperand(FirstGEP, SecondGEP);
831*9880d681SAndroid Build Coastguard Worker
832*9880d681SAndroid Build Coastguard Worker if (ResultPtr->getType() != Variadic->getType())
833*9880d681SAndroid Build Coastguard Worker ResultPtr = Builder.CreateBitCast(ResultPtr, Variadic->getType());
834*9880d681SAndroid Build Coastguard Worker
835*9880d681SAndroid Build Coastguard Worker Variadic->replaceAllUsesWith(ResultPtr);
836*9880d681SAndroid Build Coastguard Worker Variadic->eraseFromParent();
837*9880d681SAndroid Build Coastguard Worker }
838*9880d681SAndroid Build Coastguard Worker
839*9880d681SAndroid Build Coastguard Worker void
lowerToArithmetics(GetElementPtrInst * Variadic,int64_t AccumulativeByteOffset)840*9880d681SAndroid Build Coastguard Worker SeparateConstOffsetFromGEP::lowerToArithmetics(GetElementPtrInst *Variadic,
841*9880d681SAndroid Build Coastguard Worker int64_t AccumulativeByteOffset) {
842*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(Variadic);
843*9880d681SAndroid Build Coastguard Worker Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
844*9880d681SAndroid Build Coastguard Worker
845*9880d681SAndroid Build Coastguard Worker Value *ResultPtr = Builder.CreatePtrToInt(Variadic->getOperand(0), IntPtrTy);
846*9880d681SAndroid Build Coastguard Worker gep_type_iterator GTI = gep_type_begin(*Variadic);
847*9880d681SAndroid Build Coastguard Worker // Create ADD/SHL/MUL arithmetic operations for each sequential indices. We
848*9880d681SAndroid Build Coastguard Worker // don't create arithmetics for structure indices, as they are accumulated
849*9880d681SAndroid Build Coastguard Worker // in the constant offset index.
850*9880d681SAndroid Build Coastguard Worker for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
851*9880d681SAndroid Build Coastguard Worker if (isa<SequentialType>(*GTI)) {
852*9880d681SAndroid Build Coastguard Worker Value *Idx = Variadic->getOperand(I);
853*9880d681SAndroid Build Coastguard Worker // Skip zero indices.
854*9880d681SAndroid Build Coastguard Worker if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
855*9880d681SAndroid Build Coastguard Worker if (CI->isZero())
856*9880d681SAndroid Build Coastguard Worker continue;
857*9880d681SAndroid Build Coastguard Worker
858*9880d681SAndroid Build Coastguard Worker APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
859*9880d681SAndroid Build Coastguard Worker DL->getTypeAllocSize(GTI.getIndexedType()));
860*9880d681SAndroid Build Coastguard Worker // Scale the index by element size.
861*9880d681SAndroid Build Coastguard Worker if (ElementSize != 1) {
862*9880d681SAndroid Build Coastguard Worker if (ElementSize.isPowerOf2()) {
863*9880d681SAndroid Build Coastguard Worker Idx = Builder.CreateShl(
864*9880d681SAndroid Build Coastguard Worker Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
865*9880d681SAndroid Build Coastguard Worker } else {
866*9880d681SAndroid Build Coastguard Worker Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
867*9880d681SAndroid Build Coastguard Worker }
868*9880d681SAndroid Build Coastguard Worker }
869*9880d681SAndroid Build Coastguard Worker // Create an ADD for each index.
870*9880d681SAndroid Build Coastguard Worker ResultPtr = Builder.CreateAdd(ResultPtr, Idx);
871*9880d681SAndroid Build Coastguard Worker }
872*9880d681SAndroid Build Coastguard Worker }
873*9880d681SAndroid Build Coastguard Worker
874*9880d681SAndroid Build Coastguard Worker // Create an ADD for the constant offset index.
875*9880d681SAndroid Build Coastguard Worker if (AccumulativeByteOffset != 0) {
876*9880d681SAndroid Build Coastguard Worker ResultPtr = Builder.CreateAdd(
877*9880d681SAndroid Build Coastguard Worker ResultPtr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset));
878*9880d681SAndroid Build Coastguard Worker }
879*9880d681SAndroid Build Coastguard Worker
880*9880d681SAndroid Build Coastguard Worker ResultPtr = Builder.CreateIntToPtr(ResultPtr, Variadic->getType());
881*9880d681SAndroid Build Coastguard Worker Variadic->replaceAllUsesWith(ResultPtr);
882*9880d681SAndroid Build Coastguard Worker Variadic->eraseFromParent();
883*9880d681SAndroid Build Coastguard Worker }
884*9880d681SAndroid Build Coastguard Worker
splitGEP(GetElementPtrInst * GEP)885*9880d681SAndroid Build Coastguard Worker bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
886*9880d681SAndroid Build Coastguard Worker // Skip vector GEPs.
887*9880d681SAndroid Build Coastguard Worker if (GEP->getType()->isVectorTy())
888*9880d681SAndroid Build Coastguard Worker return false;
889*9880d681SAndroid Build Coastguard Worker
890*9880d681SAndroid Build Coastguard Worker // The backend can already nicely handle the case where all indices are
891*9880d681SAndroid Build Coastguard Worker // constant.
892*9880d681SAndroid Build Coastguard Worker if (GEP->hasAllConstantIndices())
893*9880d681SAndroid Build Coastguard Worker return false;
894*9880d681SAndroid Build Coastguard Worker
895*9880d681SAndroid Build Coastguard Worker bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
896*9880d681SAndroid Build Coastguard Worker
897*9880d681SAndroid Build Coastguard Worker bool NeedsExtraction;
898*9880d681SAndroid Build Coastguard Worker int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
899*9880d681SAndroid Build Coastguard Worker
900*9880d681SAndroid Build Coastguard Worker if (!NeedsExtraction)
901*9880d681SAndroid Build Coastguard Worker return Changed;
902*9880d681SAndroid Build Coastguard Worker // If LowerGEP is disabled, before really splitting the GEP, check whether the
903*9880d681SAndroid Build Coastguard Worker // backend supports the addressing mode we are about to produce. If no, this
904*9880d681SAndroid Build Coastguard Worker // splitting probably won't be beneficial.
905*9880d681SAndroid Build Coastguard Worker // If LowerGEP is enabled, even the extracted constant offset can not match
906*9880d681SAndroid Build Coastguard Worker // the addressing mode, we can still do optimizations to other lowered parts
907*9880d681SAndroid Build Coastguard Worker // of variable indices. Therefore, we don't check for addressing modes in that
908*9880d681SAndroid Build Coastguard Worker // case.
909*9880d681SAndroid Build Coastguard Worker if (!LowerGEP) {
910*9880d681SAndroid Build Coastguard Worker TargetTransformInfo &TTI =
911*9880d681SAndroid Build Coastguard Worker getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
912*9880d681SAndroid Build Coastguard Worker *GEP->getParent()->getParent());
913*9880d681SAndroid Build Coastguard Worker unsigned AddrSpace = GEP->getPointerAddressSpace();
914*9880d681SAndroid Build Coastguard Worker if (!TTI.isLegalAddressingMode(GEP->getResultElementType(),
915*9880d681SAndroid Build Coastguard Worker /*BaseGV=*/nullptr, AccumulativeByteOffset,
916*9880d681SAndroid Build Coastguard Worker /*HasBaseReg=*/true, /*Scale=*/0,
917*9880d681SAndroid Build Coastguard Worker AddrSpace)) {
918*9880d681SAndroid Build Coastguard Worker return Changed;
919*9880d681SAndroid Build Coastguard Worker }
920*9880d681SAndroid Build Coastguard Worker }
921*9880d681SAndroid Build Coastguard Worker
922*9880d681SAndroid Build Coastguard Worker // Remove the constant offset in each sequential index. The resultant GEP
923*9880d681SAndroid Build Coastguard Worker // computes the variadic base.
924*9880d681SAndroid Build Coastguard Worker // Notice that we don't remove struct field indices here. If LowerGEP is
925*9880d681SAndroid Build Coastguard Worker // disabled, a structure index is not accumulated and we still use the old
926*9880d681SAndroid Build Coastguard Worker // one. If LowerGEP is enabled, a structure index is accumulated in the
927*9880d681SAndroid Build Coastguard Worker // constant offset. LowerToSingleIndexGEPs or lowerToArithmetics will later
928*9880d681SAndroid Build Coastguard Worker // handle the constant offset and won't need a new structure index.
929*9880d681SAndroid Build Coastguard Worker gep_type_iterator GTI = gep_type_begin(*GEP);
930*9880d681SAndroid Build Coastguard Worker for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
931*9880d681SAndroid Build Coastguard Worker if (isa<SequentialType>(*GTI)) {
932*9880d681SAndroid Build Coastguard Worker // Splits this GEP index into a variadic part and a constant offset, and
933*9880d681SAndroid Build Coastguard Worker // uses the variadic part as the new index.
934*9880d681SAndroid Build Coastguard Worker Value *OldIdx = GEP->getOperand(I);
935*9880d681SAndroid Build Coastguard Worker User *UserChainTail;
936*9880d681SAndroid Build Coastguard Worker Value *NewIdx =
937*9880d681SAndroid Build Coastguard Worker ConstantOffsetExtractor::Extract(OldIdx, GEP, UserChainTail, DT);
938*9880d681SAndroid Build Coastguard Worker if (NewIdx != nullptr) {
939*9880d681SAndroid Build Coastguard Worker // Switches to the index with the constant offset removed.
940*9880d681SAndroid Build Coastguard Worker GEP->setOperand(I, NewIdx);
941*9880d681SAndroid Build Coastguard Worker // After switching to the new index, we can garbage-collect UserChain
942*9880d681SAndroid Build Coastguard Worker // and the old index if they are not used.
943*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(UserChainTail);
944*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(OldIdx);
945*9880d681SAndroid Build Coastguard Worker }
946*9880d681SAndroid Build Coastguard Worker }
947*9880d681SAndroid Build Coastguard Worker }
948*9880d681SAndroid Build Coastguard Worker
949*9880d681SAndroid Build Coastguard Worker // Clear the inbounds attribute because the new index may be off-bound.
950*9880d681SAndroid Build Coastguard Worker // e.g.,
951*9880d681SAndroid Build Coastguard Worker //
952*9880d681SAndroid Build Coastguard Worker // b = add i64 a, 5
953*9880d681SAndroid Build Coastguard Worker // addr = gep inbounds float, float* p, i64 b
954*9880d681SAndroid Build Coastguard Worker //
955*9880d681SAndroid Build Coastguard Worker // is transformed to:
956*9880d681SAndroid Build Coastguard Worker //
957*9880d681SAndroid Build Coastguard Worker // addr2 = gep float, float* p, i64 a ; inbounds removed
958*9880d681SAndroid Build Coastguard Worker // addr = gep inbounds float, float* addr2, i64 5
959*9880d681SAndroid Build Coastguard Worker //
960*9880d681SAndroid Build Coastguard Worker // If a is -4, although the old index b is in bounds, the new index a is
961*9880d681SAndroid Build Coastguard Worker // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
962*9880d681SAndroid Build Coastguard Worker // inbounds keyword is not present, the offsets are added to the base
963*9880d681SAndroid Build Coastguard Worker // address with silently-wrapping two's complement arithmetic".
964*9880d681SAndroid Build Coastguard Worker // Therefore, the final code will be a semantically equivalent.
965*9880d681SAndroid Build Coastguard Worker //
966*9880d681SAndroid Build Coastguard Worker // TODO(jingyue): do some range analysis to keep as many inbounds as
967*9880d681SAndroid Build Coastguard Worker // possible. GEPs with inbounds are more friendly to alias analysis.
968*9880d681SAndroid Build Coastguard Worker bool GEPWasInBounds = GEP->isInBounds();
969*9880d681SAndroid Build Coastguard Worker GEP->setIsInBounds(false);
970*9880d681SAndroid Build Coastguard Worker
971*9880d681SAndroid Build Coastguard Worker // Lowers a GEP to either GEPs with a single index or arithmetic operations.
972*9880d681SAndroid Build Coastguard Worker if (LowerGEP) {
973*9880d681SAndroid Build Coastguard Worker // As currently BasicAA does not analyze ptrtoint/inttoptr, do not lower to
974*9880d681SAndroid Build Coastguard Worker // arithmetic operations if the target uses alias analysis in codegen.
975*9880d681SAndroid Build Coastguard Worker if (TM && TM->getSubtargetImpl(*GEP->getParent()->getParent())->useAA())
976*9880d681SAndroid Build Coastguard Worker lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
977*9880d681SAndroid Build Coastguard Worker else
978*9880d681SAndroid Build Coastguard Worker lowerToArithmetics(GEP, AccumulativeByteOffset);
979*9880d681SAndroid Build Coastguard Worker return true;
980*9880d681SAndroid Build Coastguard Worker }
981*9880d681SAndroid Build Coastguard Worker
982*9880d681SAndroid Build Coastguard Worker // No need to create another GEP if the accumulative byte offset is 0.
983*9880d681SAndroid Build Coastguard Worker if (AccumulativeByteOffset == 0)
984*9880d681SAndroid Build Coastguard Worker return true;
985*9880d681SAndroid Build Coastguard Worker
986*9880d681SAndroid Build Coastguard Worker // Offsets the base with the accumulative byte offset.
987*9880d681SAndroid Build Coastguard Worker //
988*9880d681SAndroid Build Coastguard Worker // %gep ; the base
989*9880d681SAndroid Build Coastguard Worker // ... %gep ...
990*9880d681SAndroid Build Coastguard Worker //
991*9880d681SAndroid Build Coastguard Worker // => add the offset
992*9880d681SAndroid Build Coastguard Worker //
993*9880d681SAndroid Build Coastguard Worker // %gep2 ; clone of %gep
994*9880d681SAndroid Build Coastguard Worker // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
995*9880d681SAndroid Build Coastguard Worker // %gep ; will be removed
996*9880d681SAndroid Build Coastguard Worker // ... %gep ...
997*9880d681SAndroid Build Coastguard Worker //
998*9880d681SAndroid Build Coastguard Worker // => replace all uses of %gep with %new.gep and remove %gep
999*9880d681SAndroid Build Coastguard Worker //
1000*9880d681SAndroid Build Coastguard Worker // %gep2 ; clone of %gep
1001*9880d681SAndroid Build Coastguard Worker // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
1002*9880d681SAndroid Build Coastguard Worker // ... %new.gep ...
1003*9880d681SAndroid Build Coastguard Worker //
1004*9880d681SAndroid Build Coastguard Worker // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
1005*9880d681SAndroid Build Coastguard Worker // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
1006*9880d681SAndroid Build Coastguard Worker // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
1007*9880d681SAndroid Build Coastguard Worker // type of %gep.
1008*9880d681SAndroid Build Coastguard Worker //
1009*9880d681SAndroid Build Coastguard Worker // %gep2 ; clone of %gep
1010*9880d681SAndroid Build Coastguard Worker // %0 = bitcast %gep2 to i8*
1011*9880d681SAndroid Build Coastguard Worker // %uglygep = gep %0, <offset>
1012*9880d681SAndroid Build Coastguard Worker // %new.gep = bitcast %uglygep to <type of %gep>
1013*9880d681SAndroid Build Coastguard Worker // ... %new.gep ...
1014*9880d681SAndroid Build Coastguard Worker Instruction *NewGEP = GEP->clone();
1015*9880d681SAndroid Build Coastguard Worker NewGEP->insertBefore(GEP);
1016*9880d681SAndroid Build Coastguard Worker
1017*9880d681SAndroid Build Coastguard Worker // Per ANSI C standard, signed / unsigned = unsigned and signed % unsigned =
1018*9880d681SAndroid Build Coastguard Worker // unsigned.. Therefore, we cast ElementTypeSizeOfGEP to signed because it is
1019*9880d681SAndroid Build Coastguard Worker // used with unsigned integers later.
1020*9880d681SAndroid Build Coastguard Worker int64_t ElementTypeSizeOfGEP = static_cast<int64_t>(
1021*9880d681SAndroid Build Coastguard Worker DL->getTypeAllocSize(GEP->getResultElementType()));
1022*9880d681SAndroid Build Coastguard Worker Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
1023*9880d681SAndroid Build Coastguard Worker if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
1024*9880d681SAndroid Build Coastguard Worker // Very likely. As long as %gep is natually aligned, the byte offset we
1025*9880d681SAndroid Build Coastguard Worker // extracted should be a multiple of sizeof(*%gep).
1026*9880d681SAndroid Build Coastguard Worker int64_t Index = AccumulativeByteOffset / ElementTypeSizeOfGEP;
1027*9880d681SAndroid Build Coastguard Worker NewGEP = GetElementPtrInst::Create(GEP->getResultElementType(), NewGEP,
1028*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntPtrTy, Index, true),
1029*9880d681SAndroid Build Coastguard Worker GEP->getName(), GEP);
1030*9880d681SAndroid Build Coastguard Worker // Inherit the inbounds attribute of the original GEP.
1031*9880d681SAndroid Build Coastguard Worker cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
1032*9880d681SAndroid Build Coastguard Worker } else {
1033*9880d681SAndroid Build Coastguard Worker // Unlikely but possible. For example,
1034*9880d681SAndroid Build Coastguard Worker // #pragma pack(1)
1035*9880d681SAndroid Build Coastguard Worker // struct S {
1036*9880d681SAndroid Build Coastguard Worker // int a[3];
1037*9880d681SAndroid Build Coastguard Worker // int64 b[8];
1038*9880d681SAndroid Build Coastguard Worker // };
1039*9880d681SAndroid Build Coastguard Worker // #pragma pack()
1040*9880d681SAndroid Build Coastguard Worker //
1041*9880d681SAndroid Build Coastguard Worker // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
1042*9880d681SAndroid Build Coastguard Worker // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
1043*9880d681SAndroid Build Coastguard Worker // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
1044*9880d681SAndroid Build Coastguard Worker // sizeof(int64).
1045*9880d681SAndroid Build Coastguard Worker //
1046*9880d681SAndroid Build Coastguard Worker // Emit an uglygep in this case.
1047*9880d681SAndroid Build Coastguard Worker Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
1048*9880d681SAndroid Build Coastguard Worker GEP->getPointerAddressSpace());
1049*9880d681SAndroid Build Coastguard Worker NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
1050*9880d681SAndroid Build Coastguard Worker NewGEP = GetElementPtrInst::Create(
1051*9880d681SAndroid Build Coastguard Worker Type::getInt8Ty(GEP->getContext()), NewGEP,
1052*9880d681SAndroid Build Coastguard Worker ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true), "uglygep",
1053*9880d681SAndroid Build Coastguard Worker GEP);
1054*9880d681SAndroid Build Coastguard Worker // Inherit the inbounds attribute of the original GEP.
1055*9880d681SAndroid Build Coastguard Worker cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
1056*9880d681SAndroid Build Coastguard Worker if (GEP->getType() != I8PtrTy)
1057*9880d681SAndroid Build Coastguard Worker NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
1058*9880d681SAndroid Build Coastguard Worker }
1059*9880d681SAndroid Build Coastguard Worker
1060*9880d681SAndroid Build Coastguard Worker GEP->replaceAllUsesWith(NewGEP);
1061*9880d681SAndroid Build Coastguard Worker GEP->eraseFromParent();
1062*9880d681SAndroid Build Coastguard Worker
1063*9880d681SAndroid Build Coastguard Worker return true;
1064*9880d681SAndroid Build Coastguard Worker }
1065*9880d681SAndroid Build Coastguard Worker
runOnFunction(Function & F)1066*9880d681SAndroid Build Coastguard Worker bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
1067*9880d681SAndroid Build Coastguard Worker if (skipFunction(F))
1068*9880d681SAndroid Build Coastguard Worker return false;
1069*9880d681SAndroid Build Coastguard Worker
1070*9880d681SAndroid Build Coastguard Worker if (DisableSeparateConstOffsetFromGEP)
1071*9880d681SAndroid Build Coastguard Worker return false;
1072*9880d681SAndroid Build Coastguard Worker
1073*9880d681SAndroid Build Coastguard Worker DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1074*9880d681SAndroid Build Coastguard Worker SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1075*9880d681SAndroid Build Coastguard Worker LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1076*9880d681SAndroid Build Coastguard Worker TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1077*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1078*9880d681SAndroid Build Coastguard Worker for (BasicBlock &B : F) {
1079*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = B.begin(), IE = B.end(); I != IE;)
1080*9880d681SAndroid Build Coastguard Worker if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++))
1081*9880d681SAndroid Build Coastguard Worker Changed |= splitGEP(GEP);
1082*9880d681SAndroid Build Coastguard Worker // No need to split GEP ConstantExprs because all its indices are constant
1083*9880d681SAndroid Build Coastguard Worker // already.
1084*9880d681SAndroid Build Coastguard Worker }
1085*9880d681SAndroid Build Coastguard Worker
1086*9880d681SAndroid Build Coastguard Worker Changed |= reuniteExts(F);
1087*9880d681SAndroid Build Coastguard Worker
1088*9880d681SAndroid Build Coastguard Worker if (VerifyNoDeadCode)
1089*9880d681SAndroid Build Coastguard Worker verifyNoDeadCode(F);
1090*9880d681SAndroid Build Coastguard Worker
1091*9880d681SAndroid Build Coastguard Worker return Changed;
1092*9880d681SAndroid Build Coastguard Worker }
1093*9880d681SAndroid Build Coastguard Worker
findClosestMatchingDominator(const SCEV * Key,Instruction * Dominatee)1094*9880d681SAndroid Build Coastguard Worker Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
1095*9880d681SAndroid Build Coastguard Worker const SCEV *Key, Instruction *Dominatee) {
1096*9880d681SAndroid Build Coastguard Worker auto Pos = DominatingExprs.find(Key);
1097*9880d681SAndroid Build Coastguard Worker if (Pos == DominatingExprs.end())
1098*9880d681SAndroid Build Coastguard Worker return nullptr;
1099*9880d681SAndroid Build Coastguard Worker
1100*9880d681SAndroid Build Coastguard Worker auto &Candidates = Pos->second;
1101*9880d681SAndroid Build Coastguard Worker // Because we process the basic blocks in pre-order of the dominator tree, a
1102*9880d681SAndroid Build Coastguard Worker // candidate that doesn't dominate the current instruction won't dominate any
1103*9880d681SAndroid Build Coastguard Worker // future instruction either. Therefore, we pop it out of the stack. This
1104*9880d681SAndroid Build Coastguard Worker // optimization makes the algorithm O(n).
1105*9880d681SAndroid Build Coastguard Worker while (!Candidates.empty()) {
1106*9880d681SAndroid Build Coastguard Worker Instruction *Candidate = Candidates.back();
1107*9880d681SAndroid Build Coastguard Worker if (DT->dominates(Candidate, Dominatee))
1108*9880d681SAndroid Build Coastguard Worker return Candidate;
1109*9880d681SAndroid Build Coastguard Worker Candidates.pop_back();
1110*9880d681SAndroid Build Coastguard Worker }
1111*9880d681SAndroid Build Coastguard Worker return nullptr;
1112*9880d681SAndroid Build Coastguard Worker }
1113*9880d681SAndroid Build Coastguard Worker
reuniteExts(Instruction * I)1114*9880d681SAndroid Build Coastguard Worker bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *I) {
1115*9880d681SAndroid Build Coastguard Worker if (!SE->isSCEVable(I->getType()))
1116*9880d681SAndroid Build Coastguard Worker return false;
1117*9880d681SAndroid Build Coastguard Worker
1118*9880d681SAndroid Build Coastguard Worker // Dom: LHS+RHS
1119*9880d681SAndroid Build Coastguard Worker // I: sext(LHS)+sext(RHS)
1120*9880d681SAndroid Build Coastguard Worker // If Dom can't sign overflow and Dom dominates I, optimize I to sext(Dom).
1121*9880d681SAndroid Build Coastguard Worker // TODO: handle zext
1122*9880d681SAndroid Build Coastguard Worker Value *LHS = nullptr, *RHS = nullptr;
1123*9880d681SAndroid Build Coastguard Worker if (match(I, m_Add(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS)))) ||
1124*9880d681SAndroid Build Coastguard Worker match(I, m_Sub(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1125*9880d681SAndroid Build Coastguard Worker if (LHS->getType() == RHS->getType()) {
1126*9880d681SAndroid Build Coastguard Worker const SCEV *Key =
1127*9880d681SAndroid Build Coastguard Worker SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1128*9880d681SAndroid Build Coastguard Worker if (auto *Dom = findClosestMatchingDominator(Key, I)) {
1129*9880d681SAndroid Build Coastguard Worker Instruction *NewSExt = new SExtInst(Dom, I->getType(), "", I);
1130*9880d681SAndroid Build Coastguard Worker NewSExt->takeName(I);
1131*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(NewSExt);
1132*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(I);
1133*9880d681SAndroid Build Coastguard Worker return true;
1134*9880d681SAndroid Build Coastguard Worker }
1135*9880d681SAndroid Build Coastguard Worker }
1136*9880d681SAndroid Build Coastguard Worker }
1137*9880d681SAndroid Build Coastguard Worker
1138*9880d681SAndroid Build Coastguard Worker // Add I to DominatingExprs if it's an add/sub that can't sign overflow.
1139*9880d681SAndroid Build Coastguard Worker if (match(I, m_NSWAdd(m_Value(LHS), m_Value(RHS))) ||
1140*9880d681SAndroid Build Coastguard Worker match(I, m_NSWSub(m_Value(LHS), m_Value(RHS)))) {
1141*9880d681SAndroid Build Coastguard Worker if (isKnownNotFullPoison(I)) {
1142*9880d681SAndroid Build Coastguard Worker const SCEV *Key =
1143*9880d681SAndroid Build Coastguard Worker SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1144*9880d681SAndroid Build Coastguard Worker DominatingExprs[Key].push_back(I);
1145*9880d681SAndroid Build Coastguard Worker }
1146*9880d681SAndroid Build Coastguard Worker }
1147*9880d681SAndroid Build Coastguard Worker return false;
1148*9880d681SAndroid Build Coastguard Worker }
1149*9880d681SAndroid Build Coastguard Worker
reuniteExts(Function & F)1150*9880d681SAndroid Build Coastguard Worker bool SeparateConstOffsetFromGEP::reuniteExts(Function &F) {
1151*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1152*9880d681SAndroid Build Coastguard Worker DominatingExprs.clear();
1153*9880d681SAndroid Build Coastguard Worker for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
1154*9880d681SAndroid Build Coastguard Worker Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
1155*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = Node->getBlock();
1156*9880d681SAndroid Build Coastguard Worker for (auto I = BB->begin(); I != BB->end(); ) {
1157*9880d681SAndroid Build Coastguard Worker Instruction *Cur = &*I++;
1158*9880d681SAndroid Build Coastguard Worker Changed |= reuniteExts(Cur);
1159*9880d681SAndroid Build Coastguard Worker }
1160*9880d681SAndroid Build Coastguard Worker }
1161*9880d681SAndroid Build Coastguard Worker return Changed;
1162*9880d681SAndroid Build Coastguard Worker }
1163*9880d681SAndroid Build Coastguard Worker
verifyNoDeadCode(Function & F)1164*9880d681SAndroid Build Coastguard Worker void SeparateConstOffsetFromGEP::verifyNoDeadCode(Function &F) {
1165*9880d681SAndroid Build Coastguard Worker for (BasicBlock &B : F) {
1166*9880d681SAndroid Build Coastguard Worker for (Instruction &I : B) {
1167*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(&I)) {
1168*9880d681SAndroid Build Coastguard Worker std::string ErrMessage;
1169*9880d681SAndroid Build Coastguard Worker raw_string_ostream RSO(ErrMessage);
1170*9880d681SAndroid Build Coastguard Worker RSO << "Dead instruction detected!\n" << I << "\n";
1171*9880d681SAndroid Build Coastguard Worker llvm_unreachable(RSO.str().c_str());
1172*9880d681SAndroid Build Coastguard Worker }
1173*9880d681SAndroid Build Coastguard Worker }
1174*9880d681SAndroid Build Coastguard Worker }
1175*9880d681SAndroid Build Coastguard Worker }
1176*9880d681SAndroid Build Coastguard Worker
isLegalToSwapOperand(GetElementPtrInst * FirstGEP,GetElementPtrInst * SecondGEP,Loop * CurLoop)1177*9880d681SAndroid Build Coastguard Worker bool SeparateConstOffsetFromGEP::isLegalToSwapOperand(
1178*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *FirstGEP, GetElementPtrInst *SecondGEP, Loop *CurLoop) {
1179*9880d681SAndroid Build Coastguard Worker if (!FirstGEP || !FirstGEP->hasOneUse())
1180*9880d681SAndroid Build Coastguard Worker return false;
1181*9880d681SAndroid Build Coastguard Worker
1182*9880d681SAndroid Build Coastguard Worker if (!SecondGEP || FirstGEP->getParent() != SecondGEP->getParent())
1183*9880d681SAndroid Build Coastguard Worker return false;
1184*9880d681SAndroid Build Coastguard Worker
1185*9880d681SAndroid Build Coastguard Worker if (FirstGEP == SecondGEP)
1186*9880d681SAndroid Build Coastguard Worker return false;
1187*9880d681SAndroid Build Coastguard Worker
1188*9880d681SAndroid Build Coastguard Worker unsigned FirstNum = FirstGEP->getNumOperands();
1189*9880d681SAndroid Build Coastguard Worker unsigned SecondNum = SecondGEP->getNumOperands();
1190*9880d681SAndroid Build Coastguard Worker // Give up if the number of operands are not 2.
1191*9880d681SAndroid Build Coastguard Worker if (FirstNum != SecondNum || FirstNum != 2)
1192*9880d681SAndroid Build Coastguard Worker return false;
1193*9880d681SAndroid Build Coastguard Worker
1194*9880d681SAndroid Build Coastguard Worker Value *FirstBase = FirstGEP->getOperand(0);
1195*9880d681SAndroid Build Coastguard Worker Value *SecondBase = SecondGEP->getOperand(0);
1196*9880d681SAndroid Build Coastguard Worker Value *FirstOffset = FirstGEP->getOperand(1);
1197*9880d681SAndroid Build Coastguard Worker // Give up if the index of the first GEP is loop invariant.
1198*9880d681SAndroid Build Coastguard Worker if (CurLoop->isLoopInvariant(FirstOffset))
1199*9880d681SAndroid Build Coastguard Worker return false;
1200*9880d681SAndroid Build Coastguard Worker
1201*9880d681SAndroid Build Coastguard Worker // Give up if base doesn't have same type.
1202*9880d681SAndroid Build Coastguard Worker if (FirstBase->getType() != SecondBase->getType())
1203*9880d681SAndroid Build Coastguard Worker return false;
1204*9880d681SAndroid Build Coastguard Worker
1205*9880d681SAndroid Build Coastguard Worker Instruction *FirstOffsetDef = dyn_cast<Instruction>(FirstOffset);
1206*9880d681SAndroid Build Coastguard Worker
1207*9880d681SAndroid Build Coastguard Worker // Check if the second operand of first GEP has constant coefficient.
1208*9880d681SAndroid Build Coastguard Worker // For an example, for the following code, we won't gain anything by
1209*9880d681SAndroid Build Coastguard Worker // hoisting the second GEP out because the second GEP can be folded away.
1210*9880d681SAndroid Build Coastguard Worker // %scevgep.sum.ur159 = add i64 %idxprom48.ur, 256
1211*9880d681SAndroid Build Coastguard Worker // %67 = shl i64 %scevgep.sum.ur159, 2
1212*9880d681SAndroid Build Coastguard Worker // %uglygep160 = getelementptr i8* %65, i64 %67
1213*9880d681SAndroid Build Coastguard Worker // %uglygep161 = getelementptr i8* %uglygep160, i64 -1024
1214*9880d681SAndroid Build Coastguard Worker
1215*9880d681SAndroid Build Coastguard Worker // Skip constant shift instruction which may be generated by Splitting GEPs.
1216*9880d681SAndroid Build Coastguard Worker if (FirstOffsetDef && FirstOffsetDef->isShift() &&
1217*9880d681SAndroid Build Coastguard Worker isa<ConstantInt>(FirstOffsetDef->getOperand(1)))
1218*9880d681SAndroid Build Coastguard Worker FirstOffsetDef = dyn_cast<Instruction>(FirstOffsetDef->getOperand(0));
1219*9880d681SAndroid Build Coastguard Worker
1220*9880d681SAndroid Build Coastguard Worker // Give up if FirstOffsetDef is an Add or Sub with constant.
1221*9880d681SAndroid Build Coastguard Worker // Because it may not profitable at all due to constant folding.
1222*9880d681SAndroid Build Coastguard Worker if (FirstOffsetDef)
1223*9880d681SAndroid Build Coastguard Worker if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FirstOffsetDef)) {
1224*9880d681SAndroid Build Coastguard Worker unsigned opc = BO->getOpcode();
1225*9880d681SAndroid Build Coastguard Worker if ((opc == Instruction::Add || opc == Instruction::Sub) &&
1226*9880d681SAndroid Build Coastguard Worker (isa<ConstantInt>(BO->getOperand(0)) ||
1227*9880d681SAndroid Build Coastguard Worker isa<ConstantInt>(BO->getOperand(1))))
1228*9880d681SAndroid Build Coastguard Worker return false;
1229*9880d681SAndroid Build Coastguard Worker }
1230*9880d681SAndroid Build Coastguard Worker return true;
1231*9880d681SAndroid Build Coastguard Worker }
1232*9880d681SAndroid Build Coastguard Worker
hasMoreThanOneUseInLoop(Value * V,Loop * L)1233*9880d681SAndroid Build Coastguard Worker bool SeparateConstOffsetFromGEP::hasMoreThanOneUseInLoop(Value *V, Loop *L) {
1234*9880d681SAndroid Build Coastguard Worker int UsesInLoop = 0;
1235*9880d681SAndroid Build Coastguard Worker for (User *U : V->users()) {
1236*9880d681SAndroid Build Coastguard Worker if (Instruction *User = dyn_cast<Instruction>(U))
1237*9880d681SAndroid Build Coastguard Worker if (L->contains(User))
1238*9880d681SAndroid Build Coastguard Worker if (++UsesInLoop > 1)
1239*9880d681SAndroid Build Coastguard Worker return true;
1240*9880d681SAndroid Build Coastguard Worker }
1241*9880d681SAndroid Build Coastguard Worker return false;
1242*9880d681SAndroid Build Coastguard Worker }
1243*9880d681SAndroid Build Coastguard Worker
swapGEPOperand(GetElementPtrInst * First,GetElementPtrInst * Second)1244*9880d681SAndroid Build Coastguard Worker void SeparateConstOffsetFromGEP::swapGEPOperand(GetElementPtrInst *First,
1245*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *Second) {
1246*9880d681SAndroid Build Coastguard Worker Value *Offset1 = First->getOperand(1);
1247*9880d681SAndroid Build Coastguard Worker Value *Offset2 = Second->getOperand(1);
1248*9880d681SAndroid Build Coastguard Worker First->setOperand(1, Offset2);
1249*9880d681SAndroid Build Coastguard Worker Second->setOperand(1, Offset1);
1250*9880d681SAndroid Build Coastguard Worker
1251*9880d681SAndroid Build Coastguard Worker // We changed p+o+c to p+c+o, p+c may not be inbound anymore.
1252*9880d681SAndroid Build Coastguard Worker const DataLayout &DAL = First->getModule()->getDataLayout();
1253*9880d681SAndroid Build Coastguard Worker APInt Offset(DAL.getPointerSizeInBits(
1254*9880d681SAndroid Build Coastguard Worker cast<PointerType>(First->getType())->getAddressSpace()),
1255*9880d681SAndroid Build Coastguard Worker 0);
1256*9880d681SAndroid Build Coastguard Worker Value *NewBase =
1257*9880d681SAndroid Build Coastguard Worker First->stripAndAccumulateInBoundsConstantOffsets(DAL, Offset);
1258*9880d681SAndroid Build Coastguard Worker uint64_t ObjectSize;
1259*9880d681SAndroid Build Coastguard Worker if (!getObjectSize(NewBase, ObjectSize, DAL, TLI) ||
1260*9880d681SAndroid Build Coastguard Worker Offset.ugt(ObjectSize)) {
1261*9880d681SAndroid Build Coastguard Worker First->setIsInBounds(false);
1262*9880d681SAndroid Build Coastguard Worker Second->setIsInBounds(false);
1263*9880d681SAndroid Build Coastguard Worker } else
1264*9880d681SAndroid Build Coastguard Worker First->setIsInBounds(true);
1265*9880d681SAndroid Build Coastguard Worker }
1266