1fef3036dSMartin Elshuber //===- InterleavedLoadCombine.cpp - Combine Interleaved Loads ---*- C++ -*-===//
2fef3036dSMartin Elshuber //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fef3036dSMartin Elshuber //
7fef3036dSMartin Elshuber //===----------------------------------------------------------------------===//
8fef3036dSMartin Elshuber //
9fef3036dSMartin Elshuber // \file
10fef3036dSMartin Elshuber //
11fef3036dSMartin Elshuber // This file defines the interleaved-load-combine pass. The pass searches for
12fef3036dSMartin Elshuber // ShuffleVectorInstruction that execute interleaving loads. If a matching
13fef3036dSMartin Elshuber // pattern is found, it adds a combined load and further instructions in a
14fef3036dSMartin Elshuber // pattern that is detectable by InterleavedAccesPass. The old instructions are
15fef3036dSMartin Elshuber // left dead to be removed later. The pass is specifically designed to be
16fef3036dSMartin Elshuber // executed just before InterleavedAccesPass to find any left-over instances
17fef3036dSMartin Elshuber // that are not detected within former passes.
18fef3036dSMartin Elshuber //
19fef3036dSMartin Elshuber //===----------------------------------------------------------------------===//
20fef3036dSMartin Elshuber
21fef3036dSMartin Elshuber #include "llvm/ADT/Statistic.h"
22fef3036dSMartin Elshuber #include "llvm/Analysis/MemorySSA.h"
23fef3036dSMartin Elshuber #include "llvm/Analysis/MemorySSAUpdater.h"
24fef3036dSMartin Elshuber #include "llvm/Analysis/OptimizationRemarkEmitter.h"
25fef3036dSMartin Elshuber #include "llvm/Analysis/TargetTransformInfo.h"
26fef3036dSMartin Elshuber #include "llvm/CodeGen/Passes.h"
27fef3036dSMartin Elshuber #include "llvm/CodeGen/TargetLowering.h"
28fef3036dSMartin Elshuber #include "llvm/CodeGen/TargetPassConfig.h"
29fef3036dSMartin Elshuber #include "llvm/CodeGen/TargetSubtargetInfo.h"
30fef3036dSMartin Elshuber #include "llvm/IR/DataLayout.h"
31fef3036dSMartin Elshuber #include "llvm/IR/Dominators.h"
32fef3036dSMartin Elshuber #include "llvm/IR/Function.h"
33a278250bSNico Weber #include "llvm/IR/IRBuilder.h"
34989f1c72Sserge-sans-paille #include "llvm/IR/Instructions.h"
35fef3036dSMartin Elshuber #include "llvm/IR/Module.h"
3605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
37fef3036dSMartin Elshuber #include "llvm/Pass.h"
38fef3036dSMartin Elshuber #include "llvm/Support/Debug.h"
39fef3036dSMartin Elshuber #include "llvm/Support/ErrorHandling.h"
40fef3036dSMartin Elshuber #include "llvm/Support/raw_ostream.h"
41fef3036dSMartin Elshuber #include "llvm/Target/TargetMachine.h"
42fef3036dSMartin Elshuber
43fef3036dSMartin Elshuber #include <algorithm>
44fef3036dSMartin Elshuber #include <cassert>
45fef3036dSMartin Elshuber #include <list>
46fef3036dSMartin Elshuber
47fef3036dSMartin Elshuber using namespace llvm;
48fef3036dSMartin Elshuber
49fef3036dSMartin Elshuber #define DEBUG_TYPE "interleaved-load-combine"
50fef3036dSMartin Elshuber
51fef3036dSMartin Elshuber namespace {
52fef3036dSMartin Elshuber
53fef3036dSMartin Elshuber /// Statistic counter
54fef3036dSMartin Elshuber STATISTIC(NumInterleavedLoadCombine, "Number of combined loads");
55fef3036dSMartin Elshuber
56fef3036dSMartin Elshuber /// Option to disable the pass
57fef3036dSMartin Elshuber static cl::opt<bool> DisableInterleavedLoadCombine(
58fef3036dSMartin Elshuber "disable-" DEBUG_TYPE, cl::init(false), cl::Hidden,
59fef3036dSMartin Elshuber cl::desc("Disable combining of interleaved loads"));
60fef3036dSMartin Elshuber
61fef3036dSMartin Elshuber struct VectorInfo;
62fef3036dSMartin Elshuber
63fef3036dSMartin Elshuber struct InterleavedLoadCombineImpl {
64fef3036dSMartin Elshuber public:
InterleavedLoadCombineImpl__anon07e87e4b0111::InterleavedLoadCombineImpl65fef3036dSMartin Elshuber InterleavedLoadCombineImpl(Function &F, DominatorTree &DT, MemorySSA &MSSA,
66fef3036dSMartin Elshuber TargetMachine &TM)
67fef3036dSMartin Elshuber : F(F), DT(DT), MSSA(MSSA),
68fef3036dSMartin Elshuber TLI(*TM.getSubtargetImpl(F)->getTargetLowering()),
69fef3036dSMartin Elshuber TTI(TM.getTargetTransformInfo(F)) {}
70fef3036dSMartin Elshuber
71fef3036dSMartin Elshuber /// Scan the function for interleaved load candidates and execute the
72fef3036dSMartin Elshuber /// replacement if applicable.
73fef3036dSMartin Elshuber bool run();
74fef3036dSMartin Elshuber
75fef3036dSMartin Elshuber private:
76fef3036dSMartin Elshuber /// Function this pass is working on
77fef3036dSMartin Elshuber Function &F;
78fef3036dSMartin Elshuber
79fef3036dSMartin Elshuber /// Dominator Tree Analysis
80fef3036dSMartin Elshuber DominatorTree &DT;
81fef3036dSMartin Elshuber
82fef3036dSMartin Elshuber /// Memory Alias Analyses
83fef3036dSMartin Elshuber MemorySSA &MSSA;
84fef3036dSMartin Elshuber
85fef3036dSMartin Elshuber /// Target Lowering Information
86fef3036dSMartin Elshuber const TargetLowering &TLI;
87fef3036dSMartin Elshuber
88fef3036dSMartin Elshuber /// Target Transform Information
89fef3036dSMartin Elshuber const TargetTransformInfo TTI;
90fef3036dSMartin Elshuber
91fef3036dSMartin Elshuber /// Find the instruction in sets LIs that dominates all others, return nullptr
92fef3036dSMartin Elshuber /// if there is none.
93fef3036dSMartin Elshuber LoadInst *findFirstLoad(const std::set<LoadInst *> &LIs);
94fef3036dSMartin Elshuber
95fef3036dSMartin Elshuber /// Replace interleaved load candidates. It does additional
96fef3036dSMartin Elshuber /// analyses if this makes sense. Returns true on success and false
97fef3036dSMartin Elshuber /// of nothing has been changed.
98fef3036dSMartin Elshuber bool combine(std::list<VectorInfo> &InterleavedLoad,
99fef3036dSMartin Elshuber OptimizationRemarkEmitter &ORE);
100fef3036dSMartin Elshuber
101fef3036dSMartin Elshuber /// Given a set of VectorInfo containing candidates for a given interleave
102fef3036dSMartin Elshuber /// factor, find a set that represents a 'factor' interleaved load.
103fef3036dSMartin Elshuber bool findPattern(std::list<VectorInfo> &Candidates,
104fef3036dSMartin Elshuber std::list<VectorInfo> &InterleavedLoad, unsigned Factor,
105fef3036dSMartin Elshuber const DataLayout &DL);
106fef3036dSMartin Elshuber }; // InterleavedLoadCombine
107fef3036dSMartin Elshuber
108fef3036dSMartin Elshuber /// First Order Polynomial on an n-Bit Integer Value
109fef3036dSMartin Elshuber ///
110fef3036dSMartin Elshuber /// Polynomial(Value) = Value * B + A + E*2^(n-e)
111fef3036dSMartin Elshuber ///
112fef3036dSMartin Elshuber /// A and B are the coefficients. E*2^(n-e) is an error within 'e' most
113fef3036dSMartin Elshuber /// significant bits. It is introduced if an exact computation cannot be proven
114fef3036dSMartin Elshuber /// (e.q. division by 2).
115fef3036dSMartin Elshuber ///
116fef3036dSMartin Elshuber /// As part of this optimization multiple loads will be combined. It necessary
117fef3036dSMartin Elshuber /// to prove that loads are within some relative offset to each other. This
118fef3036dSMartin Elshuber /// class is used to prove relative offsets of values loaded from memory.
119fef3036dSMartin Elshuber ///
120fef3036dSMartin Elshuber /// Representing an integer in this form is sound since addition in two's
121fef3036dSMartin Elshuber /// complement is associative (trivial) and multiplication distributes over the
122fef3036dSMartin Elshuber /// addition (see Proof(1) in Polynomial::mul). Further, both operations
123fef3036dSMartin Elshuber /// commute.
124fef3036dSMartin Elshuber //
125fef3036dSMartin Elshuber // Example:
126fef3036dSMartin Elshuber // declare @fn(i64 %IDX, <4 x float>* %PTR) {
127fef3036dSMartin Elshuber // %Pa1 = add i64 %IDX, 2
128fef3036dSMartin Elshuber // %Pa2 = lshr i64 %Pa1, 1
129fef3036dSMartin Elshuber // %Pa3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pa2
130fef3036dSMartin Elshuber // %Va = load <4 x float>, <4 x float>* %Pa3
131fef3036dSMartin Elshuber //
132fef3036dSMartin Elshuber // %Pb1 = add i64 %IDX, 4
133fef3036dSMartin Elshuber // %Pb2 = lshr i64 %Pb1, 1
134fef3036dSMartin Elshuber // %Pb3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pb2
135fef3036dSMartin Elshuber // %Vb = load <4 x float>, <4 x float>* %Pb3
136fef3036dSMartin Elshuber // ... }
137fef3036dSMartin Elshuber //
138fef3036dSMartin Elshuber // The goal is to prove that two loads load consecutive addresses.
139fef3036dSMartin Elshuber //
140fef3036dSMartin Elshuber // In this case the polynomials are constructed by the following
141fef3036dSMartin Elshuber // steps.
142fef3036dSMartin Elshuber //
143fef3036dSMartin Elshuber // The number tag #e specifies the error bits.
144fef3036dSMartin Elshuber //
145fef3036dSMartin Elshuber // Pa_0 = %IDX #0
146fef3036dSMartin Elshuber // Pa_1 = %IDX + 2 #0 | add 2
147fef3036dSMartin Elshuber // Pa_2 = %IDX/2 + 1 #1 | lshr 1
148fef3036dSMartin Elshuber // Pa_3 = %IDX/2 + 1 #1 | GEP, step signext to i64
149fef3036dSMartin Elshuber // Pa_4 = (%IDX/2)*16 + 16 #0 | GEP, multiply index by sizeof(4) for floats
150fef3036dSMartin Elshuber // Pa_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
151fef3036dSMartin Elshuber //
152fef3036dSMartin Elshuber // Pb_0 = %IDX #0
153fef3036dSMartin Elshuber // Pb_1 = %IDX + 4 #0 | add 2
154fef3036dSMartin Elshuber // Pb_2 = %IDX/2 + 2 #1 | lshr 1
155fef3036dSMartin Elshuber // Pb_3 = %IDX/2 + 2 #1 | GEP, step signext to i64
156fef3036dSMartin Elshuber // Pb_4 = (%IDX/2)*16 + 32 #0 | GEP, multiply index by sizeof(4) for floats
157fef3036dSMartin Elshuber // Pb_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
158fef3036dSMartin Elshuber //
159fef3036dSMartin Elshuber // Pb_5 - Pa_5 = 16 #0 | subtract to get the offset
160fef3036dSMartin Elshuber //
161fef3036dSMartin Elshuber // Remark: %PTR is not maintained within this class. So in this instance the
162fef3036dSMartin Elshuber // offset of 16 can only be assumed if the pointers are equal.
163fef3036dSMartin Elshuber //
164fef3036dSMartin Elshuber class Polynomial {
165fef3036dSMartin Elshuber /// Operations on B
166fef3036dSMartin Elshuber enum BOps {
167fef3036dSMartin Elshuber LShr,
168fef3036dSMartin Elshuber Mul,
169fef3036dSMartin Elshuber SExt,
170fef3036dSMartin Elshuber Trunc,
171fef3036dSMartin Elshuber };
172fef3036dSMartin Elshuber
173fef3036dSMartin Elshuber /// Number of Error Bits e
1743cbe0bc4SKazu Hirata unsigned ErrorMSBs = (unsigned)-1;
175fef3036dSMartin Elshuber
176fef3036dSMartin Elshuber /// Value
1773cbe0bc4SKazu Hirata Value *V = nullptr;
178fef3036dSMartin Elshuber
179fef3036dSMartin Elshuber /// Coefficient B
180fef3036dSMartin Elshuber SmallVector<std::pair<BOps, APInt>, 4> B;
181fef3036dSMartin Elshuber
182fef3036dSMartin Elshuber /// Coefficient A
183fef3036dSMartin Elshuber APInt A;
184fef3036dSMartin Elshuber
185fef3036dSMartin Elshuber public:
Polynomial(Value * V)1863cbe0bc4SKazu Hirata Polynomial(Value *V) : V(V) {
187fef3036dSMartin Elshuber IntegerType *Ty = dyn_cast<IntegerType>(V->getType());
188fef3036dSMartin Elshuber if (Ty) {
189fef3036dSMartin Elshuber ErrorMSBs = 0;
190fef3036dSMartin Elshuber this->V = V;
191fef3036dSMartin Elshuber A = APInt(Ty->getBitWidth(), 0);
192fef3036dSMartin Elshuber }
193fef3036dSMartin Elshuber }
194fef3036dSMartin Elshuber
Polynomial(const APInt & A,unsigned ErrorMSBs=0)195fef3036dSMartin Elshuber Polynomial(const APInt &A, unsigned ErrorMSBs = 0)
1963cbe0bc4SKazu Hirata : ErrorMSBs(ErrorMSBs), A(A) {}
197fef3036dSMartin Elshuber
Polynomial(unsigned BitWidth,uint64_t A,unsigned ErrorMSBs=0)198fef3036dSMartin Elshuber Polynomial(unsigned BitWidth, uint64_t A, unsigned ErrorMSBs = 0)
1993cbe0bc4SKazu Hirata : ErrorMSBs(ErrorMSBs), A(BitWidth, A) {}
200fef3036dSMartin Elshuber
2013cbe0bc4SKazu Hirata Polynomial() = default;
202fef3036dSMartin Elshuber
203fef3036dSMartin Elshuber /// Increment and clamp the number of undefined bits.
incErrorMSBs(unsigned amt)204fef3036dSMartin Elshuber void incErrorMSBs(unsigned amt) {
205fef3036dSMartin Elshuber if (ErrorMSBs == (unsigned)-1)
206fef3036dSMartin Elshuber return;
207fef3036dSMartin Elshuber
208fef3036dSMartin Elshuber ErrorMSBs += amt;
209fef3036dSMartin Elshuber if (ErrorMSBs > A.getBitWidth())
210fef3036dSMartin Elshuber ErrorMSBs = A.getBitWidth();
211fef3036dSMartin Elshuber }
212fef3036dSMartin Elshuber
213fef3036dSMartin Elshuber /// Decrement and clamp the number of undefined bits.
decErrorMSBs(unsigned amt)214fef3036dSMartin Elshuber void decErrorMSBs(unsigned amt) {
215fef3036dSMartin Elshuber if (ErrorMSBs == (unsigned)-1)
216fef3036dSMartin Elshuber return;
217fef3036dSMartin Elshuber
218fef3036dSMartin Elshuber if (ErrorMSBs > amt)
219fef3036dSMartin Elshuber ErrorMSBs -= amt;
220fef3036dSMartin Elshuber else
221fef3036dSMartin Elshuber ErrorMSBs = 0;
222fef3036dSMartin Elshuber }
223fef3036dSMartin Elshuber
224fef3036dSMartin Elshuber /// Apply an add on the polynomial
add(const APInt & C)225fef3036dSMartin Elshuber Polynomial &add(const APInt &C) {
226fef3036dSMartin Elshuber // Note: Addition is associative in two's complement even when in case of
227fef3036dSMartin Elshuber // signed overflow.
228fef3036dSMartin Elshuber //
229fef3036dSMartin Elshuber // Error bits can only propagate into higher significant bits. As these are
230fef3036dSMartin Elshuber // already regarded as undefined, there is no change.
231fef3036dSMartin Elshuber //
232fef3036dSMartin Elshuber // Theorem: Adding a constant to a polynomial does not change the error
233fef3036dSMartin Elshuber // term.
234fef3036dSMartin Elshuber //
235fef3036dSMartin Elshuber // Proof:
236fef3036dSMartin Elshuber //
237fef3036dSMartin Elshuber // Since the addition is associative and commutes:
238fef3036dSMartin Elshuber //
239fef3036dSMartin Elshuber // (B + A + E*2^(n-e)) + C = B + (A + C) + E*2^(n-e)
240fef3036dSMartin Elshuber // [qed]
241fef3036dSMartin Elshuber
242fef3036dSMartin Elshuber if (C.getBitWidth() != A.getBitWidth()) {
243fef3036dSMartin Elshuber ErrorMSBs = (unsigned)-1;
244fef3036dSMartin Elshuber return *this;
245fef3036dSMartin Elshuber }
246fef3036dSMartin Elshuber
247fef3036dSMartin Elshuber A += C;
248fef3036dSMartin Elshuber return *this;
249fef3036dSMartin Elshuber }
250fef3036dSMartin Elshuber
251fef3036dSMartin Elshuber /// Apply a multiplication onto the polynomial.
mul(const APInt & C)252fef3036dSMartin Elshuber Polynomial &mul(const APInt &C) {
253fef3036dSMartin Elshuber // Note: Multiplication distributes over the addition
254fef3036dSMartin Elshuber //
255fef3036dSMartin Elshuber // Theorem: Multiplication distributes over the addition
256fef3036dSMartin Elshuber //
257fef3036dSMartin Elshuber // Proof(1):
258fef3036dSMartin Elshuber //
259fef3036dSMartin Elshuber // (B+A)*C =-
260fef3036dSMartin Elshuber // = (B + A) + (B + A) + .. {C Times}
261fef3036dSMartin Elshuber // addition is associative and commutes, hence
262fef3036dSMartin Elshuber // = B + B + .. {C Times} .. + A + A + .. {C times}
263fef3036dSMartin Elshuber // = B*C + A*C
264fef3036dSMartin Elshuber // (see (function add) for signed values and overflows)
265fef3036dSMartin Elshuber // [qed]
266fef3036dSMartin Elshuber //
267fef3036dSMartin Elshuber // Theorem: If C has c trailing zeros, errors bits in A or B are shifted out
268fef3036dSMartin Elshuber // to the left.
269fef3036dSMartin Elshuber //
270fef3036dSMartin Elshuber // Proof(2):
271fef3036dSMartin Elshuber //
272fef3036dSMartin Elshuber // Let B' and A' be the n-Bit inputs with some unknown errors EA,
273fef3036dSMartin Elshuber // EB at e leading bits. B' and A' can be written down as:
274fef3036dSMartin Elshuber //
275fef3036dSMartin Elshuber // B' = B + 2^(n-e)*EB
276fef3036dSMartin Elshuber // A' = A + 2^(n-e)*EA
277fef3036dSMartin Elshuber //
278fef3036dSMartin Elshuber // Let C' be an input with c trailing zero bits. C' can be written as
279fef3036dSMartin Elshuber //
280fef3036dSMartin Elshuber // C' = C*2^c
281fef3036dSMartin Elshuber //
282fef3036dSMartin Elshuber // Therefore we can compute the result by using distributivity and
283fef3036dSMartin Elshuber // commutativity.
284fef3036dSMartin Elshuber //
285fef3036dSMartin Elshuber // (B'*C' + A'*C') = [B + 2^(n-e)*EB] * C' + [A + 2^(n-e)*EA] * C' =
286fef3036dSMartin Elshuber // = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
287fef3036dSMartin Elshuber // = (B'+A') * C' =
288fef3036dSMartin Elshuber // = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
289fef3036dSMartin Elshuber // = [B + A + 2^(n-e)*EB + 2^(n-e)*EA] * C' =
290fef3036dSMartin Elshuber // = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C' =
291fef3036dSMartin Elshuber // = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C*2^c =
292fef3036dSMartin Elshuber // = (B + A) * C' + C*(EB + EA)*2^(n-e)*2^c =
293fef3036dSMartin Elshuber //
294fef3036dSMartin Elshuber // Let EC be the final error with EC = C*(EB + EA)
295fef3036dSMartin Elshuber //
296fef3036dSMartin Elshuber // = (B + A)*C' + EC*2^(n-e)*2^c =
297fef3036dSMartin Elshuber // = (B + A)*C' + EC*2^(n-(e-c))
298fef3036dSMartin Elshuber //
299fef3036dSMartin Elshuber // Since EC is multiplied by 2^(n-(e-c)) the resulting error contains c
300fef3036dSMartin Elshuber // less error bits than the input. c bits are shifted out to the left.
301fef3036dSMartin Elshuber // [qed]
302fef3036dSMartin Elshuber
303fef3036dSMartin Elshuber if (C.getBitWidth() != A.getBitWidth()) {
304fef3036dSMartin Elshuber ErrorMSBs = (unsigned)-1;
305fef3036dSMartin Elshuber return *this;
306fef3036dSMartin Elshuber }
307fef3036dSMartin Elshuber
308fef3036dSMartin Elshuber // Multiplying by one is a no-op.
309a9bceb2bSJay Foad if (C.isOne()) {
310fef3036dSMartin Elshuber return *this;
311fef3036dSMartin Elshuber }
312fef3036dSMartin Elshuber
313fef3036dSMartin Elshuber // Multiplying by zero removes the coefficient B and defines all bits.
314735f4671SChris Lattner if (C.isZero()) {
315fef3036dSMartin Elshuber ErrorMSBs = 0;
316fef3036dSMartin Elshuber deleteB();
317fef3036dSMartin Elshuber }
318fef3036dSMartin Elshuber
319fef3036dSMartin Elshuber // See Proof(2): Trailing zero bits indicate a left shift. This removes
320fef3036dSMartin Elshuber // leading bits from the result even if they are undefined.
321fef3036dSMartin Elshuber decErrorMSBs(C.countTrailingZeros());
322fef3036dSMartin Elshuber
323fef3036dSMartin Elshuber A *= C;
324fef3036dSMartin Elshuber pushBOperation(Mul, C);
325fef3036dSMartin Elshuber return *this;
326fef3036dSMartin Elshuber }
327fef3036dSMartin Elshuber
328fef3036dSMartin Elshuber /// Apply a logical shift right on the polynomial
lshr(const APInt & C)329fef3036dSMartin Elshuber Polynomial &lshr(const APInt &C) {
330fef3036dSMartin Elshuber // Theorem(1): (B + A + E*2^(n-e)) >> 1 => (B >> 1) + (A >> 1) + E'*2^(n-e')
331fef3036dSMartin Elshuber // where
332fef3036dSMartin Elshuber // e' = e + 1,
333fef3036dSMartin Elshuber // E is a e-bit number,
334fef3036dSMartin Elshuber // E' is a e'-bit number,
335fef3036dSMartin Elshuber // holds under the following precondition:
336fef3036dSMartin Elshuber // pre(1): A % 2 = 0
337fef3036dSMartin Elshuber // pre(2): e < n, (see Theorem(2) for the trivial case with e=n)
338fef3036dSMartin Elshuber // where >> expresses a logical shift to the right, with adding zeros.
339fef3036dSMartin Elshuber //
340fef3036dSMartin Elshuber // We need to show that for every, E there is a E'
341fef3036dSMartin Elshuber //
342fef3036dSMartin Elshuber // B = b_h * 2^(n-1) + b_m * 2 + b_l
343fef3036dSMartin Elshuber // A = a_h * 2^(n-1) + a_m * 2 (pre(1))
344fef3036dSMartin Elshuber //
345fef3036dSMartin Elshuber // where a_h, b_h, b_l are single bits, and a_m, b_m are (n-2) bit numbers
346fef3036dSMartin Elshuber //
347fef3036dSMartin Elshuber // Let X = (B + A + E*2^(n-e)) >> 1
348fef3036dSMartin Elshuber // Let Y = (B >> 1) + (A >> 1) + E*2^(n-e) >> 1
349fef3036dSMartin Elshuber //
350fef3036dSMartin Elshuber // X = [B + A + E*2^(n-e)] >> 1 =
351fef3036dSMartin Elshuber // = [ b_h * 2^(n-1) + b_m * 2 + b_l +
352fef3036dSMartin Elshuber // + a_h * 2^(n-1) + a_m * 2 +
353fef3036dSMartin Elshuber // + E * 2^(n-e) ] >> 1 =
354fef3036dSMartin Elshuber //
355fef3036dSMartin Elshuber // The sum is built by putting the overflow of [a_m + b+n] into the term
356fef3036dSMartin Elshuber // 2^(n-1). As there are no more bits beyond 2^(n-1) the overflow within
357fef3036dSMartin Elshuber // this bit is discarded. This is expressed by % 2.
358fef3036dSMartin Elshuber //
359fef3036dSMartin Elshuber // The bit in position 0 cannot overflow into the term (b_m + a_m).
360fef3036dSMartin Elshuber //
361fef3036dSMartin Elshuber // = [ ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-1) +
362fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) * 2 +
363fef3036dSMartin Elshuber // + b_l + E * 2^(n-e) ] >> 1 =
364fef3036dSMartin Elshuber //
365fef3036dSMartin Elshuber // The shift is computed by dividing the terms by 2 and by cutting off
366fef3036dSMartin Elshuber // b_l.
367fef3036dSMartin Elshuber //
368fef3036dSMartin Elshuber // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
369fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) +
370fef3036dSMartin Elshuber // + E * 2^(n-(e+1)) =
371fef3036dSMartin Elshuber //
372fef3036dSMartin Elshuber // by the definition in the Theorem e+1 = e'
373fef3036dSMartin Elshuber //
374fef3036dSMartin Elshuber // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
375fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) +
376fef3036dSMartin Elshuber // + E * 2^(n-e') =
377fef3036dSMartin Elshuber //
378fef3036dSMartin Elshuber // Compute Y by applying distributivity first
379fef3036dSMartin Elshuber //
380fef3036dSMartin Elshuber // Y = (B >> 1) + (A >> 1) + E*2^(n-e') =
381fef3036dSMartin Elshuber // = (b_h * 2^(n-1) + b_m * 2 + b_l) >> 1 +
382fef3036dSMartin Elshuber // + (a_h * 2^(n-1) + a_m * 2) >> 1 +
383fef3036dSMartin Elshuber // + E * 2^(n-e) >> 1 =
384fef3036dSMartin Elshuber //
385fef3036dSMartin Elshuber // Again, the shift is computed by dividing the terms by 2 and by cutting
386fef3036dSMartin Elshuber // off b_l.
387fef3036dSMartin Elshuber //
388fef3036dSMartin Elshuber // = b_h * 2^(n-2) + b_m +
389fef3036dSMartin Elshuber // + a_h * 2^(n-2) + a_m +
390fef3036dSMartin Elshuber // + E * 2^(n-(e+1)) =
391fef3036dSMartin Elshuber //
392fef3036dSMartin Elshuber // Again, the sum is built by putting the overflow of [a_m + b+n] into
393fef3036dSMartin Elshuber // the term 2^(n-1). But this time there is room for a second bit in the
394fef3036dSMartin Elshuber // term 2^(n-2) we add this bit to a new term and denote it o_h in a
395fef3036dSMartin Elshuber // second step.
396fef3036dSMartin Elshuber //
397fef3036dSMartin Elshuber // = ([b_h + a_h + (b_m + a_m) >> (n-2)] >> 1) * 2^(n-1) +
398fef3036dSMartin Elshuber // + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
399fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) +
400fef3036dSMartin Elshuber // + E * 2^(n-(e+1)) =
401fef3036dSMartin Elshuber //
402fef3036dSMartin Elshuber // Let o_h = [b_h + a_h + (b_m + a_m) >> (n-2)] >> 1
403fef3036dSMartin Elshuber // Further replace e+1 by e'.
404fef3036dSMartin Elshuber //
405fef3036dSMartin Elshuber // = o_h * 2^(n-1) +
406fef3036dSMartin Elshuber // + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
407fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) +
408fef3036dSMartin Elshuber // + E * 2^(n-e') =
409fef3036dSMartin Elshuber //
410fef3036dSMartin Elshuber // Move o_h into the error term and construct E'. To ensure that there is
411fef3036dSMartin Elshuber // no 2^x with negative x, this step requires pre(2) (e < n).
412fef3036dSMartin Elshuber //
413fef3036dSMartin Elshuber // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
414fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) +
415fef3036dSMartin Elshuber // + o_h * 2^(e'-1) * 2^(n-e') + | pre(2), move 2^(e'-1)
416fef3036dSMartin Elshuber // | out of the old exponent
417fef3036dSMartin Elshuber // + E * 2^(n-e') =
418fef3036dSMartin Elshuber // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
419fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) +
420fef3036dSMartin Elshuber // + [o_h * 2^(e'-1) + E] * 2^(n-e') + | move 2^(e'-1) out of
421fef3036dSMartin Elshuber // | the old exponent
422fef3036dSMartin Elshuber //
423fef3036dSMartin Elshuber // Let E' = o_h * 2^(e'-1) + E
424fef3036dSMartin Elshuber //
425fef3036dSMartin Elshuber // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
426fef3036dSMartin Elshuber // + ((b_m + a_m) % 2^(n-2)) +
427fef3036dSMartin Elshuber // + E' * 2^(n-e')
428fef3036dSMartin Elshuber //
429fef3036dSMartin Elshuber // Because X and Y are distinct only in there error terms and E' can be
430fef3036dSMartin Elshuber // constructed as shown the theorem holds.
431fef3036dSMartin Elshuber // [qed]
432fef3036dSMartin Elshuber //
433fef3036dSMartin Elshuber // For completeness in case of the case e=n it is also required to show that
434fef3036dSMartin Elshuber // distributivity can be applied.
435fef3036dSMartin Elshuber //
436fef3036dSMartin Elshuber // In this case Theorem(1) transforms to (the pre-condition on A can also be
437fef3036dSMartin Elshuber // dropped)
438fef3036dSMartin Elshuber //
439fef3036dSMartin Elshuber // Theorem(2): (B + A + E) >> 1 => (B >> 1) + (A >> 1) + E'
440fef3036dSMartin Elshuber // where
441fef3036dSMartin Elshuber // A, B, E, E' are two's complement numbers with the same bit
442fef3036dSMartin Elshuber // width
443fef3036dSMartin Elshuber //
444fef3036dSMartin Elshuber // Let A + B + E = X
445fef3036dSMartin Elshuber // Let (B >> 1) + (A >> 1) = Y
446fef3036dSMartin Elshuber //
447fef3036dSMartin Elshuber // Therefore we need to show that for every X and Y there is an E' which
448fef3036dSMartin Elshuber // makes the equation
449fef3036dSMartin Elshuber //
450fef3036dSMartin Elshuber // X = Y + E'
451fef3036dSMartin Elshuber //
452fef3036dSMartin Elshuber // hold. This is trivially the case for E' = X - Y.
453fef3036dSMartin Elshuber //
454fef3036dSMartin Elshuber // [qed]
455fef3036dSMartin Elshuber //
456fef3036dSMartin Elshuber // Remark: Distributing lshr with and arbitrary number n can be expressed as
457fef3036dSMartin Elshuber // ((((B + A) lshr 1) lshr 1) ... ) {n times}.
458fef3036dSMartin Elshuber // This construction induces n additional error bits at the left.
459fef3036dSMartin Elshuber
460fef3036dSMartin Elshuber if (C.getBitWidth() != A.getBitWidth()) {
461fef3036dSMartin Elshuber ErrorMSBs = (unsigned)-1;
462fef3036dSMartin Elshuber return *this;
463fef3036dSMartin Elshuber }
464fef3036dSMartin Elshuber
465735f4671SChris Lattner if (C.isZero())
466fef3036dSMartin Elshuber return *this;
467fef3036dSMartin Elshuber
468fef3036dSMartin Elshuber // Test if the result will be zero
469fef3036dSMartin Elshuber unsigned shiftAmt = C.getZExtValue();
470fef3036dSMartin Elshuber if (shiftAmt >= C.getBitWidth())
471fef3036dSMartin Elshuber return mul(APInt(C.getBitWidth(), 0));
472fef3036dSMartin Elshuber
473fef3036dSMartin Elshuber // The proof that shiftAmt LSBs are zero for at least one summand is only
474fef3036dSMartin Elshuber // possible for the constant number.
475fef3036dSMartin Elshuber //
476fef3036dSMartin Elshuber // If this can be proven add shiftAmt to the error counter
477fef3036dSMartin Elshuber // `ErrorMSBs`. Otherwise set all bits as undefined.
478fef3036dSMartin Elshuber if (A.countTrailingZeros() < shiftAmt)
479fef3036dSMartin Elshuber ErrorMSBs = A.getBitWidth();
480fef3036dSMartin Elshuber else
481fef3036dSMartin Elshuber incErrorMSBs(shiftAmt);
482fef3036dSMartin Elshuber
483fef3036dSMartin Elshuber // Apply the operation.
484fef3036dSMartin Elshuber pushBOperation(LShr, C);
485fef3036dSMartin Elshuber A = A.lshr(shiftAmt);
486fef3036dSMartin Elshuber
487fef3036dSMartin Elshuber return *this;
488fef3036dSMartin Elshuber }
489fef3036dSMartin Elshuber
490fef3036dSMartin Elshuber /// Apply a sign-extend or truncate operation on the polynomial.
sextOrTrunc(unsigned n)491fef3036dSMartin Elshuber Polynomial &sextOrTrunc(unsigned n) {
492fef3036dSMartin Elshuber if (n < A.getBitWidth()) {
493fef3036dSMartin Elshuber // Truncate: Clearly undefined Bits on the MSB side are removed
494fef3036dSMartin Elshuber // if there are any.
495fef3036dSMartin Elshuber decErrorMSBs(A.getBitWidth() - n);
496fef3036dSMartin Elshuber A = A.trunc(n);
497fef3036dSMartin Elshuber pushBOperation(Trunc, APInt(sizeof(n) * 8, n));
498fef3036dSMartin Elshuber }
499fef3036dSMartin Elshuber if (n > A.getBitWidth()) {
500fef3036dSMartin Elshuber // Extend: Clearly extending first and adding later is different
501fef3036dSMartin Elshuber // to adding first and extending later in all extended bits.
502fef3036dSMartin Elshuber incErrorMSBs(n - A.getBitWidth());
503fef3036dSMartin Elshuber A = A.sext(n);
504fef3036dSMartin Elshuber pushBOperation(SExt, APInt(sizeof(n) * 8, n));
505fef3036dSMartin Elshuber }
506fef3036dSMartin Elshuber
507fef3036dSMartin Elshuber return *this;
508fef3036dSMartin Elshuber }
509fef3036dSMartin Elshuber
510fef3036dSMartin Elshuber /// Test if there is a coefficient B.
isFirstOrder() const511fef3036dSMartin Elshuber bool isFirstOrder() const { return V != nullptr; }
512fef3036dSMartin Elshuber
513fef3036dSMartin Elshuber /// Test coefficient B of two Polynomials are equal.
isCompatibleTo(const Polynomial & o) const514fef3036dSMartin Elshuber bool isCompatibleTo(const Polynomial &o) const {
515fef3036dSMartin Elshuber // The polynomial use different bit width.
516fef3036dSMartin Elshuber if (A.getBitWidth() != o.A.getBitWidth())
517fef3036dSMartin Elshuber return false;
518fef3036dSMartin Elshuber
519fef3036dSMartin Elshuber // If neither Polynomial has the Coefficient B.
520fef3036dSMartin Elshuber if (!isFirstOrder() && !o.isFirstOrder())
521fef3036dSMartin Elshuber return true;
522fef3036dSMartin Elshuber
523fef3036dSMartin Elshuber // The index variable is different.
524fef3036dSMartin Elshuber if (V != o.V)
525fef3036dSMartin Elshuber return false;
526fef3036dSMartin Elshuber
527fef3036dSMartin Elshuber // Check the operations.
528fef3036dSMartin Elshuber if (B.size() != o.B.size())
529fef3036dSMartin Elshuber return false;
530fef3036dSMartin Elshuber
531*9e6d1f4bSKazu Hirata auto *ob = o.B.begin();
532*9e6d1f4bSKazu Hirata for (const auto &b : B) {
533fef3036dSMartin Elshuber if (b != *ob)
534fef3036dSMartin Elshuber return false;
535fef3036dSMartin Elshuber ob++;
536fef3036dSMartin Elshuber }
537fef3036dSMartin Elshuber
538fef3036dSMartin Elshuber return true;
539fef3036dSMartin Elshuber }
540fef3036dSMartin Elshuber
541fef3036dSMartin Elshuber /// Subtract two polynomials, return an undefined polynomial if
542fef3036dSMartin Elshuber /// subtraction is not possible.
operator -(const Polynomial & o) const543fef3036dSMartin Elshuber Polynomial operator-(const Polynomial &o) const {
544fef3036dSMartin Elshuber // Return an undefined polynomial if incompatible.
545fef3036dSMartin Elshuber if (!isCompatibleTo(o))
546fef3036dSMartin Elshuber return Polynomial();
547fef3036dSMartin Elshuber
548fef3036dSMartin Elshuber // If the polynomials are compatible (meaning they have the same
549fef3036dSMartin Elshuber // coefficient on B), B is eliminated. Thus a polynomial solely
550fef3036dSMartin Elshuber // containing A is returned
551fef3036dSMartin Elshuber return Polynomial(A - o.A, std::max(ErrorMSBs, o.ErrorMSBs));
552fef3036dSMartin Elshuber }
553fef3036dSMartin Elshuber
554fef3036dSMartin Elshuber /// Subtract a constant from a polynomial,
operator -(uint64_t C) const555fef3036dSMartin Elshuber Polynomial operator-(uint64_t C) const {
556fef3036dSMartin Elshuber Polynomial Result(*this);
557fef3036dSMartin Elshuber Result.A -= C;
558fef3036dSMartin Elshuber return Result;
559fef3036dSMartin Elshuber }
560fef3036dSMartin Elshuber
561fef3036dSMartin Elshuber /// Add a constant to a polynomial,
operator +(uint64_t C) const562fef3036dSMartin Elshuber Polynomial operator+(uint64_t C) const {
563fef3036dSMartin Elshuber Polynomial Result(*this);
564fef3036dSMartin Elshuber Result.A += C;
565fef3036dSMartin Elshuber return Result;
566fef3036dSMartin Elshuber }
567fef3036dSMartin Elshuber
568fef3036dSMartin Elshuber /// Returns true if it can be proven that two Polynomials are equal.
isProvenEqualTo(const Polynomial & o)569fef3036dSMartin Elshuber bool isProvenEqualTo(const Polynomial &o) {
570fef3036dSMartin Elshuber // Subtract both polynomials and test if it is fully defined and zero.
571fef3036dSMartin Elshuber Polynomial r = *this - o;
572735f4671SChris Lattner return (r.ErrorMSBs == 0) && (!r.isFirstOrder()) && (r.A.isZero());
573fef3036dSMartin Elshuber }
574fef3036dSMartin Elshuber
575fef3036dSMartin Elshuber /// Print the polynomial into a stream.
print(raw_ostream & OS) const576fef3036dSMartin Elshuber void print(raw_ostream &OS) const {
577fef3036dSMartin Elshuber OS << "[{#ErrBits:" << ErrorMSBs << "} ";
578fef3036dSMartin Elshuber
579fef3036dSMartin Elshuber if (V) {
580fef3036dSMartin Elshuber for (auto b : B)
581fef3036dSMartin Elshuber OS << "(";
582fef3036dSMartin Elshuber OS << "(" << *V << ") ";
583fef3036dSMartin Elshuber
584fef3036dSMartin Elshuber for (auto b : B) {
585fef3036dSMartin Elshuber switch (b.first) {
586fef3036dSMartin Elshuber case LShr:
587fef3036dSMartin Elshuber OS << "LShr ";
588fef3036dSMartin Elshuber break;
589fef3036dSMartin Elshuber case Mul:
590fef3036dSMartin Elshuber OS << "Mul ";
591fef3036dSMartin Elshuber break;
592fef3036dSMartin Elshuber case SExt:
593fef3036dSMartin Elshuber OS << "SExt ";
594fef3036dSMartin Elshuber break;
595fef3036dSMartin Elshuber case Trunc:
596fef3036dSMartin Elshuber OS << "Trunc ";
597fef3036dSMartin Elshuber break;
598fef3036dSMartin Elshuber }
599fef3036dSMartin Elshuber
600fef3036dSMartin Elshuber OS << b.second << ") ";
601fef3036dSMartin Elshuber }
602fef3036dSMartin Elshuber }
603fef3036dSMartin Elshuber
604fef3036dSMartin Elshuber OS << "+ " << A << "]";
605fef3036dSMartin Elshuber }
606fef3036dSMartin Elshuber
607fef3036dSMartin Elshuber private:
deleteB()608fef3036dSMartin Elshuber void deleteB() {
609fef3036dSMartin Elshuber V = nullptr;
610fef3036dSMartin Elshuber B.clear();
611fef3036dSMartin Elshuber }
612fef3036dSMartin Elshuber
pushBOperation(const BOps Op,const APInt & C)613fef3036dSMartin Elshuber void pushBOperation(const BOps Op, const APInt &C) {
614fef3036dSMartin Elshuber if (isFirstOrder()) {
615fef3036dSMartin Elshuber B.push_back(std::make_pair(Op, C));
616fef3036dSMartin Elshuber return;
617fef3036dSMartin Elshuber }
618fef3036dSMartin Elshuber }
619fef3036dSMartin Elshuber };
620fef3036dSMartin Elshuber
6219ad5717fSSimon Pilgrim #ifndef NDEBUG
operator <<(raw_ostream & OS,const Polynomial & S)6229ad5717fSSimon Pilgrim static raw_ostream &operator<<(raw_ostream &OS, const Polynomial &S) {
6239ad5717fSSimon Pilgrim S.print(OS);
6249ad5717fSSimon Pilgrim return OS;
6259ad5717fSSimon Pilgrim }
6269ad5717fSSimon Pilgrim #endif
6279ad5717fSSimon Pilgrim
628fef3036dSMartin Elshuber /// VectorInfo stores abstract the following information for each vector
629fef3036dSMartin Elshuber /// element:
630fef3036dSMartin Elshuber ///
631fef3036dSMartin Elshuber /// 1) The the memory address loaded into the element as Polynomial
632fef3036dSMartin Elshuber /// 2) a set of load instruction necessary to construct the vector,
633fef3036dSMartin Elshuber /// 3) a set of all other instructions that are necessary to create the vector and
634fef3036dSMartin Elshuber /// 4) a pointer value that can be used as relative base for all elements.
635fef3036dSMartin Elshuber struct VectorInfo {
636fef3036dSMartin Elshuber private:
VectorInfo__anon07e87e4b0111::VectorInfo637fef3036dSMartin Elshuber VectorInfo(const VectorInfo &c) : VTy(c.VTy) {
638fef3036dSMartin Elshuber llvm_unreachable(
639fef3036dSMartin Elshuber "Copying VectorInfo is neither implemented nor necessary,");
640fef3036dSMartin Elshuber }
641fef3036dSMartin Elshuber
642fef3036dSMartin Elshuber public:
643fef3036dSMartin Elshuber /// Information of a Vector Element
644fef3036dSMartin Elshuber struct ElementInfo {
645fef3036dSMartin Elshuber /// Offset Polynomial.
646fef3036dSMartin Elshuber Polynomial Ofs;
647fef3036dSMartin Elshuber
648fef3036dSMartin Elshuber /// The Load Instruction used to Load the entry. LI is null if the pointer
649fef3036dSMartin Elshuber /// of the load instruction does not point on to the entry
650fef3036dSMartin Elshuber LoadInst *LI;
651fef3036dSMartin Elshuber
ElementInfo__anon07e87e4b0111::VectorInfo::ElementInfo652fef3036dSMartin Elshuber ElementInfo(Polynomial Offset = Polynomial(), LoadInst *LI = nullptr)
653fef3036dSMartin Elshuber : Ofs(Offset), LI(LI) {}
654fef3036dSMartin Elshuber };
655fef3036dSMartin Elshuber
656fef3036dSMartin Elshuber /// Basic-block the load instructions are within
6572bea207dSKazu Hirata BasicBlock *BB = nullptr;
658fef3036dSMartin Elshuber
659fef3036dSMartin Elshuber /// Pointer value of all participation load instructions
6602bea207dSKazu Hirata Value *PV = nullptr;
661fef3036dSMartin Elshuber
662fef3036dSMartin Elshuber /// Participating load instructions
663fef3036dSMartin Elshuber std::set<LoadInst *> LIs;
664fef3036dSMartin Elshuber
665fef3036dSMartin Elshuber /// Participating instructions
666fef3036dSMartin Elshuber std::set<Instruction *> Is;
667fef3036dSMartin Elshuber
668fef3036dSMartin Elshuber /// Final shuffle-vector instruction
6692bea207dSKazu Hirata ShuffleVectorInst *SVI = nullptr;
670fef3036dSMartin Elshuber
671fef3036dSMartin Elshuber /// Information of the offset for each vector element
672fef3036dSMartin Elshuber ElementInfo *EI;
673fef3036dSMartin Elshuber
674fef3036dSMartin Elshuber /// Vector Type
675364c5954SDavid Sherwood FixedVectorType *const VTy;
676fef3036dSMartin Elshuber
VectorInfo__anon07e87e4b0111::VectorInfo6772bea207dSKazu Hirata VectorInfo(FixedVectorType *VTy) : VTy(VTy) {
678fef3036dSMartin Elshuber EI = new ElementInfo[VTy->getNumElements()];
679fef3036dSMartin Elshuber }
680fef3036dSMartin Elshuber
~VectorInfo__anon07e87e4b0111::VectorInfo681fef3036dSMartin Elshuber virtual ~VectorInfo() { delete[] EI; }
682fef3036dSMartin Elshuber
getDimension__anon07e87e4b0111::VectorInfo683fef3036dSMartin Elshuber unsigned getDimension() const { return VTy->getNumElements(); }
684fef3036dSMartin Elshuber
685fef3036dSMartin Elshuber /// Test if the VectorInfo can be part of an interleaved load with the
686fef3036dSMartin Elshuber /// specified factor.
687fef3036dSMartin Elshuber ///
688fef3036dSMartin Elshuber /// \param Factor of the interleave
689fef3036dSMartin Elshuber /// \param DL Targets Datalayout
690fef3036dSMartin Elshuber ///
691fef3036dSMartin Elshuber /// \returns true if this is possible and false if not
isInterleaved__anon07e87e4b0111::VectorInfo692fef3036dSMartin Elshuber bool isInterleaved(unsigned Factor, const DataLayout &DL) const {
693fef3036dSMartin Elshuber unsigned Size = DL.getTypeAllocSize(VTy->getElementType());
694fef3036dSMartin Elshuber for (unsigned i = 1; i < getDimension(); i++) {
695fef3036dSMartin Elshuber if (!EI[i].Ofs.isProvenEqualTo(EI[0].Ofs + i * Factor * Size)) {
696fef3036dSMartin Elshuber return false;
697fef3036dSMartin Elshuber }
698fef3036dSMartin Elshuber }
699fef3036dSMartin Elshuber return true;
700fef3036dSMartin Elshuber }
701fef3036dSMartin Elshuber
702fef3036dSMartin Elshuber /// Recursively computes the vector information stored in V.
703fef3036dSMartin Elshuber ///
704fef3036dSMartin Elshuber /// This function delegates the work to specialized implementations
705fef3036dSMartin Elshuber ///
706fef3036dSMartin Elshuber /// \param V Value to operate on
707fef3036dSMartin Elshuber /// \param Result Result of the computation
708fef3036dSMartin Elshuber ///
709fef3036dSMartin Elshuber /// \returns false if no sensible information can be gathered.
compute__anon07e87e4b0111::VectorInfo710fef3036dSMartin Elshuber static bool compute(Value *V, VectorInfo &Result, const DataLayout &DL) {
711fef3036dSMartin Elshuber ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
712fef3036dSMartin Elshuber if (SVI)
713fef3036dSMartin Elshuber return computeFromSVI(SVI, Result, DL);
714fef3036dSMartin Elshuber LoadInst *LI = dyn_cast<LoadInst>(V);
715fef3036dSMartin Elshuber if (LI)
716fef3036dSMartin Elshuber return computeFromLI(LI, Result, DL);
717fef3036dSMartin Elshuber BitCastInst *BCI = dyn_cast<BitCastInst>(V);
718fef3036dSMartin Elshuber if (BCI)
719fef3036dSMartin Elshuber return computeFromBCI(BCI, Result, DL);
720fef3036dSMartin Elshuber return false;
721fef3036dSMartin Elshuber }
722fef3036dSMartin Elshuber
723fef3036dSMartin Elshuber /// BitCastInst specialization to compute the vector information.
724fef3036dSMartin Elshuber ///
725fef3036dSMartin Elshuber /// \param BCI BitCastInst to operate on
726fef3036dSMartin Elshuber /// \param Result Result of the computation
727fef3036dSMartin Elshuber ///
728fef3036dSMartin Elshuber /// \returns false if no sensible information can be gathered.
computeFromBCI__anon07e87e4b0111::VectorInfo729fef3036dSMartin Elshuber static bool computeFromBCI(BitCastInst *BCI, VectorInfo &Result,
730fef3036dSMartin Elshuber const DataLayout &DL) {
731fef3036dSMartin Elshuber Instruction *Op = dyn_cast<Instruction>(BCI->getOperand(0));
732fef3036dSMartin Elshuber
733fef3036dSMartin Elshuber if (!Op)
734fef3036dSMartin Elshuber return false;
735fef3036dSMartin Elshuber
736364c5954SDavid Sherwood FixedVectorType *VTy = dyn_cast<FixedVectorType>(Op->getType());
737fef3036dSMartin Elshuber if (!VTy)
738fef3036dSMartin Elshuber return false;
739fef3036dSMartin Elshuber
740fef3036dSMartin Elshuber // We can only cast from large to smaller vectors
741fef3036dSMartin Elshuber if (Result.VTy->getNumElements() % VTy->getNumElements())
742fef3036dSMartin Elshuber return false;
743fef3036dSMartin Elshuber
744fef3036dSMartin Elshuber unsigned Factor = Result.VTy->getNumElements() / VTy->getNumElements();
745fef3036dSMartin Elshuber unsigned NewSize = DL.getTypeAllocSize(Result.VTy->getElementType());
746fef3036dSMartin Elshuber unsigned OldSize = DL.getTypeAllocSize(VTy->getElementType());
747fef3036dSMartin Elshuber
748fef3036dSMartin Elshuber if (NewSize * Factor != OldSize)
749fef3036dSMartin Elshuber return false;
750fef3036dSMartin Elshuber
751fef3036dSMartin Elshuber VectorInfo Old(VTy);
752fef3036dSMartin Elshuber if (!compute(Op, Old, DL))
753fef3036dSMartin Elshuber return false;
754fef3036dSMartin Elshuber
755fef3036dSMartin Elshuber for (unsigned i = 0; i < Result.VTy->getNumElements(); i += Factor) {
756fef3036dSMartin Elshuber for (unsigned j = 0; j < Factor; j++) {
757fef3036dSMartin Elshuber Result.EI[i + j] =
758fef3036dSMartin Elshuber ElementInfo(Old.EI[i / Factor].Ofs + j * NewSize,
759fef3036dSMartin Elshuber j == 0 ? Old.EI[i / Factor].LI : nullptr);
760fef3036dSMartin Elshuber }
761fef3036dSMartin Elshuber }
762fef3036dSMartin Elshuber
763fef3036dSMartin Elshuber Result.BB = Old.BB;
764fef3036dSMartin Elshuber Result.PV = Old.PV;
765fef3036dSMartin Elshuber Result.LIs.insert(Old.LIs.begin(), Old.LIs.end());
766fef3036dSMartin Elshuber Result.Is.insert(Old.Is.begin(), Old.Is.end());
767fef3036dSMartin Elshuber Result.Is.insert(BCI);
768fef3036dSMartin Elshuber Result.SVI = nullptr;
769fef3036dSMartin Elshuber
770fef3036dSMartin Elshuber return true;
771fef3036dSMartin Elshuber }
772fef3036dSMartin Elshuber
773fef3036dSMartin Elshuber /// ShuffleVectorInst specialization to compute vector information.
774fef3036dSMartin Elshuber ///
775fef3036dSMartin Elshuber /// \param SVI ShuffleVectorInst to operate on
776fef3036dSMartin Elshuber /// \param Result Result of the computation
777fef3036dSMartin Elshuber ///
778fef3036dSMartin Elshuber /// Compute the left and the right side vector information and merge them by
779fef3036dSMartin Elshuber /// applying the shuffle operation. This function also ensures that the left
780fef3036dSMartin Elshuber /// and right side have compatible loads. This means that all loads are with
781fef3036dSMartin Elshuber /// in the same basic block and are based on the same pointer.
782fef3036dSMartin Elshuber ///
783fef3036dSMartin Elshuber /// \returns false if no sensible information can be gathered.
computeFromSVI__anon07e87e4b0111::VectorInfo784fef3036dSMartin Elshuber static bool computeFromSVI(ShuffleVectorInst *SVI, VectorInfo &Result,
785fef3036dSMartin Elshuber const DataLayout &DL) {
786364c5954SDavid Sherwood FixedVectorType *ArgTy =
787364c5954SDavid Sherwood cast<FixedVectorType>(SVI->getOperand(0)->getType());
788fef3036dSMartin Elshuber
789fef3036dSMartin Elshuber // Compute the left hand vector information.
790fef3036dSMartin Elshuber VectorInfo LHS(ArgTy);
791fef3036dSMartin Elshuber if (!compute(SVI->getOperand(0), LHS, DL))
792fef3036dSMartin Elshuber LHS.BB = nullptr;
793fef3036dSMartin Elshuber
794fef3036dSMartin Elshuber // Compute the right hand vector information.
795fef3036dSMartin Elshuber VectorInfo RHS(ArgTy);
796fef3036dSMartin Elshuber if (!compute(SVI->getOperand(1), RHS, DL))
797fef3036dSMartin Elshuber RHS.BB = nullptr;
798fef3036dSMartin Elshuber
799fef3036dSMartin Elshuber // Neither operand produced sensible results?
800fef3036dSMartin Elshuber if (!LHS.BB && !RHS.BB)
801fef3036dSMartin Elshuber return false;
802fef3036dSMartin Elshuber // Only RHS produced sensible results?
803fef3036dSMartin Elshuber else if (!LHS.BB) {
804fef3036dSMartin Elshuber Result.BB = RHS.BB;
805fef3036dSMartin Elshuber Result.PV = RHS.PV;
806fef3036dSMartin Elshuber }
807fef3036dSMartin Elshuber // Only LHS produced sensible results?
808fef3036dSMartin Elshuber else if (!RHS.BB) {
809fef3036dSMartin Elshuber Result.BB = LHS.BB;
810fef3036dSMartin Elshuber Result.PV = LHS.PV;
811fef3036dSMartin Elshuber }
812fef3036dSMartin Elshuber // Both operands produced sensible results?
8135a47dc60SMartin Elshuber else if ((LHS.BB == RHS.BB) && (LHS.PV == RHS.PV)) {
814fef3036dSMartin Elshuber Result.BB = LHS.BB;
815fef3036dSMartin Elshuber Result.PV = LHS.PV;
816fef3036dSMartin Elshuber }
817fef3036dSMartin Elshuber // Both operands produced sensible results but they are incompatible.
818fef3036dSMartin Elshuber else {
819fef3036dSMartin Elshuber return false;
820fef3036dSMartin Elshuber }
821fef3036dSMartin Elshuber
822fef3036dSMartin Elshuber // Merge and apply the operation on the offset information.
823fef3036dSMartin Elshuber if (LHS.BB) {
824fef3036dSMartin Elshuber Result.LIs.insert(LHS.LIs.begin(), LHS.LIs.end());
825fef3036dSMartin Elshuber Result.Is.insert(LHS.Is.begin(), LHS.Is.end());
826fef3036dSMartin Elshuber }
827fef3036dSMartin Elshuber if (RHS.BB) {
828fef3036dSMartin Elshuber Result.LIs.insert(RHS.LIs.begin(), RHS.LIs.end());
829fef3036dSMartin Elshuber Result.Is.insert(RHS.Is.begin(), RHS.Is.end());
830fef3036dSMartin Elshuber }
831fef3036dSMartin Elshuber Result.Is.insert(SVI);
832fef3036dSMartin Elshuber Result.SVI = SVI;
833fef3036dSMartin Elshuber
834fef3036dSMartin Elshuber int j = 0;
835fef3036dSMartin Elshuber for (int i : SVI->getShuffleMask()) {
836fef3036dSMartin Elshuber assert((i < 2 * (signed)ArgTy->getNumElements()) &&
837fef3036dSMartin Elshuber "Invalid ShuffleVectorInst (index out of bounds)");
838fef3036dSMartin Elshuber
839fef3036dSMartin Elshuber if (i < 0)
840fef3036dSMartin Elshuber Result.EI[j] = ElementInfo();
841fef3036dSMartin Elshuber else if (i < (signed)ArgTy->getNumElements()) {
842fef3036dSMartin Elshuber if (LHS.BB)
843fef3036dSMartin Elshuber Result.EI[j] = LHS.EI[i];
844fef3036dSMartin Elshuber else
845fef3036dSMartin Elshuber Result.EI[j] = ElementInfo();
846fef3036dSMartin Elshuber } else {
847fef3036dSMartin Elshuber if (RHS.BB)
848fef3036dSMartin Elshuber Result.EI[j] = RHS.EI[i - ArgTy->getNumElements()];
849fef3036dSMartin Elshuber else
850fef3036dSMartin Elshuber Result.EI[j] = ElementInfo();
851fef3036dSMartin Elshuber }
852fef3036dSMartin Elshuber j++;
853fef3036dSMartin Elshuber }
854fef3036dSMartin Elshuber
855fef3036dSMartin Elshuber return true;
856fef3036dSMartin Elshuber }
857fef3036dSMartin Elshuber
858fef3036dSMartin Elshuber /// LoadInst specialization to compute vector information.
859fef3036dSMartin Elshuber ///
860fef3036dSMartin Elshuber /// This function also acts as abort condition to the recursion.
861fef3036dSMartin Elshuber ///
862fef3036dSMartin Elshuber /// \param LI LoadInst to operate on
863fef3036dSMartin Elshuber /// \param Result Result of the computation
864fef3036dSMartin Elshuber ///
865fef3036dSMartin Elshuber /// \returns false if no sensible information can be gathered.
computeFromLI__anon07e87e4b0111::VectorInfo866fef3036dSMartin Elshuber static bool computeFromLI(LoadInst *LI, VectorInfo &Result,
867fef3036dSMartin Elshuber const DataLayout &DL) {
868fef3036dSMartin Elshuber Value *BasePtr;
869fef3036dSMartin Elshuber Polynomial Offset;
870fef3036dSMartin Elshuber
871fef3036dSMartin Elshuber if (LI->isVolatile())
872fef3036dSMartin Elshuber return false;
873fef3036dSMartin Elshuber
874fef3036dSMartin Elshuber if (LI->isAtomic())
875fef3036dSMartin Elshuber return false;
876fef3036dSMartin Elshuber
877fef3036dSMartin Elshuber // Get the base polynomial
878fef3036dSMartin Elshuber computePolynomialFromPointer(*LI->getPointerOperand(), Offset, BasePtr, DL);
879fef3036dSMartin Elshuber
880fef3036dSMartin Elshuber Result.BB = LI->getParent();
881fef3036dSMartin Elshuber Result.PV = BasePtr;
882fef3036dSMartin Elshuber Result.LIs.insert(LI);
883fef3036dSMartin Elshuber Result.Is.insert(LI);
884fef3036dSMartin Elshuber
885fef3036dSMartin Elshuber for (unsigned i = 0; i < Result.getDimension(); i++) {
886fef3036dSMartin Elshuber Value *Idx[2] = {
887fef3036dSMartin Elshuber ConstantInt::get(Type::getInt32Ty(LI->getContext()), 0),
888fef3036dSMartin Elshuber ConstantInt::get(Type::getInt32Ty(LI->getContext()), i),
889fef3036dSMartin Elshuber };
890fef3036dSMartin Elshuber int64_t Ofs = DL.getIndexedOffsetInType(Result.VTy, makeArrayRef(Idx, 2));
891fef3036dSMartin Elshuber Result.EI[i] = ElementInfo(Offset + Ofs, i == 0 ? LI : nullptr);
892fef3036dSMartin Elshuber }
893fef3036dSMartin Elshuber
894fef3036dSMartin Elshuber return true;
895fef3036dSMartin Elshuber }
896fef3036dSMartin Elshuber
897fef3036dSMartin Elshuber /// Recursively compute polynomial of a value.
898fef3036dSMartin Elshuber ///
899fef3036dSMartin Elshuber /// \param BO Input binary operation
900fef3036dSMartin Elshuber /// \param Result Result polynomial
computePolynomialBinOp__anon07e87e4b0111::VectorInfo901fef3036dSMartin Elshuber static void computePolynomialBinOp(BinaryOperator &BO, Polynomial &Result) {
902fef3036dSMartin Elshuber Value *LHS = BO.getOperand(0);
903fef3036dSMartin Elshuber Value *RHS = BO.getOperand(1);
904fef3036dSMartin Elshuber
905fef3036dSMartin Elshuber // Find the RHS Constant if any
906fef3036dSMartin Elshuber ConstantInt *C = dyn_cast<ConstantInt>(RHS);
907fef3036dSMartin Elshuber if ((!C) && BO.isCommutative()) {
908fef3036dSMartin Elshuber C = dyn_cast<ConstantInt>(LHS);
909fef3036dSMartin Elshuber if (C)
910fef3036dSMartin Elshuber std::swap(LHS, RHS);
911fef3036dSMartin Elshuber }
912fef3036dSMartin Elshuber
913fef3036dSMartin Elshuber switch (BO.getOpcode()) {
914fef3036dSMartin Elshuber case Instruction::Add:
915fef3036dSMartin Elshuber if (!C)
916fef3036dSMartin Elshuber break;
917fef3036dSMartin Elshuber
918fef3036dSMartin Elshuber computePolynomial(*LHS, Result);
919fef3036dSMartin Elshuber Result.add(C->getValue());
920fef3036dSMartin Elshuber return;
921fef3036dSMartin Elshuber
922fef3036dSMartin Elshuber case Instruction::LShr:
923fef3036dSMartin Elshuber if (!C)
924fef3036dSMartin Elshuber break;
925fef3036dSMartin Elshuber
926fef3036dSMartin Elshuber computePolynomial(*LHS, Result);
927fef3036dSMartin Elshuber Result.lshr(C->getValue());
928fef3036dSMartin Elshuber return;
929fef3036dSMartin Elshuber
930fef3036dSMartin Elshuber default:
931fef3036dSMartin Elshuber break;
932fef3036dSMartin Elshuber }
933fef3036dSMartin Elshuber
934fef3036dSMartin Elshuber Result = Polynomial(&BO);
935fef3036dSMartin Elshuber }
936fef3036dSMartin Elshuber
937fef3036dSMartin Elshuber /// Recursively compute polynomial of a value
938fef3036dSMartin Elshuber ///
939fef3036dSMartin Elshuber /// \param V input value
940fef3036dSMartin Elshuber /// \param Result result polynomial
computePolynomial__anon07e87e4b0111::VectorInfo941fef3036dSMartin Elshuber static void computePolynomial(Value &V, Polynomial &Result) {
9422b4ace3fSSimon Pilgrim if (auto *BO = dyn_cast<BinaryOperator>(&V))
9432b4ace3fSSimon Pilgrim computePolynomialBinOp(*BO, Result);
944fef3036dSMartin Elshuber else
945fef3036dSMartin Elshuber Result = Polynomial(&V);
946fef3036dSMartin Elshuber }
947fef3036dSMartin Elshuber
948fef3036dSMartin Elshuber /// Compute the Polynomial representation of a Pointer type.
949fef3036dSMartin Elshuber ///
950fef3036dSMartin Elshuber /// \param Ptr input pointer value
951fef3036dSMartin Elshuber /// \param Result result polynomial
952fef3036dSMartin Elshuber /// \param BasePtr pointer the polynomial is based on
953fef3036dSMartin Elshuber /// \param DL Datalayout of the target machine
computePolynomialFromPointer__anon07e87e4b0111::VectorInfo954fef3036dSMartin Elshuber static void computePolynomialFromPointer(Value &Ptr, Polynomial &Result,
955fef3036dSMartin Elshuber Value *&BasePtr,
956fef3036dSMartin Elshuber const DataLayout &DL) {
957fef3036dSMartin Elshuber // Not a pointer type? Return an undefined polynomial
958fef3036dSMartin Elshuber PointerType *PtrTy = dyn_cast<PointerType>(Ptr.getType());
959fef3036dSMartin Elshuber if (!PtrTy) {
960fef3036dSMartin Elshuber Result = Polynomial();
961fef3036dSMartin Elshuber BasePtr = nullptr;
9629b17b80aSSimon Pilgrim return;
963fef3036dSMartin Elshuber }
964fef3036dSMartin Elshuber unsigned PointerBits =
965fef3036dSMartin Elshuber DL.getIndexSizeInBits(PtrTy->getPointerAddressSpace());
966fef3036dSMartin Elshuber
967fef3036dSMartin Elshuber /// Skip pointer casts. Return Zero polynomial otherwise
968fef3036dSMartin Elshuber if (isa<CastInst>(&Ptr)) {
969fef3036dSMartin Elshuber CastInst &CI = *cast<CastInst>(&Ptr);
970fef3036dSMartin Elshuber switch (CI.getOpcode()) {
971fef3036dSMartin Elshuber case Instruction::BitCast:
972fef3036dSMartin Elshuber computePolynomialFromPointer(*CI.getOperand(0), Result, BasePtr, DL);
973fef3036dSMartin Elshuber break;
974fef3036dSMartin Elshuber default:
975fef3036dSMartin Elshuber BasePtr = &Ptr;
976fef3036dSMartin Elshuber Polynomial(PointerBits, 0);
977fef3036dSMartin Elshuber break;
978fef3036dSMartin Elshuber }
979fef3036dSMartin Elshuber }
980fef3036dSMartin Elshuber /// Resolve GetElementPtrInst.
981fef3036dSMartin Elshuber else if (isa<GetElementPtrInst>(&Ptr)) {
982fef3036dSMartin Elshuber GetElementPtrInst &GEP = *cast<GetElementPtrInst>(&Ptr);
983fef3036dSMartin Elshuber
984fef3036dSMartin Elshuber APInt BaseOffset(PointerBits, 0);
985fef3036dSMartin Elshuber
986fef3036dSMartin Elshuber // Check if we can compute the Offset with accumulateConstantOffset
987fef3036dSMartin Elshuber if (GEP.accumulateConstantOffset(DL, BaseOffset)) {
988fef3036dSMartin Elshuber Result = Polynomial(BaseOffset);
989fef3036dSMartin Elshuber BasePtr = GEP.getPointerOperand();
990fef3036dSMartin Elshuber return;
991fef3036dSMartin Elshuber } else {
992fef3036dSMartin Elshuber // Otherwise we allow that the last index operand of the GEP is
993fef3036dSMartin Elshuber // non-constant.
994fef3036dSMartin Elshuber unsigned idxOperand, e;
995fef3036dSMartin Elshuber SmallVector<Value *, 4> Indices;
996fef3036dSMartin Elshuber for (idxOperand = 1, e = GEP.getNumOperands(); idxOperand < e;
997fef3036dSMartin Elshuber idxOperand++) {
998fef3036dSMartin Elshuber ConstantInt *IDX = dyn_cast<ConstantInt>(GEP.getOperand(idxOperand));
999fef3036dSMartin Elshuber if (!IDX)
1000fef3036dSMartin Elshuber break;
1001fef3036dSMartin Elshuber Indices.push_back(IDX);
1002fef3036dSMartin Elshuber }
1003fef3036dSMartin Elshuber
1004fef3036dSMartin Elshuber // It must also be the last operand.
1005fef3036dSMartin Elshuber if (idxOperand + 1 != e) {
1006fef3036dSMartin Elshuber Result = Polynomial();
1007fef3036dSMartin Elshuber BasePtr = nullptr;
1008fef3036dSMartin Elshuber return;
1009fef3036dSMartin Elshuber }
1010fef3036dSMartin Elshuber
1011fef3036dSMartin Elshuber // Compute the polynomial of the index operand.
1012fef3036dSMartin Elshuber computePolynomial(*GEP.getOperand(idxOperand), Result);
1013fef3036dSMartin Elshuber
1014fef3036dSMartin Elshuber // Compute base offset from zero based index, excluding the last
1015fef3036dSMartin Elshuber // variable operand.
1016fef3036dSMartin Elshuber BaseOffset =
1017fef3036dSMartin Elshuber DL.getIndexedOffsetInType(GEP.getSourceElementType(), Indices);
1018fef3036dSMartin Elshuber
1019fef3036dSMartin Elshuber // Apply the operations of GEP to the polynomial.
1020fef3036dSMartin Elshuber unsigned ResultSize = DL.getTypeAllocSize(GEP.getResultElementType());
1021fef3036dSMartin Elshuber Result.sextOrTrunc(PointerBits);
1022fef3036dSMartin Elshuber Result.mul(APInt(PointerBits, ResultSize));
1023fef3036dSMartin Elshuber Result.add(BaseOffset);
1024fef3036dSMartin Elshuber BasePtr = GEP.getPointerOperand();
1025fef3036dSMartin Elshuber }
1026fef3036dSMartin Elshuber }
1027fef3036dSMartin Elshuber // All other instructions are handled by using the value as base pointer and
1028fef3036dSMartin Elshuber // a zero polynomial.
1029fef3036dSMartin Elshuber else {
1030fef3036dSMartin Elshuber BasePtr = &Ptr;
1031fef3036dSMartin Elshuber Polynomial(DL.getIndexSizeInBits(PtrTy->getPointerAddressSpace()), 0);
1032fef3036dSMartin Elshuber }
1033fef3036dSMartin Elshuber }
1034fef3036dSMartin Elshuber
1035fef3036dSMartin Elshuber #ifndef NDEBUG
print__anon07e87e4b0111::VectorInfo1036fef3036dSMartin Elshuber void print(raw_ostream &OS) const {
1037fef3036dSMartin Elshuber if (PV)
1038fef3036dSMartin Elshuber OS << *PV;
1039fef3036dSMartin Elshuber else
1040fef3036dSMartin Elshuber OS << "(none)";
1041fef3036dSMartin Elshuber OS << " + ";
1042fef3036dSMartin Elshuber for (unsigned i = 0; i < getDimension(); i++)
1043fef3036dSMartin Elshuber OS << ((i == 0) ? "[" : ", ") << EI[i].Ofs;
1044fef3036dSMartin Elshuber OS << "]";
1045fef3036dSMartin Elshuber }
1046fef3036dSMartin Elshuber #endif
1047fef3036dSMartin Elshuber };
1048fef3036dSMartin Elshuber
1049fef3036dSMartin Elshuber } // anonymous namespace
1050fef3036dSMartin Elshuber
findPattern(std::list<VectorInfo> & Candidates,std::list<VectorInfo> & InterleavedLoad,unsigned Factor,const DataLayout & DL)1051fef3036dSMartin Elshuber bool InterleavedLoadCombineImpl::findPattern(
1052fef3036dSMartin Elshuber std::list<VectorInfo> &Candidates, std::list<VectorInfo> &InterleavedLoad,
1053fef3036dSMartin Elshuber unsigned Factor, const DataLayout &DL) {
1054fef3036dSMartin Elshuber for (auto C0 = Candidates.begin(), E0 = Candidates.end(); C0 != E0; ++C0) {
1055fef3036dSMartin Elshuber unsigned i;
1056fef3036dSMartin Elshuber // Try to find an interleaved load using the front of Worklist as first line
1057fef3036dSMartin Elshuber unsigned Size = DL.getTypeAllocSize(C0->VTy->getElementType());
1058fef3036dSMartin Elshuber
1059fef3036dSMartin Elshuber // List containing iterators pointing to the VectorInfos of the candidates
1060fef3036dSMartin Elshuber std::vector<std::list<VectorInfo>::iterator> Res(Factor, Candidates.end());
1061fef3036dSMartin Elshuber
1062fef3036dSMartin Elshuber for (auto C = Candidates.begin(), E = Candidates.end(); C != E; C++) {
1063fef3036dSMartin Elshuber if (C->VTy != C0->VTy)
1064fef3036dSMartin Elshuber continue;
1065fef3036dSMartin Elshuber if (C->BB != C0->BB)
1066fef3036dSMartin Elshuber continue;
1067fef3036dSMartin Elshuber if (C->PV != C0->PV)
1068fef3036dSMartin Elshuber continue;
1069fef3036dSMartin Elshuber
1070fef3036dSMartin Elshuber // Check the current value matches any of factor - 1 remaining lines
1071fef3036dSMartin Elshuber for (i = 1; i < Factor; i++) {
1072fef3036dSMartin Elshuber if (C->EI[0].Ofs.isProvenEqualTo(C0->EI[0].Ofs + i * Size)) {
1073fef3036dSMartin Elshuber Res[i] = C;
1074fef3036dSMartin Elshuber }
1075fef3036dSMartin Elshuber }
1076fef3036dSMartin Elshuber
1077fef3036dSMartin Elshuber for (i = 1; i < Factor; i++) {
1078fef3036dSMartin Elshuber if (Res[i] == Candidates.end())
1079fef3036dSMartin Elshuber break;
1080fef3036dSMartin Elshuber }
1081fef3036dSMartin Elshuber if (i == Factor) {
1082fef3036dSMartin Elshuber Res[0] = C0;
1083fef3036dSMartin Elshuber break;
1084fef3036dSMartin Elshuber }
1085fef3036dSMartin Elshuber }
1086fef3036dSMartin Elshuber
1087fef3036dSMartin Elshuber if (Res[0] != Candidates.end()) {
1088fef3036dSMartin Elshuber // Move the result into the output
1089fef3036dSMartin Elshuber for (unsigned i = 0; i < Factor; i++) {
1090fef3036dSMartin Elshuber InterleavedLoad.splice(InterleavedLoad.end(), Candidates, Res[i]);
1091fef3036dSMartin Elshuber }
1092fef3036dSMartin Elshuber
1093fef3036dSMartin Elshuber return true;
1094fef3036dSMartin Elshuber }
1095fef3036dSMartin Elshuber }
1096fef3036dSMartin Elshuber return false;
1097fef3036dSMartin Elshuber }
1098fef3036dSMartin Elshuber
1099fef3036dSMartin Elshuber LoadInst *
findFirstLoad(const std::set<LoadInst * > & LIs)1100fef3036dSMartin Elshuber InterleavedLoadCombineImpl::findFirstLoad(const std::set<LoadInst *> &LIs) {
1101fef3036dSMartin Elshuber assert(!LIs.empty() && "No load instructions given.");
1102fef3036dSMartin Elshuber
1103fef3036dSMartin Elshuber // All LIs are within the same BB. Select the first for a reference.
1104fef3036dSMartin Elshuber BasicBlock *BB = (*LIs.begin())->getParent();
11059850d3b1SKazu Hirata BasicBlock::iterator FLI = llvm::find_if(
11069850d3b1SKazu Hirata *BB, [&LIs](Instruction &I) -> bool { return is_contained(LIs, &I); });
1107fef3036dSMartin Elshuber assert(FLI != BB->end());
1108fef3036dSMartin Elshuber
1109fef3036dSMartin Elshuber return cast<LoadInst>(FLI);
1110fef3036dSMartin Elshuber }
1111fef3036dSMartin Elshuber
combine(std::list<VectorInfo> & InterleavedLoad,OptimizationRemarkEmitter & ORE)1112fef3036dSMartin Elshuber bool InterleavedLoadCombineImpl::combine(std::list<VectorInfo> &InterleavedLoad,
1113fef3036dSMartin Elshuber OptimizationRemarkEmitter &ORE) {
1114fef3036dSMartin Elshuber LLVM_DEBUG(dbgs() << "Checking interleaved load\n");
1115fef3036dSMartin Elshuber
1116fef3036dSMartin Elshuber // The insertion point is the LoadInst which loads the first values. The
1117fef3036dSMartin Elshuber // following tests are used to proof that the combined load can be inserted
1118fef3036dSMartin Elshuber // just before InsertionPoint.
1119fef3036dSMartin Elshuber LoadInst *InsertionPoint = InterleavedLoad.front().EI[0].LI;
1120fef3036dSMartin Elshuber
1121fef3036dSMartin Elshuber // Test if the offset is computed
1122fef3036dSMartin Elshuber if (!InsertionPoint)
1123fef3036dSMartin Elshuber return false;
1124fef3036dSMartin Elshuber
1125fef3036dSMartin Elshuber std::set<LoadInst *> LIs;
1126fef3036dSMartin Elshuber std::set<Instruction *> Is;
1127fef3036dSMartin Elshuber std::set<Instruction *> SVIs;
1128fef3036dSMartin Elshuber
11299b76160eSDavid Sherwood InstructionCost InterleavedCost;
11309b76160eSDavid Sherwood InstructionCost InstructionCost = 0;
11311a7b7d7bSDaniil Fukalov const TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency;
1132fef3036dSMartin Elshuber
1133fef3036dSMartin Elshuber // Get the interleave factor
1134fef3036dSMartin Elshuber unsigned Factor = InterleavedLoad.size();
1135fef3036dSMartin Elshuber
1136fef3036dSMartin Elshuber // Merge all input sets used in analysis
1137fef3036dSMartin Elshuber for (auto &VI : InterleavedLoad) {
1138fef3036dSMartin Elshuber // Generate a set of all load instructions to be combined
1139fef3036dSMartin Elshuber LIs.insert(VI.LIs.begin(), VI.LIs.end());
1140fef3036dSMartin Elshuber
1141fef3036dSMartin Elshuber // Generate a set of all instructions taking part in load
1142fef3036dSMartin Elshuber // interleaved. This list excludes the instructions necessary for the
1143fef3036dSMartin Elshuber // polynomial construction.
1144fef3036dSMartin Elshuber Is.insert(VI.Is.begin(), VI.Is.end());
1145fef3036dSMartin Elshuber
1146fef3036dSMartin Elshuber // Generate the set of the final ShuffleVectorInst.
1147fef3036dSMartin Elshuber SVIs.insert(VI.SVI);
1148fef3036dSMartin Elshuber }
1149fef3036dSMartin Elshuber
1150fef3036dSMartin Elshuber // There is nothing to combine.
1151fef3036dSMartin Elshuber if (LIs.size() < 2)
1152fef3036dSMartin Elshuber return false;
1153fef3036dSMartin Elshuber
1154fef3036dSMartin Elshuber // Test if all participating instruction will be dead after the
1155fef3036dSMartin Elshuber // transformation. If intermediate results are used, no performance gain can
1156fef3036dSMartin Elshuber // be expected. Also sum the cost of the Instructions beeing left dead.
1157*9e6d1f4bSKazu Hirata for (const auto &I : Is) {
1158fef3036dSMartin Elshuber // Compute the old cost
11591a7b7d7bSDaniil Fukalov InstructionCost += TTI.getInstructionCost(I, CostKind);
1160fef3036dSMartin Elshuber
1161fef3036dSMartin Elshuber // The final SVIs are allowed not to be dead, all uses will be replaced
1162fef3036dSMartin Elshuber if (SVIs.find(I) != SVIs.end())
1163fef3036dSMartin Elshuber continue;
1164fef3036dSMartin Elshuber
1165fef3036dSMartin Elshuber // If there are users outside the set to be eliminated, we abort the
1166fef3036dSMartin Elshuber // transformation. No gain can be expected.
11678dc7b982SMark de Wever for (auto *U : I->users()) {
1168fef3036dSMartin Elshuber if (Is.find(dyn_cast<Instruction>(U)) == Is.end())
1169fef3036dSMartin Elshuber return false;
1170fef3036dSMartin Elshuber }
1171fef3036dSMartin Elshuber }
1172fef3036dSMartin Elshuber
11739b76160eSDavid Sherwood // We need to have a valid cost in order to proceed.
11749b76160eSDavid Sherwood if (!InstructionCost.isValid())
11759b76160eSDavid Sherwood return false;
11769b76160eSDavid Sherwood
1177fef3036dSMartin Elshuber // We know that all LoadInst are within the same BB. This guarantees that
1178fef3036dSMartin Elshuber // either everything or nothing is loaded.
1179fef3036dSMartin Elshuber LoadInst *First = findFirstLoad(LIs);
1180fef3036dSMartin Elshuber
1181fef3036dSMartin Elshuber // To be safe that the loads can be combined, iterate over all loads and test
1182fef3036dSMartin Elshuber // that the corresponding defining access dominates first LI. This guarantees
1183fef3036dSMartin Elshuber // that there are no aliasing stores in between the loads.
1184fef3036dSMartin Elshuber auto FMA = MSSA.getMemoryAccess(First);
1185*9e6d1f4bSKazu Hirata for (auto *LI : LIs) {
1186fef3036dSMartin Elshuber auto MADef = MSSA.getMemoryAccess(LI)->getDefiningAccess();
1187fef3036dSMartin Elshuber if (!MSSA.dominates(MADef, FMA))
1188fef3036dSMartin Elshuber return false;
1189fef3036dSMartin Elshuber }
1190fef3036dSMartin Elshuber assert(!LIs.empty() && "There are no LoadInst to combine");
1191fef3036dSMartin Elshuber
1192fef3036dSMartin Elshuber // It is necessary that insertion point dominates all final ShuffleVectorInst.
1193fef3036dSMartin Elshuber for (auto &VI : InterleavedLoad) {
1194fef3036dSMartin Elshuber if (!DT.dominates(InsertionPoint, VI.SVI))
1195fef3036dSMartin Elshuber return false;
1196fef3036dSMartin Elshuber }
1197fef3036dSMartin Elshuber
1198fef3036dSMartin Elshuber // All checks are done. Add instructions detectable by InterleavedAccessPass
1199fef3036dSMartin Elshuber // The old instruction will are left dead.
1200fef3036dSMartin Elshuber IRBuilder<> Builder(InsertionPoint);
1201fef3036dSMartin Elshuber Type *ETy = InterleavedLoad.front().SVI->getType()->getElementType();
1202fef3036dSMartin Elshuber unsigned ElementsPerSVI =
1203ff5b9a7bSChristopher Tetreault cast<FixedVectorType>(InterleavedLoad.front().SVI->getType())
1204ff5b9a7bSChristopher Tetreault ->getNumElements();
1205364c5954SDavid Sherwood FixedVectorType *ILTy = FixedVectorType::get(ETy, Factor * ElementsPerSVI);
1206fef3036dSMartin Elshuber
1207a40dc4eaSBenjamin Kramer auto Indices = llvm::to_vector<4>(llvm::seq<unsigned>(0, Factor));
1208fef3036dSMartin Elshuber InterleavedCost = TTI.getInterleavedMemoryOpCost(
1209fdc7c7fbSGuillaume Chatelet Instruction::Load, ILTy, Factor, Indices, InsertionPoint->getAlign(),
12101a7b7d7bSDaniil Fukalov InsertionPoint->getPointerAddressSpace(), CostKind);
1211fef3036dSMartin Elshuber
1212fef3036dSMartin Elshuber if (InterleavedCost >= InstructionCost) {
1213fef3036dSMartin Elshuber return false;
1214fef3036dSMartin Elshuber }
1215fef3036dSMartin Elshuber
1216fef3036dSMartin Elshuber // Create a pointer cast for the wide load.
1217fef3036dSMartin Elshuber auto CI = Builder.CreatePointerCast(InsertionPoint->getOperand(0),
1218fef3036dSMartin Elshuber ILTy->getPointerTo(),
1219fef3036dSMartin Elshuber "interleaved.wide.ptrcast");
1220fef3036dSMartin Elshuber
1221fef3036dSMartin Elshuber // Create the wide load and update the MemorySSA.
1222279fa8e0SGuillaume Chatelet auto LI = Builder.CreateAlignedLoad(ILTy, CI, InsertionPoint->getAlign(),
1223fef3036dSMartin Elshuber "interleaved.wide.load");
1224fef3036dSMartin Elshuber auto MSSAU = MemorySSAUpdater(&MSSA);
1225fef3036dSMartin Elshuber MemoryUse *MSSALoad = cast<MemoryUse>(MSSAU.createMemoryAccessBefore(
1226fef3036dSMartin Elshuber LI, nullptr, MSSA.getMemoryAccess(InsertionPoint)));
1227e5c4308bSFlorian Hahn MSSAU.insertUse(MSSALoad, /*RenameUses=*/ true);
1228fef3036dSMartin Elshuber
1229fef3036dSMartin Elshuber // Create the final SVIs and replace all uses.
1230fef3036dSMartin Elshuber int i = 0;
1231fef3036dSMartin Elshuber for (auto &VI : InterleavedLoad) {
12326f64dacaSBenjamin Kramer SmallVector<int, 4> Mask;
1233fef3036dSMartin Elshuber for (unsigned j = 0; j < ElementsPerSVI; j++)
1234fef3036dSMartin Elshuber Mask.push_back(i + j * Factor);
1235fef3036dSMartin Elshuber
1236fef3036dSMartin Elshuber Builder.SetInsertPoint(VI.SVI);
12379b296102SJuneyoung Lee auto SVI = Builder.CreateShuffleVector(LI, Mask, "interleaved.shuffle");
1238fef3036dSMartin Elshuber VI.SVI->replaceAllUsesWith(SVI);
1239fef3036dSMartin Elshuber i++;
1240fef3036dSMartin Elshuber }
1241fef3036dSMartin Elshuber
1242fef3036dSMartin Elshuber NumInterleavedLoadCombine++;
1243fef3036dSMartin Elshuber ORE.emit([&]() {
1244fef3036dSMartin Elshuber return OptimizationRemark(DEBUG_TYPE, "Combined Interleaved Load", LI)
1245fef3036dSMartin Elshuber << "Load interleaved combined with factor "
1246fef3036dSMartin Elshuber << ore::NV("Factor", Factor);
1247fef3036dSMartin Elshuber });
1248fef3036dSMartin Elshuber
1249fef3036dSMartin Elshuber return true;
1250fef3036dSMartin Elshuber }
1251fef3036dSMartin Elshuber
run()1252fef3036dSMartin Elshuber bool InterleavedLoadCombineImpl::run() {
1253fef3036dSMartin Elshuber OptimizationRemarkEmitter ORE(&F);
1254fef3036dSMartin Elshuber bool changed = false;
1255fef3036dSMartin Elshuber unsigned MaxFactor = TLI.getMaxSupportedInterleaveFactor();
1256fef3036dSMartin Elshuber
1257fef3036dSMartin Elshuber auto &DL = F.getParent()->getDataLayout();
1258fef3036dSMartin Elshuber
1259fef3036dSMartin Elshuber // Start with the highest factor to avoid combining and recombining.
1260fef3036dSMartin Elshuber for (unsigned Factor = MaxFactor; Factor >= 2; Factor--) {
1261fef3036dSMartin Elshuber std::list<VectorInfo> Candidates;
1262fef3036dSMartin Elshuber
1263fef3036dSMartin Elshuber for (BasicBlock &BB : F) {
1264fef3036dSMartin Elshuber for (Instruction &I : BB) {
1265fef3036dSMartin Elshuber if (auto SVI = dyn_cast<ShuffleVectorInst>(&I)) {
1266364c5954SDavid Sherwood // We don't support scalable vectors in this pass.
1267364c5954SDavid Sherwood if (isa<ScalableVectorType>(SVI->getType()))
1268364c5954SDavid Sherwood continue;
1269fef3036dSMartin Elshuber
1270364c5954SDavid Sherwood Candidates.emplace_back(cast<FixedVectorType>(SVI->getType()));
1271fef3036dSMartin Elshuber
1272fef3036dSMartin Elshuber if (!VectorInfo::computeFromSVI(SVI, Candidates.back(), DL)) {
1273fef3036dSMartin Elshuber Candidates.pop_back();
1274fef3036dSMartin Elshuber continue;
1275fef3036dSMartin Elshuber }
1276fef3036dSMartin Elshuber
1277fef3036dSMartin Elshuber if (!Candidates.back().isInterleaved(Factor, DL)) {
1278fef3036dSMartin Elshuber Candidates.pop_back();
1279fef3036dSMartin Elshuber }
1280fef3036dSMartin Elshuber }
1281fef3036dSMartin Elshuber }
1282fef3036dSMartin Elshuber }
1283fef3036dSMartin Elshuber
1284fef3036dSMartin Elshuber std::list<VectorInfo> InterleavedLoad;
1285fef3036dSMartin Elshuber while (findPattern(Candidates, InterleavedLoad, Factor, DL)) {
1286fef3036dSMartin Elshuber if (combine(InterleavedLoad, ORE)) {
1287fef3036dSMartin Elshuber changed = true;
1288fef3036dSMartin Elshuber } else {
1289fef3036dSMartin Elshuber // Remove the first element of the Interleaved Load but put the others
1290fef3036dSMartin Elshuber // back on the list and continue searching
1291fef3036dSMartin Elshuber Candidates.splice(Candidates.begin(), InterleavedLoad,
1292fef3036dSMartin Elshuber std::next(InterleavedLoad.begin()),
1293fef3036dSMartin Elshuber InterleavedLoad.end());
1294fef3036dSMartin Elshuber }
1295fef3036dSMartin Elshuber InterleavedLoad.clear();
1296fef3036dSMartin Elshuber }
1297fef3036dSMartin Elshuber }
1298fef3036dSMartin Elshuber
1299fef3036dSMartin Elshuber return changed;
1300fef3036dSMartin Elshuber }
1301fef3036dSMartin Elshuber
1302fef3036dSMartin Elshuber namespace {
1303fef3036dSMartin Elshuber /// This pass combines interleaved loads into a pattern detectable by
1304fef3036dSMartin Elshuber /// InterleavedAccessPass.
1305fef3036dSMartin Elshuber struct InterleavedLoadCombine : public FunctionPass {
1306fef3036dSMartin Elshuber static char ID;
1307fef3036dSMartin Elshuber
InterleavedLoadCombine__anon07e87e4b0411::InterleavedLoadCombine1308fef3036dSMartin Elshuber InterleavedLoadCombine() : FunctionPass(ID) {
1309fef3036dSMartin Elshuber initializeInterleavedLoadCombinePass(*PassRegistry::getPassRegistry());
1310fef3036dSMartin Elshuber }
1311fef3036dSMartin Elshuber
getPassName__anon07e87e4b0411::InterleavedLoadCombine1312fef3036dSMartin Elshuber StringRef getPassName() const override {
1313fef3036dSMartin Elshuber return "Interleaved Load Combine Pass";
1314fef3036dSMartin Elshuber }
1315fef3036dSMartin Elshuber
runOnFunction__anon07e87e4b0411::InterleavedLoadCombine1316fef3036dSMartin Elshuber bool runOnFunction(Function &F) override {
1317fef3036dSMartin Elshuber if (DisableInterleavedLoadCombine)
1318fef3036dSMartin Elshuber return false;
1319fef3036dSMartin Elshuber
1320fef3036dSMartin Elshuber auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1321fef3036dSMartin Elshuber if (!TPC)
1322fef3036dSMartin Elshuber return false;
1323fef3036dSMartin Elshuber
1324fef3036dSMartin Elshuber LLVM_DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName()
1325fef3036dSMartin Elshuber << "\n");
1326fef3036dSMartin Elshuber
1327fef3036dSMartin Elshuber return InterleavedLoadCombineImpl(
1328fef3036dSMartin Elshuber F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1329fef3036dSMartin Elshuber getAnalysis<MemorySSAWrapperPass>().getMSSA(),
1330fef3036dSMartin Elshuber TPC->getTM<TargetMachine>())
1331fef3036dSMartin Elshuber .run();
1332fef3036dSMartin Elshuber }
1333fef3036dSMartin Elshuber
getAnalysisUsage__anon07e87e4b0411::InterleavedLoadCombine1334fef3036dSMartin Elshuber void getAnalysisUsage(AnalysisUsage &AU) const override {
1335fef3036dSMartin Elshuber AU.addRequired<MemorySSAWrapperPass>();
1336fef3036dSMartin Elshuber AU.addRequired<DominatorTreeWrapperPass>();
1337fef3036dSMartin Elshuber FunctionPass::getAnalysisUsage(AU);
1338fef3036dSMartin Elshuber }
1339fef3036dSMartin Elshuber
1340fef3036dSMartin Elshuber private:
1341fef3036dSMartin Elshuber };
1342fef3036dSMartin Elshuber } // anonymous namespace
1343fef3036dSMartin Elshuber
1344fef3036dSMartin Elshuber char InterleavedLoadCombine::ID = 0;
1345fef3036dSMartin Elshuber
1346fef3036dSMartin Elshuber INITIALIZE_PASS_BEGIN(
1347fef3036dSMartin Elshuber InterleavedLoadCombine, DEBUG_TYPE,
1348fef3036dSMartin Elshuber "Combine interleaved loads into wide loads and shufflevector instructions",
1349fef3036dSMartin Elshuber false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)1350fef3036dSMartin Elshuber INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1351fef3036dSMartin Elshuber INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1352fef3036dSMartin Elshuber INITIALIZE_PASS_END(
1353fef3036dSMartin Elshuber InterleavedLoadCombine, DEBUG_TYPE,
1354fef3036dSMartin Elshuber "Combine interleaved loads into wide loads and shufflevector instructions",
1355fef3036dSMartin Elshuber false, false)
1356fef3036dSMartin Elshuber
1357fef3036dSMartin Elshuber FunctionPass *
1358fef3036dSMartin Elshuber llvm::createInterleavedLoadCombinePass() {
1359fef3036dSMartin Elshuber auto P = new InterleavedLoadCombine();
1360fef3036dSMartin Elshuber return P;
1361fef3036dSMartin Elshuber }
1362