blob: 69690b358f5c20bb0a47f9c85911a31f1baa5b1e [file] [log] [blame]
Eli Benderskya108a652014-05-01 18:38:36 +00001//===-- SeparateConstOffsetFromGEP.cpp - ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Loop unrolling may create many similar GEPs for array accesses.
11// e.g., a 2-level loop
12//
13// float a[32][32]; // global variable
14//
15// for (int i = 0; i < 2; ++i) {
16// for (int j = 0; j < 2; ++j) {
17// ...
18// ... = a[x + i][y + j];
19// ...
20// }
21// }
22//
23// will probably be unrolled to:
24//
25// gep %a, 0, %x, %y; load
26// gep %a, 0, %x, %y + 1; load
27// gep %a, 0, %x + 1, %y; load
28// gep %a, 0, %x + 1, %y + 1; load
29//
30// LLVM's GVN does not use partial redundancy elimination yet, and is thus
31// unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs
32// significant slowdown in targets with limited addressing modes. For instance,
33// because the PTX target does not support the reg+reg addressing mode, the
34// NVPTX backend emits PTX code that literally computes the pointer address of
35// each GEP, wasting tons of registers. It emits the following PTX for the
36// first load and similar PTX for other loads.
37//
38// mov.u32 %r1, %x;
39// mov.u32 %r2, %y;
40// mul.wide.u32 %rl2, %r1, 128;
41// mov.u64 %rl3, a;
42// add.s64 %rl4, %rl3, %rl2;
43// mul.wide.u32 %rl5, %r2, 4;
44// add.s64 %rl6, %rl4, %rl5;
45// ld.global.f32 %f1, [%rl6];
46//
47// To reduce the register pressure, the optimization implemented in this file
48// merges the common part of a group of GEPs, so we can compute each pointer
49// address by adding a simple offset to the common part, saving many registers.
50//
51// It works by splitting each GEP into a variadic base and a constant offset.
52// The variadic base can be computed once and reused by multiple GEPs, and the
53// constant offsets can be nicely folded into the reg+immediate addressing mode
54// (supported by most targets) without using any extra register.
55//
56// For instance, we transform the four GEPs and four loads in the above example
57// into:
58//
59// base = gep a, 0, x, y
60// load base
61// laod base + 1 * sizeof(float)
62// load base + 32 * sizeof(float)
63// load base + 33 * sizeof(float)
64//
65// Given the transformed IR, a backend that supports the reg+immediate
66// addressing mode can easily fold the pointer arithmetics into the loads. For
67// example, the NVPTX backend can easily fold the pointer arithmetics into the
68// ld.global.f32 instructions, and the resultant PTX uses much fewer registers.
69//
70// mov.u32 %r1, %tid.x;
71// mov.u32 %r2, %tid.y;
72// mul.wide.u32 %rl2, %r1, 128;
73// mov.u64 %rl3, a;
74// add.s64 %rl4, %rl3, %rl2;
75// mul.wide.u32 %rl5, %r2, 4;
76// add.s64 %rl6, %rl4, %rl5;
77// ld.global.f32 %f1, [%rl6]; // so far the same as unoptimized PTX
78// ld.global.f32 %f2, [%rl6+4]; // much better
79// ld.global.f32 %f3, [%rl6+128]; // much better
80// ld.global.f32 %f4, [%rl6+132]; // much better
81//
Hao Liu1d2a0612014-11-19 06:24:44 +000082// Another improvement enabled by the LowerGEP flag is to lower a GEP with
83// multiple indices to either multiple GEPs with a single index or arithmetic
84// operations (depending on whether the target uses alias analysis in codegen).
85// Such transformation can have following benefits:
86// (1) It can always extract constants in the indices of structure type.
87// (2) After such Lowering, there are more optimization opportunities such as
88// CSE, LICM and CGP.
89//
90// E.g. The following GEPs have multiple indices:
91// BB1:
92// %p = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 3
93// load %p
94// ...
95// BB2:
96// %p2 = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 2
97// load %p2
98// ...
99//
100// We can not do CSE for to the common part related to index "i64 %i". Lowering
101// GEPs can achieve such goals.
102// If the target does not use alias analysis in codegen, this pass will
103// lower a GEP with multiple indices into arithmetic operations:
104// BB1:
105// %1 = ptrtoint [10 x %struct]* %ptr to i64 ; CSE opportunity
106// %2 = mul i64 %i, length_of_10xstruct ; CSE opportunity
107// %3 = add i64 %1, %2 ; CSE opportunity
108// %4 = mul i64 %j1, length_of_struct
109// %5 = add i64 %3, %4
110// %6 = add i64 %3, struct_field_3 ; Constant offset
111// %p = inttoptr i64 %6 to i32*
112// load %p
113// ...
114// BB2:
115// %7 = ptrtoint [10 x %struct]* %ptr to i64 ; CSE opportunity
116// %8 = mul i64 %i, length_of_10xstruct ; CSE opportunity
117// %9 = add i64 %7, %8 ; CSE opportunity
118// %10 = mul i64 %j2, length_of_struct
119// %11 = add i64 %9, %10
120// %12 = add i64 %11, struct_field_2 ; Constant offset
121// %p = inttoptr i64 %12 to i32*
122// load %p2
123// ...
124//
125// If the target uses alias analysis in codegen, this pass will lower a GEP
126// with multiple indices into multiple GEPs with a single index:
127// BB1:
128// %1 = bitcast [10 x %struct]* %ptr to i8* ; CSE opportunity
129// %2 = mul i64 %i, length_of_10xstruct ; CSE opportunity
130// %3 = getelementptr i8* %1, i64 %2 ; CSE opportunity
131// %4 = mul i64 %j1, length_of_struct
132// %5 = getelementptr i8* %3, i64 %4
133// %6 = getelementptr i8* %5, struct_field_3 ; Constant offset
134// %p = bitcast i8* %6 to i32*
135// load %p
136// ...
137// BB2:
138// %7 = bitcast [10 x %struct]* %ptr to i8* ; CSE opportunity
139// %8 = mul i64 %i, length_of_10xstruct ; CSE opportunity
140// %9 = getelementptr i8* %7, i64 %8 ; CSE opportunity
141// %10 = mul i64 %j2, length_of_struct
142// %11 = getelementptr i8* %9, i64 %10
143// %12 = getelementptr i8* %11, struct_field_2 ; Constant offset
144// %p2 = bitcast i8* %12 to i32*
145// load %p2
146// ...
147//
148// Lowering GEPs can also benefit other passes such as LICM and CGP.
149// LICM (Loop Invariant Code Motion) can not hoist/sink a GEP of multiple
150// indices if one of the index is variant. If we lower such GEP into invariant
151// parts and variant parts, LICM can hoist/sink those invariant parts.
152// CGP (CodeGen Prepare) tries to sink address calculations that match the
153// target's addressing modes. A GEP with multiple indices may not match and will
154// not be sunk. If we lower such GEP into smaller parts, CGP may sink some of
155// them. So we end up with a better addressing mode.
156//
Eli Benderskya108a652014-05-01 18:38:36 +0000157//===----------------------------------------------------------------------===//
158
159#include "llvm/Analysis/TargetTransformInfo.h"
160#include "llvm/Analysis/ValueTracking.h"
161#include "llvm/IR/Constants.h"
162#include "llvm/IR/DataLayout.h"
163#include "llvm/IR/Instructions.h"
164#include "llvm/IR/LLVMContext.h"
165#include "llvm/IR/Module.h"
166#include "llvm/IR/Operator.h"
167#include "llvm/Support/CommandLine.h"
168#include "llvm/Support/raw_ostream.h"
169#include "llvm/Transforms/Scalar.h"
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000170#include "llvm/Transforms/Utils/Local.h"
Hao Liu1d2a0612014-11-19 06:24:44 +0000171#include "llvm/Target/TargetMachine.h"
172#include "llvm/Target/TargetSubtargetInfo.h"
173#include "llvm/IR/IRBuilder.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000174
175using namespace llvm;
176
177static cl::opt<bool> DisableSeparateConstOffsetFromGEP(
178 "disable-separate-const-offset-from-gep", cl::init(false),
179 cl::desc("Do not separate the constant offset from a GEP instruction"),
180 cl::Hidden);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000181// Setting this flag may emit false positives when the input module already
182// contains dead instructions. Therefore, we set it only in unit tests that are
183// free of dead code.
184static cl::opt<bool>
185 VerifyNoDeadCode("reassociate-geps-verify-no-dead-code", cl::init(false),
186 cl::desc("Verify this pass produces no dead code"),
187 cl::Hidden);
Eli Benderskya108a652014-05-01 18:38:36 +0000188
189namespace {
190
191/// \brief A helper class for separating a constant offset from a GEP index.
192///
193/// In real programs, a GEP index may be more complicated than a simple addition
194/// of something and a constant integer which can be trivially splitted. For
195/// example, to split ((a << 3) | 5) + b, we need to search deeper for the
Alp Tokerbeaca192014-05-15 01:52:21 +0000196/// constant offset, so that we can separate the index to (a << 3) + b and 5.
Eli Benderskya108a652014-05-01 18:38:36 +0000197///
198/// Therefore, this class looks into the expression that computes a given GEP
199/// index, and tries to find a constant integer that can be hoisted to the
200/// outermost level of the expression as an addition. Not every constant in an
201/// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
202/// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
203/// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
204class ConstantOffsetExtractor {
205 public:
Hao Liu1d2a0612014-11-19 06:24:44 +0000206 /// Extracts a constant offset from the given GEP index. It returns the
Eli Benderskya108a652014-05-01 18:38:36 +0000207 /// new index representing the remainder (equal to the original index minus
Hao Liu1d2a0612014-11-19 06:24:44 +0000208 /// the constant offset), or nullptr if we cannot extract a constant offset.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000209 /// \p Idx The given GEP index
210 /// \p GEP The given GEP
211 /// \p UserChainTail Outputs the tail of UserChain so that we can
212 /// garbage-collect unused instructions in UserChain.
213 static Value *Extract(Value *Idx, GetElementPtrInst *GEP,
214 User *&UserChainTail);
Hao Liu1d2a0612014-11-19 06:24:44 +0000215 /// Looks for a constant offset from the given GEP index without extracting
216 /// it. It returns the numeric value of the extracted constant offset (0 if
217 /// failed). The meaning of the arguments are the same as Extract.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000218 static int64_t Find(Value *Idx, GetElementPtrInst *GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000219
220 private:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000221 ConstantOffsetExtractor(Instruction *InsertionPt) : IP(InsertionPt) {}
Jingyue Wu84465472014-06-05 22:07:33 +0000222 /// Searches the expression that computes V for a non-zero constant C s.t.
223 /// V can be reassociated into the form V' + C. If the searching is
224 /// successful, returns C and update UserChain as a def-use chain from C to V;
225 /// otherwise, UserChain is empty.
Eli Benderskya108a652014-05-01 18:38:36 +0000226 ///
Jingyue Wu84465472014-06-05 22:07:33 +0000227 /// \p V The given expression
228 /// \p SignExtended Whether V will be sign-extended in the computation of the
229 /// GEP index
230 /// \p ZeroExtended Whether V will be zero-extended in the computation of the
231 /// GEP index
232 /// \p NonNegative Whether V is guaranteed to be non-negative. For example,
233 /// an index of an inbounds GEP is guaranteed to be
234 /// non-negative. Levaraging this, we can better split
235 /// inbounds GEPs.
236 APInt find(Value *V, bool SignExtended, bool ZeroExtended, bool NonNegative);
237 /// A helper function to look into both operands of a binary operator.
238 APInt findInEitherOperand(BinaryOperator *BO, bool SignExtended,
239 bool ZeroExtended);
240 /// After finding the constant offset C from the GEP index I, we build a new
241 /// index I' s.t. I' + C = I. This function builds and returns the new
242 /// index I' according to UserChain produced by function "find".
243 ///
244 /// The building conceptually takes two steps:
245 /// 1) iteratively distribute s/zext towards the leaves of the expression tree
246 /// that computes I
247 /// 2) reassociate the expression tree to the form I' + C.
248 ///
249 /// For example, to extract the 5 from sext(a + (b + 5)), we first distribute
250 /// sext to a, b and 5 so that we have
251 /// sext(a) + (sext(b) + 5).
252 /// Then, we reassociate it to
253 /// (sext(a) + sext(b)) + 5.
254 /// Given this form, we know I' is sext(a) + sext(b).
255 Value *rebuildWithoutConstOffset();
256 /// After the first step of rebuilding the GEP index without the constant
257 /// offset, distribute s/zext to the operands of all operators in UserChain.
258 /// e.g., zext(sext(a + (b + 5)) (assuming no overflow) =>
259 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))).
260 ///
261 /// The function also updates UserChain to point to new subexpressions after
262 /// distributing s/zext. e.g., the old UserChain of the above example is
263 /// 5 -> b + 5 -> a + (b + 5) -> sext(...) -> zext(sext(...)),
264 /// and the new UserChain is
265 /// zext(sext(5)) -> zext(sext(b)) + zext(sext(5)) ->
266 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))
267 ///
268 /// \p ChainIndex The index to UserChain. ChainIndex is initially
269 /// UserChain.size() - 1, and is decremented during
270 /// the recursion.
271 Value *distributeExtsAndCloneChain(unsigned ChainIndex);
272 /// Reassociates the GEP index to the form I' + C and returns I'.
273 Value *removeConstOffset(unsigned ChainIndex);
274 /// A helper function to apply ExtInsts, a list of s/zext, to value V.
275 /// e.g., if ExtInsts = [sext i32 to i64, zext i16 to i32], this function
276 /// returns "sext i32 (zext i16 V to i32) to i64".
277 Value *applyExts(Value *V);
Eli Benderskya108a652014-05-01 18:38:36 +0000278
279 /// Returns true if LHS and RHS have no bits in common, i.e., LHS | RHS == 0.
280 bool NoCommonBits(Value *LHS, Value *RHS) const;
281 /// Computes which bits are known to be one or zero.
282 /// \p KnownOne Mask of all bits that are known to be one.
283 /// \p KnownZero Mask of all bits that are known to be zero.
284 void ComputeKnownBits(Value *V, APInt &KnownOne, APInt &KnownZero) const;
Jingyue Wu84465472014-06-05 22:07:33 +0000285 /// A helper function that returns whether we can trace into the operands
286 /// of binary operator BO for a constant offset.
287 ///
288 /// \p SignExtended Whether BO is surrounded by sext
289 /// \p ZeroExtended Whether BO is surrounded by zext
290 /// \p NonNegative Whether BO is known to be non-negative, e.g., an in-bound
291 /// array index.
292 bool CanTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
293 bool NonNegative);
Eli Benderskya108a652014-05-01 18:38:36 +0000294
295 /// The path from the constant offset to the old GEP index. e.g., if the GEP
296 /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
297 /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
298 /// UserChain[2] will be the entire expression "a * b + (c + 5)".
299 ///
Jingyue Wu84465472014-06-05 22:07:33 +0000300 /// This path helps to rebuild the new GEP index.
Eli Benderskya108a652014-05-01 18:38:36 +0000301 SmallVector<User *, 8> UserChain;
Jingyue Wu84465472014-06-05 22:07:33 +0000302 /// A data structure used in rebuildWithoutConstOffset. Contains all
303 /// sext/zext instructions along UserChain.
304 SmallVector<CastInst *, 16> ExtInsts;
Eli Benderskya108a652014-05-01 18:38:36 +0000305 Instruction *IP; /// Insertion position of cloned instructions.
306};
307
308/// \brief A pass that tries to split every GEP in the function into a variadic
Alp Tokerbeaca192014-05-15 01:52:21 +0000309/// base and a constant offset. It is a FunctionPass because searching for the
Eli Benderskya108a652014-05-01 18:38:36 +0000310/// constant offset may inspect other basic blocks.
311class SeparateConstOffsetFromGEP : public FunctionPass {
312 public:
313 static char ID;
Hao Liu1d2a0612014-11-19 06:24:44 +0000314 SeparateConstOffsetFromGEP(const TargetMachine *TM = nullptr,
315 bool LowerGEP = false)
316 : FunctionPass(ID), TM(TM), LowerGEP(LowerGEP) {
Eli Benderskya108a652014-05-01 18:38:36 +0000317 initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry());
318 }
319
320 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth705b1852015-01-31 03:43:40 +0000321 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wu6e091c82015-02-01 02:33:02 +0000322 AU.setPreservesCFG();
Eli Benderskya108a652014-05-01 18:38:36 +0000323 }
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000324
Eli Benderskya108a652014-05-01 18:38:36 +0000325 bool runOnFunction(Function &F) override;
326
327 private:
328 /// Tries to split the given GEP into a variadic base and a constant offset,
329 /// and returns true if the splitting succeeds.
330 bool splitGEP(GetElementPtrInst *GEP);
Hao Liu1d2a0612014-11-19 06:24:44 +0000331 /// Lower a GEP with multiple indices into multiple GEPs with a single index.
332 /// Function splitGEP already split the original GEP into a variadic part and
333 /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
334 /// variadic part into a set of GEPs with a single index and applies
335 /// AccumulativeByteOffset to it.
336 /// \p Variadic The variadic part of the original GEP.
337 /// \p AccumulativeByteOffset The constant offset.
338 void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
339 int64_t AccumulativeByteOffset);
340 /// Lower a GEP with multiple indices into ptrtoint+arithmetics+inttoptr form.
341 /// Function splitGEP already split the original GEP into a variadic part and
342 /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
343 /// variadic part into a set of arithmetic operations and applies
344 /// AccumulativeByteOffset to it.
345 /// \p Variadic The variadic part of the original GEP.
346 /// \p AccumulativeByteOffset The constant offset.
347 void lowerToArithmetics(GetElementPtrInst *Variadic,
348 int64_t AccumulativeByteOffset);
349 /// Finds the constant offset within each index and accumulates them. If
350 /// LowerGEP is true, it finds in indices of both sequential and structure
351 /// types, otherwise it only finds in sequential indices. The output
352 /// NeedsExtraction indicates whether we successfully find a non-zero constant
353 /// offset.
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000354 int64_t accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
355 /// Canonicalize array indices to pointer-size integers. This helps to
356 /// simplify the logic of splitting a GEP. For example, if a + b is a
357 /// pointer-size integer, we have
358 /// gep base, a + b = gep (gep base, a), b
359 /// However, this equality may not hold if the size of a + b is smaller than
360 /// the pointer size, because LLVM conceptually sign-extends GEP indices to
361 /// pointer size before computing the address
362 /// (http://llvm.org/docs/LangRef.html#id181).
363 ///
364 /// This canonicalization is very likely already done in clang and
365 /// instcombine. Therefore, the program will probably remain the same.
366 ///
Jingyue Wu5c7b1ae2014-06-08 23:49:34 +0000367 /// Returns true if the module changes.
368 ///
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000369 /// Verified in @i32_add in split-gep.ll
370 bool canonicalizeArrayIndicesToPointerSize(GetElementPtrInst *GEP);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000371 /// Verify F is free of dead code.
372 void verifyNoDeadCode(Function &F);
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000373
Hao Liu1d2a0612014-11-19 06:24:44 +0000374 const TargetMachine *TM;
375 /// Whether to lower a GEP with multiple indices into arithmetic operations or
376 /// multiple GEPs with a single index.
377 bool LowerGEP;
Eli Benderskya108a652014-05-01 18:38:36 +0000378};
379} // anonymous namespace
380
381char SeparateConstOffsetFromGEP::ID = 0;
382INITIALIZE_PASS_BEGIN(
383 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
384 "Split GEPs to a variadic base and a constant offset for better CSE", false,
385 false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000386INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Eli Benderskya108a652014-05-01 18:38:36 +0000387INITIALIZE_PASS_END(
388 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
389 "Split GEPs to a variadic base and a constant offset for better CSE", false,
390 false)
391
Hao Liu1d2a0612014-11-19 06:24:44 +0000392FunctionPass *
393llvm::createSeparateConstOffsetFromGEPPass(const TargetMachine *TM,
394 bool LowerGEP) {
395 return new SeparateConstOffsetFromGEP(TM, LowerGEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000396}
397
Jingyue Wu84465472014-06-05 22:07:33 +0000398bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
399 bool ZeroExtended,
400 BinaryOperator *BO,
401 bool NonNegative) {
402 // We only consider ADD, SUB and OR, because a non-zero constant found in
403 // expressions composed of these operations can be easily hoisted as a
404 // constant offset by reassociation.
405 if (BO->getOpcode() != Instruction::Add &&
406 BO->getOpcode() != Instruction::Sub &&
407 BO->getOpcode() != Instruction::Or) {
408 return false;
409 }
410
411 Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
412 // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
413 // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
414 if (BO->getOpcode() == Instruction::Or && !NoCommonBits(LHS, RHS))
415 return false;
416
417 // In addition, tracing into BO requires that its surrounding s/zext (if
418 // any) is distributable to both operands.
419 //
420 // Suppose BO = A op B.
421 // SignExtended | ZeroExtended | Distributable?
422 // --------------+--------------+----------------------------------
423 // 0 | 0 | true because no s/zext exists
424 // 0 | 1 | zext(BO) == zext(A) op zext(B)
425 // 1 | 0 | sext(BO) == sext(A) op sext(B)
426 // 1 | 1 | zext(sext(BO)) ==
427 // | | zext(sext(A)) op zext(sext(B))
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000428 if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
Jingyue Wu84465472014-06-05 22:07:33 +0000429 // If a + b >= 0 and (a >= 0 or b >= 0), then
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000430 // sext(a + b) = sext(a) + sext(b)
Jingyue Wu84465472014-06-05 22:07:33 +0000431 // even if the addition is not marked nsw.
432 //
433 // Leveraging this invarient, we can trace into an sext'ed inbound GEP
434 // index if the constant offset is non-negative.
435 //
436 // Verified in @sext_add in split-gep.ll.
437 if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
438 if (!ConstLHS->isNegative())
439 return true;
440 }
441 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
442 if (!ConstRHS->isNegative())
443 return true;
444 }
445 }
Jingyue Wu80a738d2014-05-27 18:00:00 +0000446
447 // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
448 // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
449 if (BO->getOpcode() == Instruction::Add ||
450 BO->getOpcode() == Instruction::Sub) {
Jingyue Wu84465472014-06-05 22:07:33 +0000451 if (SignExtended && !BO->hasNoSignedWrap())
452 return false;
453 if (ZeroExtended && !BO->hasNoUnsignedWrap())
454 return false;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000455 }
456
Jingyue Wu84465472014-06-05 22:07:33 +0000457 return true;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000458}
459
Jingyue Wu84465472014-06-05 22:07:33 +0000460APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
461 bool SignExtended,
462 bool ZeroExtended) {
463 // BO being non-negative does not shed light on whether its operands are
464 // non-negative. Clear the NonNegative flag here.
465 APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
466 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000467 // If we found a constant offset in the left operand, stop and return that.
468 // This shortcut might cause us to miss opportunities of combining the
469 // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
470 // However, such cases are probably already handled by -instcombine,
471 // given this pass runs after the standard optimizations.
472 if (ConstantOffset != 0) return ConstantOffset;
Jingyue Wu84465472014-06-05 22:07:33 +0000473 ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
474 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000475 // If U is a sub operator, negate the constant offset found in the right
476 // operand.
Jingyue Wu84465472014-06-05 22:07:33 +0000477 if (BO->getOpcode() == Instruction::Sub)
478 ConstantOffset = -ConstantOffset;
479 return ConstantOffset;
Eli Benderskya108a652014-05-01 18:38:36 +0000480}
481
Jingyue Wu84465472014-06-05 22:07:33 +0000482APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
483 bool ZeroExtended, bool NonNegative) {
484 // TODO(jingyue): We could trace into integer/pointer casts, such as
Eli Benderskya108a652014-05-01 18:38:36 +0000485 // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
486 // integers because it gives good enough results for our benchmarks.
Jingyue Wu84465472014-06-05 22:07:33 +0000487 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Eli Benderskya108a652014-05-01 18:38:36 +0000488
Jingyue Wu84465472014-06-05 22:07:33 +0000489 // We cannot do much with Values that are not a User, such as an Argument.
Eli Benderskya108a652014-05-01 18:38:36 +0000490 User *U = dyn_cast<User>(V);
Jingyue Wu84465472014-06-05 22:07:33 +0000491 if (U == nullptr) return APInt(BitWidth, 0);
Eli Benderskya108a652014-05-01 18:38:36 +0000492
Jingyue Wu84465472014-06-05 22:07:33 +0000493 APInt ConstantOffset(BitWidth, 0);
494 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Eli Benderskya108a652014-05-01 18:38:36 +0000495 // Hooray, we found it!
Jingyue Wu84465472014-06-05 22:07:33 +0000496 ConstantOffset = CI->getValue();
497 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
498 // Trace into subexpressions for more hoisting opportunities.
499 if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative)) {
500 ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
Eli Benderskya108a652014-05-01 18:38:36 +0000501 }
Jingyue Wu84465472014-06-05 22:07:33 +0000502 } else if (isa<SExtInst>(V)) {
503 ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
504 ZeroExtended, NonNegative).sext(BitWidth);
505 } else if (isa<ZExtInst>(V)) {
506 // As an optimization, we can clear the SignExtended flag because
507 // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
508 //
509 // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
Jingyue Wu84465472014-06-05 22:07:33 +0000510 ConstantOffset =
511 find(U->getOperand(0), /* SignExtended */ false,
512 /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
Eli Benderskya108a652014-05-01 18:38:36 +0000513 }
Jingyue Wu84465472014-06-05 22:07:33 +0000514
515 // If we found a non-zero constant offset, add it to the path for
516 // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
517 // help this optimization.
Eli Benderskya108a652014-05-01 18:38:36 +0000518 if (ConstantOffset != 0)
519 UserChain.push_back(U);
520 return ConstantOffset;
521}
522
Jingyue Wu84465472014-06-05 22:07:33 +0000523Value *ConstantOffsetExtractor::applyExts(Value *V) {
524 Value *Current = V;
525 // ExtInsts is built in the use-def order. Therefore, we apply them to V
526 // in the reversed order.
527 for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
528 if (Constant *C = dyn_cast<Constant>(Current)) {
529 // If Current is a constant, apply s/zext using ConstantExpr::getCast.
530 // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
531 Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
532 } else {
533 Instruction *Ext = (*I)->clone();
534 Ext->setOperand(0, Current);
535 Ext->insertBefore(IP);
536 Current = Ext;
537 }
Eli Benderskya108a652014-05-01 18:38:36 +0000538 }
Jingyue Wu84465472014-06-05 22:07:33 +0000539 return Current;
Eli Benderskya108a652014-05-01 18:38:36 +0000540}
541
Jingyue Wu84465472014-06-05 22:07:33 +0000542Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
543 distributeExtsAndCloneChain(UserChain.size() - 1);
544 // Remove all nullptrs (used to be s/zext) from UserChain.
545 unsigned NewSize = 0;
546 for (auto I = UserChain.begin(), E = UserChain.end(); I != E; ++I) {
547 if (*I != nullptr) {
548 UserChain[NewSize] = *I;
549 NewSize++;
550 }
Eli Benderskya108a652014-05-01 18:38:36 +0000551 }
Jingyue Wu84465472014-06-05 22:07:33 +0000552 UserChain.resize(NewSize);
553 return removeConstOffset(UserChain.size() - 1);
Eli Benderskya108a652014-05-01 18:38:36 +0000554}
555
Jingyue Wu84465472014-06-05 22:07:33 +0000556Value *
557ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
558 User *U = UserChain[ChainIndex];
559 if (ChainIndex == 0) {
560 assert(isa<ConstantInt>(U));
561 // If U is a ConstantInt, applyExts will return a ConstantInt as well.
562 return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
563 }
Eli Benderskya108a652014-05-01 18:38:36 +0000564
Jingyue Wu84465472014-06-05 22:07:33 +0000565 if (CastInst *Cast = dyn_cast<CastInst>(U)) {
566 assert((isa<SExtInst>(Cast) || isa<ZExtInst>(Cast)) &&
567 "We only traced into two types of CastInst: sext and zext");
568 ExtInsts.push_back(Cast);
569 UserChain[ChainIndex] = nullptr;
570 return distributeExtsAndCloneChain(ChainIndex - 1);
571 }
572
573 // Function find only trace into BinaryOperator and CastInst.
574 BinaryOperator *BO = cast<BinaryOperator>(U);
575 // OpNo = which operand of BO is UserChain[ChainIndex - 1]
576 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
577 Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
578 Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
579
580 BinaryOperator *NewBO = nullptr;
581 if (OpNo == 0) {
582 NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
583 BO->getName(), IP);
584 } else {
585 NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
586 BO->getName(), IP);
587 }
588 return UserChain[ChainIndex] = NewBO;
Eli Benderskya108a652014-05-01 18:38:36 +0000589}
590
Jingyue Wu84465472014-06-05 22:07:33 +0000591Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
592 if (ChainIndex == 0) {
593 assert(isa<ConstantInt>(UserChain[ChainIndex]));
594 return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
595 }
Eli Benderskya108a652014-05-01 18:38:36 +0000596
Jingyue Wu84465472014-06-05 22:07:33 +0000597 BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000598 assert(BO->getNumUses() <= 1 &&
599 "distributeExtsAndCloneChain clones each BinaryOperator in "
600 "UserChain, so no one should be used more than "
601 "once");
602
Jingyue Wu84465472014-06-05 22:07:33 +0000603 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
604 assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
605 Value *NextInChain = removeConstOffset(ChainIndex - 1);
606 Value *TheOther = BO->getOperand(1 - OpNo);
607
608 // If NextInChain is 0 and not the LHS of a sub, we can simplify the
609 // sub-expression to be just TheOther.
610 if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
611 if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
612 return TheOther;
613 }
614
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000615 BinaryOperator::BinaryOps NewOp = BO->getOpcode();
Jingyue Wu84465472014-06-05 22:07:33 +0000616 if (BO->getOpcode() == Instruction::Or) {
617 // Rebuild "or" as "add", because "or" may be invalid for the new
618 // epxression.
619 //
620 // For instance, given
621 // a | (b + 5) where a and b + 5 have no common bits,
622 // we can extract 5 as the constant offset.
623 //
624 // However, reusing the "or" in the new index would give us
625 // (a | b) + 5
626 // which does not equal a | (b + 5).
627 //
628 // Replacing the "or" with "add" is fine, because
629 // a | (b + 5) = a + (b + 5) = (a + b) + 5
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000630 NewOp = Instruction::Add;
Jingyue Wu84465472014-06-05 22:07:33 +0000631 }
632
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000633 BinaryOperator *NewBO;
634 if (OpNo == 0) {
635 NewBO = BinaryOperator::Create(NewOp, NextInChain, TheOther, "", IP);
636 } else {
637 NewBO = BinaryOperator::Create(NewOp, TheOther, NextInChain, "", IP);
638 }
639 NewBO->takeName(BO);
640 return NewBO;
Eli Benderskya108a652014-05-01 18:38:36 +0000641}
642
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000643Value *ConstantOffsetExtractor::Extract(Value *Idx, GetElementPtrInst *GEP,
644 User *&UserChainTail) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645 ConstantOffsetExtractor Extractor(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000646 // Find a non-zero constant offset first.
Jingyue Wu84465472014-06-05 22:07:33 +0000647 APInt ConstantOffset =
648 Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
649 GEP->isInBounds());
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000650 if (ConstantOffset == 0) {
651 UserChainTail = nullptr;
Hao Liu1d2a0612014-11-19 06:24:44 +0000652 return nullptr;
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000653 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000654 // Separates the constant offset from the GEP index.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000655 Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
656 UserChainTail = Extractor.UserChain.back();
657 return IdxWithoutConstOffset;
Eli Benderskya108a652014-05-01 18:38:36 +0000658}
659
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000660int64_t ConstantOffsetExtractor::Find(Value *Idx, GetElementPtrInst *GEP) {
Jingyue Wu84465472014-06-05 22:07:33 +0000661 // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000662 return ConstantOffsetExtractor(GEP)
Jingyue Wu84465472014-06-05 22:07:33 +0000663 .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
664 GEP->isInBounds())
665 .getSExtValue();
Eli Benderskya108a652014-05-01 18:38:36 +0000666}
667
668void ConstantOffsetExtractor::ComputeKnownBits(Value *V, APInt &KnownOne,
669 APInt &KnownZero) const {
670 IntegerType *IT = cast<IntegerType>(V->getType());
671 KnownOne = APInt(IT->getBitWidth(), 0);
672 KnownZero = APInt(IT->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000673 const DataLayout &DL = IP->getModule()->getDataLayout();
Jay Foada0653a32014-05-14 21:14:37 +0000674 llvm::computeKnownBits(V, KnownZero, KnownOne, DL, 0);
Eli Benderskya108a652014-05-01 18:38:36 +0000675}
676
677bool ConstantOffsetExtractor::NoCommonBits(Value *LHS, Value *RHS) const {
678 assert(LHS->getType() == RHS->getType() &&
679 "LHS and RHS should have the same type");
680 APInt LHSKnownOne, LHSKnownZero, RHSKnownOne, RHSKnownZero;
681 ComputeKnownBits(LHS, LHSKnownOne, LHSKnownZero);
682 ComputeKnownBits(RHS, RHSKnownOne, RHSKnownZero);
683 return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
684}
685
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000686bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
687 GetElementPtrInst *GEP) {
688 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000689 const DataLayout &DL = GEP->getModule()->getDataLayout();
690 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000691 gep_type_iterator GTI = gep_type_begin(*GEP);
692 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
693 I != E; ++I, ++GTI) {
694 // Skip struct member indices which must be i32.
695 if (isa<SequentialType>(*GTI)) {
696 if ((*I)->getType() != IntPtrTy) {
697 *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
698 Changed = true;
699 }
700 }
701 }
702 return Changed;
703}
704
705int64_t
706SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
707 bool &NeedsExtraction) {
Eli Benderskya108a652014-05-01 18:38:36 +0000708 NeedsExtraction = false;
709 int64_t AccumulativeByteOffset = 0;
710 gep_type_iterator GTI = gep_type_begin(*GEP);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000711 const DataLayout &DL = GEP->getModule()->getDataLayout();
Eli Benderskya108a652014-05-01 18:38:36 +0000712 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
713 if (isa<SequentialType>(*GTI)) {
714 // Tries to extract a constant offset from this GEP index.
715 int64_t ConstantOffset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000716 ConstantOffsetExtractor::Find(GEP->getOperand(I), GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000717 if (ConstantOffset != 0) {
718 NeedsExtraction = true;
719 // A GEP may have multiple indices. We accumulate the extracted
720 // constant offset to a byte offset, and later offset the remainder of
721 // the original GEP with this byte offset.
722 AccumulativeByteOffset +=
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000723 ConstantOffset * DL.getTypeAllocSize(GTI.getIndexedType());
Eli Benderskya108a652014-05-01 18:38:36 +0000724 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000725 } else if (LowerGEP) {
726 StructType *StTy = cast<StructType>(*GTI);
727 uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
728 // Skip field 0 as the offset is always 0.
729 if (Field != 0) {
730 NeedsExtraction = true;
731 AccumulativeByteOffset +=
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000732 DL.getStructLayout(StTy)->getElementOffset(Field);
Hao Liu1d2a0612014-11-19 06:24:44 +0000733 }
Eli Benderskya108a652014-05-01 18:38:36 +0000734 }
735 }
736 return AccumulativeByteOffset;
737}
738
Hao Liu1d2a0612014-11-19 06:24:44 +0000739void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
740 GetElementPtrInst *Variadic, int64_t AccumulativeByteOffset) {
741 IRBuilder<> Builder(Variadic);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000742 const DataLayout &DL = Variadic->getModule()->getDataLayout();
743 Type *IntPtrTy = DL.getIntPtrType(Variadic->getType());
Hao Liu1d2a0612014-11-19 06:24:44 +0000744
745 Type *I8PtrTy =
746 Builder.getInt8PtrTy(Variadic->getType()->getPointerAddressSpace());
747 Value *ResultPtr = Variadic->getOperand(0);
748 if (ResultPtr->getType() != I8PtrTy)
749 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
750
751 gep_type_iterator GTI = gep_type_begin(*Variadic);
752 // Create an ugly GEP for each sequential index. We don't create GEPs for
753 // structure indices, as they are accumulated in the constant offset index.
754 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
755 if (isa<SequentialType>(*GTI)) {
756 Value *Idx = Variadic->getOperand(I);
757 // Skip zero indices.
758 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
759 if (CI->isZero())
760 continue;
761
762 APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000763 DL.getTypeAllocSize(GTI.getIndexedType()));
Hao Liu1d2a0612014-11-19 06:24:44 +0000764 // Scale the index by element size.
765 if (ElementSize != 1) {
766 if (ElementSize.isPowerOf2()) {
767 Idx = Builder.CreateShl(
768 Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
769 } else {
770 Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
771 }
772 }
773 // Create an ugly GEP with a single index for each index.
David Blaikie93c54442015-04-03 19:41:44 +0000774 ResultPtr =
775 Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Idx, "uglygep");
Hao Liu1d2a0612014-11-19 06:24:44 +0000776 }
777 }
778
779 // Create a GEP with the constant offset index.
780 if (AccumulativeByteOffset != 0) {
781 Value *Offset = ConstantInt::get(IntPtrTy, AccumulativeByteOffset);
David Blaikie93c54442015-04-03 19:41:44 +0000782 ResultPtr =
783 Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Offset, "uglygep");
Hao Liu1d2a0612014-11-19 06:24:44 +0000784 }
785 if (ResultPtr->getType() != Variadic->getType())
786 ResultPtr = Builder.CreateBitCast(ResultPtr, Variadic->getType());
787
788 Variadic->replaceAllUsesWith(ResultPtr);
789 Variadic->eraseFromParent();
790}
791
792void
793SeparateConstOffsetFromGEP::lowerToArithmetics(GetElementPtrInst *Variadic,
794 int64_t AccumulativeByteOffset) {
795 IRBuilder<> Builder(Variadic);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000796 const DataLayout &DL = Variadic->getModule()->getDataLayout();
797 Type *IntPtrTy = DL.getIntPtrType(Variadic->getType());
Hao Liu1d2a0612014-11-19 06:24:44 +0000798
799 Value *ResultPtr = Builder.CreatePtrToInt(Variadic->getOperand(0), IntPtrTy);
800 gep_type_iterator GTI = gep_type_begin(*Variadic);
801 // Create ADD/SHL/MUL arithmetic operations for each sequential indices. We
802 // don't create arithmetics for structure indices, as they are accumulated
803 // in the constant offset index.
804 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
805 if (isa<SequentialType>(*GTI)) {
806 Value *Idx = Variadic->getOperand(I);
807 // Skip zero indices.
808 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
809 if (CI->isZero())
810 continue;
811
812 APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000813 DL.getTypeAllocSize(GTI.getIndexedType()));
Hao Liu1d2a0612014-11-19 06:24:44 +0000814 // Scale the index by element size.
815 if (ElementSize != 1) {
816 if (ElementSize.isPowerOf2()) {
817 Idx = Builder.CreateShl(
818 Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
819 } else {
820 Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
821 }
822 }
823 // Create an ADD for each index.
824 ResultPtr = Builder.CreateAdd(ResultPtr, Idx);
825 }
826 }
827
828 // Create an ADD for the constant offset index.
829 if (AccumulativeByteOffset != 0) {
830 ResultPtr = Builder.CreateAdd(
831 ResultPtr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset));
832 }
833
834 ResultPtr = Builder.CreateIntToPtr(ResultPtr, Variadic->getType());
835 Variadic->replaceAllUsesWith(ResultPtr);
836 Variadic->eraseFromParent();
837}
838
Eli Benderskya108a652014-05-01 18:38:36 +0000839bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
840 // Skip vector GEPs.
841 if (GEP->getType()->isVectorTy())
842 return false;
843
844 // The backend can already nicely handle the case where all indices are
845 // constant.
846 if (GEP->hasAllConstantIndices())
847 return false;
848
Jingyue Wu0bdc0272014-07-16 23:25:00 +0000849 bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000850
Eli Benderskya108a652014-05-01 18:38:36 +0000851 bool NeedsExtraction;
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000852 int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
Eli Benderskya108a652014-05-01 18:38:36 +0000853
854 if (!NeedsExtraction)
855 return Changed;
Hao Liu1d2a0612014-11-19 06:24:44 +0000856 // If LowerGEP is disabled, before really splitting the GEP, check whether the
857 // backend supports the addressing mode we are about to produce. If no, this
858 // splitting probably won't be beneficial.
859 // If LowerGEP is enabled, even the extracted constant offset can not match
860 // the addressing mode, we can still do optimizations to other lowered parts
861 // of variable indices. Therefore, we don't check for addressing modes in that
862 // case.
863 if (!LowerGEP) {
Chandler Carruth705b1852015-01-31 03:43:40 +0000864 TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000865 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
866 *GEP->getParent()->getParent());
Hao Liu1d2a0612014-11-19 06:24:44 +0000867 if (!TTI.isLegalAddressingMode(GEP->getType()->getElementType(),
868 /*BaseGV=*/nullptr, AccumulativeByteOffset,
869 /*HasBaseReg=*/true, /*Scale=*/0)) {
870 return Changed;
871 }
Eli Benderskya108a652014-05-01 18:38:36 +0000872 }
873
Hao Liu1d2a0612014-11-19 06:24:44 +0000874 // Remove the constant offset in each sequential index. The resultant GEP
875 // computes the variadic base.
876 // Notice that we don't remove struct field indices here. If LowerGEP is
877 // disabled, a structure index is not accumulated and we still use the old
878 // one. If LowerGEP is enabled, a structure index is accumulated in the
879 // constant offset. LowerToSingleIndexGEPs or lowerToArithmetics will later
880 // handle the constant offset and won't need a new structure index.
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000881 gep_type_iterator GTI = gep_type_begin(*GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000882 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
883 if (isa<SequentialType>(*GTI)) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000884 // Splits this GEP index into a variadic part and a constant offset, and
885 // uses the variadic part as the new index.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000886 Value *OldIdx = GEP->getOperand(I);
887 User *UserChainTail;
888 Value *NewIdx =
889 ConstantOffsetExtractor::Extract(OldIdx, GEP, UserChainTail);
Hao Liu1d2a0612014-11-19 06:24:44 +0000890 if (NewIdx != nullptr) {
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000891 // Switches to the index with the constant offset removed.
Eli Benderskya108a652014-05-01 18:38:36 +0000892 GEP->setOperand(I, NewIdx);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000893 // After switching to the new index, we can garbage-collect UserChain
894 // and the old index if they are not used.
895 RecursivelyDeleteTriviallyDeadInstructions(UserChainTail);
896 RecursivelyDeleteTriviallyDeadInstructions(OldIdx);
Eli Benderskya108a652014-05-01 18:38:36 +0000897 }
898 }
899 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000900
Jingyue Wu84465472014-06-05 22:07:33 +0000901 // Clear the inbounds attribute because the new index may be off-bound.
902 // e.g.,
903 //
904 // b = add i64 a, 5
905 // addr = gep inbounds float* p, i64 b
906 //
907 // is transformed to:
908 //
909 // addr2 = gep float* p, i64 a
910 // addr = gep float* addr2, i64 5
911 //
912 // If a is -4, although the old index b is in bounds, the new index a is
913 // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
914 // inbounds keyword is not present, the offsets are added to the base
915 // address with silently-wrapping two's complement arithmetic".
916 // Therefore, the final code will be a semantically equivalent.
917 //
918 // TODO(jingyue): do some range analysis to keep as many inbounds as
919 // possible. GEPs with inbounds are more friendly to alias analysis.
920 GEP->setIsInBounds(false);
Eli Benderskya108a652014-05-01 18:38:36 +0000921
Hao Liu1d2a0612014-11-19 06:24:44 +0000922 // Lowers a GEP to either GEPs with a single index or arithmetic operations.
923 if (LowerGEP) {
924 // As currently BasicAA does not analyze ptrtoint/inttoptr, do not lower to
925 // arithmetic operations if the target uses alias analysis in codegen.
Eric Christophere38c8d42015-01-27 07:16:37 +0000926 if (TM && TM->getSubtargetImpl(*GEP->getParent()->getParent())->useAA())
Hao Liu1d2a0612014-11-19 06:24:44 +0000927 lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
928 else
929 lowerToArithmetics(GEP, AccumulativeByteOffset);
930 return true;
931 }
932
933 // No need to create another GEP if the accumulative byte offset is 0.
934 if (AccumulativeByteOffset == 0)
935 return true;
936
Eli Benderskya108a652014-05-01 18:38:36 +0000937 // Offsets the base with the accumulative byte offset.
938 //
939 // %gep ; the base
940 // ... %gep ...
941 //
942 // => add the offset
943 //
944 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000945 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +0000946 // %gep ; will be removed
947 // ... %gep ...
948 //
949 // => replace all uses of %gep with %new.gep and remove %gep
950 //
951 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000952 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +0000953 // ... %new.gep ...
954 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000955 // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
956 // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
957 // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
958 // type of %gep.
Eli Benderskya108a652014-05-01 18:38:36 +0000959 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000960 // %gep2 ; clone of %gep
961 // %0 = bitcast %gep2 to i8*
962 // %uglygep = gep %0, <offset>
963 // %new.gep = bitcast %uglygep to <type of %gep>
964 // ... %new.gep ...
Eli Benderskya108a652014-05-01 18:38:36 +0000965 Instruction *NewGEP = GEP->clone();
966 NewGEP->insertBefore(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000967
Jingyue Wufe72fce2014-10-25 18:34:03 +0000968 // Per ANSI C standard, signed / unsigned = unsigned and signed % unsigned =
969 // unsigned.. Therefore, we cast ElementTypeSizeOfGEP to signed because it is
970 // used with unsigned integers later.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000971 const DataLayout &DL = GEP->getModule()->getDataLayout();
Jingyue Wufe72fce2014-10-25 18:34:03 +0000972 int64_t ElementTypeSizeOfGEP = static_cast<int64_t>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000973 DL.getTypeAllocSize(GEP->getType()->getElementType()));
974 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000975 if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
976 // Very likely. As long as %gep is natually aligned, the byte offset we
977 // extracted should be a multiple of sizeof(*%gep).
Jingyue Wufe72fce2014-10-25 18:34:03 +0000978 int64_t Index = AccumulativeByteOffset / ElementTypeSizeOfGEP;
David Blaikie741c8f82015-03-14 01:53:18 +0000979 NewGEP = GetElementPtrInst::Create(GEP->getResultElementType(), NewGEP,
980 ConstantInt::get(IntPtrTy, Index, true),
981 GEP->getName(), GEP);
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000982 } else {
983 // Unlikely but possible. For example,
984 // #pragma pack(1)
985 // struct S {
986 // int a[3];
987 // int64 b[8];
988 // };
989 // #pragma pack()
990 //
991 // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
992 // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
993 // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
994 // sizeof(int64).
995 //
996 // Emit an uglygep in this case.
997 Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
998 GEP->getPointerAddressSpace());
999 NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
1000 NewGEP = GetElementPtrInst::Create(
David Blaikie741c8f82015-03-14 01:53:18 +00001001 Type::getInt8Ty(GEP->getContext()), NewGEP,
1002 ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true), "uglygep",
1003 GEP);
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001004 if (GEP->getType() != I8PtrTy)
1005 NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
1006 }
1007
1008 GEP->replaceAllUsesWith(NewGEP);
Eli Benderskya108a652014-05-01 18:38:36 +00001009 GEP->eraseFromParent();
1010
1011 return true;
1012}
1013
1014bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
Jingyue Wu6c26bb62015-02-01 02:34:41 +00001015 if (skipOptnoneFunction(F))
1016 return false;
1017
Eli Benderskya108a652014-05-01 18:38:36 +00001018 if (DisableSeparateConstOffsetFromGEP)
1019 return false;
1020
1021 bool Changed = false;
1022 for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B) {
1023 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ) {
1024 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++)) {
1025 Changed |= splitGEP(GEP);
1026 }
1027 // No need to split GEP ConstantExprs because all its indices are constant
1028 // already.
1029 }
1030 }
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001031
1032 if (VerifyNoDeadCode)
1033 verifyNoDeadCode(F);
1034
Eli Benderskya108a652014-05-01 18:38:36 +00001035 return Changed;
1036}
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001037
1038void SeparateConstOffsetFromGEP::verifyNoDeadCode(Function &F) {
1039 for (auto &B : F) {
1040 for (auto &I : B) {
1041 if (isInstructionTriviallyDead(&I)) {
1042 std::string ErrMessage;
1043 raw_string_ostream RSO(ErrMessage);
1044 RSO << "Dead instruction detected!\n" << I << "\n";
1045 llvm_unreachable(RSO.str().c_str());
1046 }
1047 }
1048 }
1049}