1 //===- InterleavedLoadCombine.cpp - Combine Interleaved Loads ---*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
11 // This file defines the interleaved-load-combine pass. The pass searches for
12 // ShuffleVectorInstruction that execute interleaving loads. If a matching
13 // pattern is found, it adds a combined load and further instructions in a
14 // pattern that is detectable by InterleavedAccesPass. The old instructions are
15 // left dead to be removed later. The pass is specifically designed to be
16 // executed just before InterleavedAccesPass to find any left-over instances
17 // that are not detected within former passes.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/MemorySSA.h"
23 #include "llvm/Analysis/MemorySSAUpdater.h"
24 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/CodeGen/InterleavedLoadCombine.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/TargetLowering.h"
29 #include "llvm/CodeGen/TargetPassConfig.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetMachine.h"
50 #define DEBUG_TYPE "interleaved-load-combine"
55 STATISTIC(NumInterleavedLoadCombine
, "Number of combined loads");
57 /// Option to disable the pass
58 static cl::opt
<bool> DisableInterleavedLoadCombine(
59 "disable-" DEBUG_TYPE
, cl::init(false), cl::Hidden
,
60 cl::desc("Disable combining of interleaved loads"));
64 struct InterleavedLoadCombineImpl
{
66 InterleavedLoadCombineImpl(Function
&F
, DominatorTree
&DT
, MemorySSA
&MSSA
,
67 const TargetTransformInfo
&TTI
,
68 const TargetMachine
&TM
)
69 : F(F
), DT(DT
), MSSA(MSSA
),
70 TLI(*TM
.getSubtargetImpl(F
)->getTargetLowering()), TTI(TTI
) {}
72 /// Scan the function for interleaved load candidates and execute the
73 /// replacement if applicable.
77 /// Function this pass is working on
80 /// Dominator Tree Analysis
83 /// Memory Alias Analyses
86 /// Target Lowering Information
87 const TargetLowering
&TLI
;
89 /// Target Transform Information
90 const TargetTransformInfo
&TTI
;
92 /// Find the instruction in sets LIs that dominates all others, return nullptr
94 LoadInst
*findFirstLoad(const std::set
<LoadInst
*> &LIs
);
96 /// Replace interleaved load candidates. It does additional
97 /// analyses if this makes sense. Returns true on success and false
98 /// of nothing has been changed.
99 bool combine(std::list
<VectorInfo
> &InterleavedLoad
,
100 OptimizationRemarkEmitter
&ORE
);
102 /// Given a set of VectorInfo containing candidates for a given interleave
103 /// factor, find a set that represents a 'factor' interleaved load.
104 bool findPattern(std::list
<VectorInfo
> &Candidates
,
105 std::list
<VectorInfo
> &InterleavedLoad
, unsigned Factor
,
106 const DataLayout
&DL
);
107 }; // InterleavedLoadCombine
109 /// First Order Polynomial on an n-Bit Integer Value
111 /// Polynomial(Value) = Value * B + A + E*2^(n-e)
113 /// A and B are the coefficients. E*2^(n-e) is an error within 'e' most
114 /// significant bits. It is introduced if an exact computation cannot be proven
115 /// (e.q. division by 2).
117 /// As part of this optimization multiple loads will be combined. It necessary
118 /// to prove that loads are within some relative offset to each other. This
119 /// class is used to prove relative offsets of values loaded from memory.
121 /// Representing an integer in this form is sound since addition in two's
122 /// complement is associative (trivial) and multiplication distributes over the
123 /// addition (see Proof(1) in Polynomial::mul). Further, both operations
127 // declare @fn(i64 %IDX, <4 x float>* %PTR) {
128 // %Pa1 = add i64 %IDX, 2
129 // %Pa2 = lshr i64 %Pa1, 1
130 // %Pa3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pa2
131 // %Va = load <4 x float>, <4 x float>* %Pa3
133 // %Pb1 = add i64 %IDX, 4
134 // %Pb2 = lshr i64 %Pb1, 1
135 // %Pb3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pb2
136 // %Vb = load <4 x float>, <4 x float>* %Pb3
139 // The goal is to prove that two loads load consecutive addresses.
141 // In this case the polynomials are constructed by the following
144 // The number tag #e specifies the error bits.
147 // Pa_1 = %IDX + 2 #0 | add 2
148 // Pa_2 = %IDX/2 + 1 #1 | lshr 1
149 // Pa_3 = %IDX/2 + 1 #1 | GEP, step signext to i64
150 // Pa_4 = (%IDX/2)*16 + 16 #0 | GEP, multiply index by sizeof(4) for floats
151 // Pa_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
154 // Pb_1 = %IDX + 4 #0 | add 2
155 // Pb_2 = %IDX/2 + 2 #1 | lshr 1
156 // Pb_3 = %IDX/2 + 2 #1 | GEP, step signext to i64
157 // Pb_4 = (%IDX/2)*16 + 32 #0 | GEP, multiply index by sizeof(4) for floats
158 // Pb_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
160 // Pb_5 - Pa_5 = 16 #0 | subtract to get the offset
162 // Remark: %PTR is not maintained within this class. So in this instance the
163 // offset of 16 can only be assumed if the pointers are equal.
174 /// Number of Error Bits e
175 unsigned ErrorMSBs
= (unsigned)-1;
181 SmallVector
<std::pair
<BOps
, APInt
>, 4> B
;
187 Polynomial(Value
*V
) : V(V
) {
188 IntegerType
*Ty
= dyn_cast
<IntegerType
>(V
->getType());
192 A
= APInt(Ty
->getBitWidth(), 0);
196 Polynomial(const APInt
&A
, unsigned ErrorMSBs
= 0)
197 : ErrorMSBs(ErrorMSBs
), A(A
) {}
199 Polynomial(unsigned BitWidth
, uint64_t A
, unsigned ErrorMSBs
= 0)
200 : ErrorMSBs(ErrorMSBs
), A(BitWidth
, A
) {}
202 Polynomial() = default;
204 /// Increment and clamp the number of undefined bits.
205 void incErrorMSBs(unsigned amt
) {
206 if (ErrorMSBs
== (unsigned)-1)
210 if (ErrorMSBs
> A
.getBitWidth())
211 ErrorMSBs
= A
.getBitWidth();
214 /// Decrement and clamp the number of undefined bits.
215 void decErrorMSBs(unsigned amt
) {
216 if (ErrorMSBs
== (unsigned)-1)
225 /// Apply an add on the polynomial
226 Polynomial
&add(const APInt
&C
) {
227 // Note: Addition is associative in two's complement even when in case of
230 // Error bits can only propagate into higher significant bits. As these are
231 // already regarded as undefined, there is no change.
233 // Theorem: Adding a constant to a polynomial does not change the error
238 // Since the addition is associative and commutes:
240 // (B + A + E*2^(n-e)) + C = B + (A + C) + E*2^(n-e)
243 if (C
.getBitWidth() != A
.getBitWidth()) {
244 ErrorMSBs
= (unsigned)-1;
252 /// Apply a multiplication onto the polynomial.
253 Polynomial
&mul(const APInt
&C
) {
254 // Note: Multiplication distributes over the addition
256 // Theorem: Multiplication distributes over the addition
261 // = (B + A) + (B + A) + .. {C Times}
262 // addition is associative and commutes, hence
263 // = B + B + .. {C Times} .. + A + A + .. {C times}
265 // (see (function add) for signed values and overflows)
268 // Theorem: If C has c trailing zeros, errors bits in A or B are shifted out
273 // Let B' and A' be the n-Bit inputs with some unknown errors EA,
274 // EB at e leading bits. B' and A' can be written down as:
276 // B' = B + 2^(n-e)*EB
277 // A' = A + 2^(n-e)*EA
279 // Let C' be an input with c trailing zero bits. C' can be written as
283 // Therefore we can compute the result by using distributivity and
286 // (B'*C' + A'*C') = [B + 2^(n-e)*EB] * C' + [A + 2^(n-e)*EA] * C' =
287 // = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
289 // = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
290 // = [B + A + 2^(n-e)*EB + 2^(n-e)*EA] * C' =
291 // = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C' =
292 // = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C*2^c =
293 // = (B + A) * C' + C*(EB + EA)*2^(n-e)*2^c =
295 // Let EC be the final error with EC = C*(EB + EA)
297 // = (B + A)*C' + EC*2^(n-e)*2^c =
298 // = (B + A)*C' + EC*2^(n-(e-c))
300 // Since EC is multiplied by 2^(n-(e-c)) the resulting error contains c
301 // less error bits than the input. c bits are shifted out to the left.
304 if (C
.getBitWidth() != A
.getBitWidth()) {
305 ErrorMSBs
= (unsigned)-1;
309 // Multiplying by one is a no-op.
314 // Multiplying by zero removes the coefficient B and defines all bits.
320 // See Proof(2): Trailing zero bits indicate a left shift. This removes
321 // leading bits from the result even if they are undefined.
322 decErrorMSBs(C
.countr_zero());
325 pushBOperation(Mul
, C
);
329 /// Apply a logical shift right on the polynomial
330 Polynomial
&lshr(const APInt
&C
) {
331 // Theorem(1): (B + A + E*2^(n-e)) >> 1 => (B >> 1) + (A >> 1) + E'*2^(n-e')
334 // E is a e-bit number,
335 // E' is a e'-bit number,
336 // holds under the following precondition:
338 // pre(2): e < n, (see Theorem(2) for the trivial case with e=n)
339 // where >> expresses a logical shift to the right, with adding zeros.
341 // We need to show that for every, E there is a E'
343 // B = b_h * 2^(n-1) + b_m * 2 + b_l
344 // A = a_h * 2^(n-1) + a_m * 2 (pre(1))
346 // where a_h, b_h, b_l are single bits, and a_m, b_m are (n-2) bit numbers
348 // Let X = (B + A + E*2^(n-e)) >> 1
349 // Let Y = (B >> 1) + (A >> 1) + E*2^(n-e) >> 1
351 // X = [B + A + E*2^(n-e)] >> 1 =
352 // = [ b_h * 2^(n-1) + b_m * 2 + b_l +
353 // + a_h * 2^(n-1) + a_m * 2 +
354 // + E * 2^(n-e) ] >> 1 =
356 // The sum is built by putting the overflow of [a_m + b+n] into the term
357 // 2^(n-1). As there are no more bits beyond 2^(n-1) the overflow within
358 // this bit is discarded. This is expressed by % 2.
360 // The bit in position 0 cannot overflow into the term (b_m + a_m).
362 // = [ ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-1) +
363 // + ((b_m + a_m) % 2^(n-2)) * 2 +
364 // + b_l + E * 2^(n-e) ] >> 1 =
366 // The shift is computed by dividing the terms by 2 and by cutting off
369 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
370 // + ((b_m + a_m) % 2^(n-2)) +
371 // + E * 2^(n-(e+1)) =
373 // by the definition in the Theorem e+1 = e'
375 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
376 // + ((b_m + a_m) % 2^(n-2)) +
379 // Compute Y by applying distributivity first
381 // Y = (B >> 1) + (A >> 1) + E*2^(n-e') =
382 // = (b_h * 2^(n-1) + b_m * 2 + b_l) >> 1 +
383 // + (a_h * 2^(n-1) + a_m * 2) >> 1 +
384 // + E * 2^(n-e) >> 1 =
386 // Again, the shift is computed by dividing the terms by 2 and by cutting
389 // = b_h * 2^(n-2) + b_m +
390 // + a_h * 2^(n-2) + a_m +
391 // + E * 2^(n-(e+1)) =
393 // Again, the sum is built by putting the overflow of [a_m + b+n] into
394 // the term 2^(n-1). But this time there is room for a second bit in the
395 // term 2^(n-2) we add this bit to a new term and denote it o_h in a
398 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] >> 1) * 2^(n-1) +
399 // + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
400 // + ((b_m + a_m) % 2^(n-2)) +
401 // + E * 2^(n-(e+1)) =
403 // Let o_h = [b_h + a_h + (b_m + a_m) >> (n-2)] >> 1
404 // Further replace e+1 by e'.
407 // + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
408 // + ((b_m + a_m) % 2^(n-2)) +
411 // Move o_h into the error term and construct E'. To ensure that there is
412 // no 2^x with negative x, this step requires pre(2) (e < n).
414 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
415 // + ((b_m + a_m) % 2^(n-2)) +
416 // + o_h * 2^(e'-1) * 2^(n-e') + | pre(2), move 2^(e'-1)
417 // | out of the old exponent
419 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
420 // + ((b_m + a_m) % 2^(n-2)) +
421 // + [o_h * 2^(e'-1) + E] * 2^(n-e') + | move 2^(e'-1) out of
422 // | the old exponent
424 // Let E' = o_h * 2^(e'-1) + E
426 // = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
427 // + ((b_m + a_m) % 2^(n-2)) +
430 // Because X and Y are distinct only in there error terms and E' can be
431 // constructed as shown the theorem holds.
434 // For completeness in case of the case e=n it is also required to show that
435 // distributivity can be applied.
437 // In this case Theorem(1) transforms to (the pre-condition on A can also be
440 // Theorem(2): (B + A + E) >> 1 => (B >> 1) + (A >> 1) + E'
442 // A, B, E, E' are two's complement numbers with the same bit
446 // Let (B >> 1) + (A >> 1) = Y
448 // Therefore we need to show that for every X and Y there is an E' which
449 // makes the equation
453 // hold. This is trivially the case for E' = X - Y.
457 // Remark: Distributing lshr with and arbitrary number n can be expressed as
458 // ((((B + A) lshr 1) lshr 1) ... ) {n times}.
459 // This construction induces n additional error bits at the left.
461 if (C
.getBitWidth() != A
.getBitWidth()) {
462 ErrorMSBs
= (unsigned)-1;
469 // Test if the result will be zero
470 unsigned shiftAmt
= C
.getZExtValue();
471 if (shiftAmt
>= C
.getBitWidth())
472 return mul(APInt(C
.getBitWidth(), 0));
474 // The proof that shiftAmt LSBs are zero for at least one summand is only
475 // possible for the constant number.
477 // If this can be proven add shiftAmt to the error counter
478 // `ErrorMSBs`. Otherwise set all bits as undefined.
479 if (A
.countr_zero() < shiftAmt
)
480 ErrorMSBs
= A
.getBitWidth();
482 incErrorMSBs(shiftAmt
);
484 // Apply the operation.
485 pushBOperation(LShr
, C
);
486 A
= A
.lshr(shiftAmt
);
491 /// Apply a sign-extend or truncate operation on the polynomial.
492 Polynomial
&sextOrTrunc(unsigned n
) {
493 if (n
< A
.getBitWidth()) {
494 // Truncate: Clearly undefined Bits on the MSB side are removed
496 decErrorMSBs(A
.getBitWidth() - n
);
498 pushBOperation(Trunc
, APInt(sizeof(n
) * 8, n
));
500 if (n
> A
.getBitWidth()) {
501 // Extend: Clearly extending first and adding later is different
502 // to adding first and extending later in all extended bits.
503 incErrorMSBs(n
- A
.getBitWidth());
505 pushBOperation(SExt
, APInt(sizeof(n
) * 8, n
));
511 /// Test if there is a coefficient B.
512 bool isFirstOrder() const { return V
!= nullptr; }
514 /// Test coefficient B of two Polynomials are equal.
515 bool isCompatibleTo(const Polynomial
&o
) const {
516 // The polynomial use different bit width.
517 if (A
.getBitWidth() != o
.A
.getBitWidth())
520 // If neither Polynomial has the Coefficient B.
521 if (!isFirstOrder() && !o
.isFirstOrder())
524 // The index variable is different.
528 // Check the operations.
529 if (B
.size() != o
.B
.size())
532 auto *ob
= o
.B
.begin();
533 for (const auto &b
: B
) {
542 /// Subtract two polynomials, return an undefined polynomial if
543 /// subtraction is not possible.
544 Polynomial
operator-(const Polynomial
&o
) const {
545 // Return an undefined polynomial if incompatible.
546 if (!isCompatibleTo(o
))
549 // If the polynomials are compatible (meaning they have the same
550 // coefficient on B), B is eliminated. Thus a polynomial solely
551 // containing A is returned
552 return Polynomial(A
- o
.A
, std::max(ErrorMSBs
, o
.ErrorMSBs
));
555 /// Subtract a constant from a polynomial,
556 Polynomial
operator-(uint64_t C
) const {
557 Polynomial
Result(*this);
562 /// Add a constant to a polynomial,
563 Polynomial
operator+(uint64_t C
) const {
564 Polynomial
Result(*this);
569 /// Returns true if it can be proven that two Polynomials are equal.
570 bool isProvenEqualTo(const Polynomial
&o
) {
571 // Subtract both polynomials and test if it is fully defined and zero.
572 Polynomial r
= *this - o
;
573 return (r
.ErrorMSBs
== 0) && (!r
.isFirstOrder()) && (r
.A
.isZero());
576 /// Print the polynomial into a stream.
577 void print(raw_ostream
&OS
) const {
578 OS
<< "[{#ErrBits:" << ErrorMSBs
<< "} ";
583 OS
<< "(" << *V
<< ") ";
601 OS
<< b
.second
<< ") ";
605 OS
<< "+ " << A
<< "]";
614 void pushBOperation(const BOps Op
, const APInt
&C
) {
615 if (isFirstOrder()) {
616 B
.push_back(std::make_pair(Op
, C
));
623 static raw_ostream
&operator<<(raw_ostream
&OS
, const Polynomial
&S
) {
629 /// VectorInfo stores abstract the following information for each vector
632 /// 1) The memory address loaded into the element as Polynomial
633 /// 2) a set of load instruction necessary to construct the vector,
634 /// 3) a set of all other instructions that are necessary to create the vector and
635 /// 4) a pointer value that can be used as relative base for all elements.
638 VectorInfo(const VectorInfo
&c
) : VTy(c
.VTy
) {
640 "Copying VectorInfo is neither implemented nor necessary,");
644 /// Information of a Vector Element
646 /// Offset Polynomial.
649 /// The Load Instruction used to Load the entry. LI is null if the pointer
650 /// of the load instruction does not point on to the entry
653 ElementInfo(Polynomial Offset
= Polynomial(), LoadInst
*LI
= nullptr)
654 : Ofs(Offset
), LI(LI
) {}
657 /// Basic-block the load instructions are within
658 BasicBlock
*BB
= nullptr;
660 /// Pointer value of all participation load instructions
663 /// Participating load instructions
664 std::set
<LoadInst
*> LIs
;
666 /// Participating instructions
667 std::set
<Instruction
*> Is
;
669 /// Final shuffle-vector instruction
670 ShuffleVectorInst
*SVI
= nullptr;
672 /// Information of the offset for each vector element
676 FixedVectorType
*const VTy
;
678 VectorInfo(FixedVectorType
*VTy
) : VTy(VTy
) {
679 EI
= new ElementInfo
[VTy
->getNumElements()];
682 VectorInfo
&operator=(const VectorInfo
&other
) = delete;
684 virtual ~VectorInfo() { delete[] EI
; }
686 unsigned getDimension() const { return VTy
->getNumElements(); }
688 /// Test if the VectorInfo can be part of an interleaved load with the
689 /// specified factor.
691 /// \param Factor of the interleave
692 /// \param DL Targets Datalayout
694 /// \returns true if this is possible and false if not
695 bool isInterleaved(unsigned Factor
, const DataLayout
&DL
) const {
696 unsigned Size
= DL
.getTypeAllocSize(VTy
->getElementType());
697 for (unsigned i
= 1; i
< getDimension(); i
++) {
698 if (!EI
[i
].Ofs
.isProvenEqualTo(EI
[0].Ofs
+ i
* Factor
* Size
)) {
705 /// Recursively computes the vector information stored in V.
707 /// This function delegates the work to specialized implementations
709 /// \param V Value to operate on
710 /// \param Result Result of the computation
712 /// \returns false if no sensible information can be gathered.
713 static bool compute(Value
*V
, VectorInfo
&Result
, const DataLayout
&DL
) {
714 ShuffleVectorInst
*SVI
= dyn_cast
<ShuffleVectorInst
>(V
);
716 return computeFromSVI(SVI
, Result
, DL
);
717 LoadInst
*LI
= dyn_cast
<LoadInst
>(V
);
719 return computeFromLI(LI
, Result
, DL
);
720 BitCastInst
*BCI
= dyn_cast
<BitCastInst
>(V
);
722 return computeFromBCI(BCI
, Result
, DL
);
726 /// BitCastInst specialization to compute the vector information.
728 /// \param BCI BitCastInst to operate on
729 /// \param Result Result of the computation
731 /// \returns false if no sensible information can be gathered.
732 static bool computeFromBCI(BitCastInst
*BCI
, VectorInfo
&Result
,
733 const DataLayout
&DL
) {
734 Instruction
*Op
= dyn_cast
<Instruction
>(BCI
->getOperand(0));
739 FixedVectorType
*VTy
= dyn_cast
<FixedVectorType
>(Op
->getType());
743 // We can only cast from large to smaller vectors
744 if (Result
.VTy
->getNumElements() % VTy
->getNumElements())
747 unsigned Factor
= Result
.VTy
->getNumElements() / VTy
->getNumElements();
748 unsigned NewSize
= DL
.getTypeAllocSize(Result
.VTy
->getElementType());
749 unsigned OldSize
= DL
.getTypeAllocSize(VTy
->getElementType());
751 if (NewSize
* Factor
!= OldSize
)
755 if (!compute(Op
, Old
, DL
))
758 for (unsigned i
= 0; i
< Result
.VTy
->getNumElements(); i
+= Factor
) {
759 for (unsigned j
= 0; j
< Factor
; j
++) {
761 ElementInfo(Old
.EI
[i
/ Factor
].Ofs
+ j
* NewSize
,
762 j
== 0 ? Old
.EI
[i
/ Factor
].LI
: nullptr);
768 Result
.LIs
.insert(Old
.LIs
.begin(), Old
.LIs
.end());
769 Result
.Is
.insert(Old
.Is
.begin(), Old
.Is
.end());
770 Result
.Is
.insert(BCI
);
771 Result
.SVI
= nullptr;
776 /// ShuffleVectorInst specialization to compute vector information.
778 /// \param SVI ShuffleVectorInst to operate on
779 /// \param Result Result of the computation
781 /// Compute the left and the right side vector information and merge them by
782 /// applying the shuffle operation. This function also ensures that the left
783 /// and right side have compatible loads. This means that all loads are with
784 /// in the same basic block and are based on the same pointer.
786 /// \returns false if no sensible information can be gathered.
787 static bool computeFromSVI(ShuffleVectorInst
*SVI
, VectorInfo
&Result
,
788 const DataLayout
&DL
) {
789 FixedVectorType
*ArgTy
=
790 cast
<FixedVectorType
>(SVI
->getOperand(0)->getType());
792 // Compute the left hand vector information.
793 VectorInfo
LHS(ArgTy
);
794 if (!compute(SVI
->getOperand(0), LHS
, DL
))
797 // Compute the right hand vector information.
798 VectorInfo
RHS(ArgTy
);
799 if (!compute(SVI
->getOperand(1), RHS
, DL
))
802 // Neither operand produced sensible results?
803 if (!LHS
.BB
&& !RHS
.BB
)
805 // Only RHS produced sensible results?
810 // Only LHS produced sensible results?
815 // Both operands produced sensible results?
816 else if ((LHS
.BB
== RHS
.BB
) && (LHS
.PV
== RHS
.PV
)) {
820 // Both operands produced sensible results but they are incompatible.
825 // Merge and apply the operation on the offset information.
827 Result
.LIs
.insert(LHS
.LIs
.begin(), LHS
.LIs
.end());
828 Result
.Is
.insert(LHS
.Is
.begin(), LHS
.Is
.end());
831 Result
.LIs
.insert(RHS
.LIs
.begin(), RHS
.LIs
.end());
832 Result
.Is
.insert(RHS
.Is
.begin(), RHS
.Is
.end());
834 Result
.Is
.insert(SVI
);
838 for (int i
: SVI
->getShuffleMask()) {
839 assert((i
< 2 * (signed)ArgTy
->getNumElements()) &&
840 "Invalid ShuffleVectorInst (index out of bounds)");
843 Result
.EI
[j
] = ElementInfo();
844 else if (i
< (signed)ArgTy
->getNumElements()) {
846 Result
.EI
[j
] = LHS
.EI
[i
];
848 Result
.EI
[j
] = ElementInfo();
851 Result
.EI
[j
] = RHS
.EI
[i
- ArgTy
->getNumElements()];
853 Result
.EI
[j
] = ElementInfo();
861 /// LoadInst specialization to compute vector information.
863 /// This function also acts as abort condition to the recursion.
865 /// \param LI LoadInst to operate on
866 /// \param Result Result of the computation
868 /// \returns false if no sensible information can be gathered.
869 static bool computeFromLI(LoadInst
*LI
, VectorInfo
&Result
,
870 const DataLayout
&DL
) {
874 if (LI
->isVolatile())
880 if (!DL
.typeSizeEqualsStoreSize(Result
.VTy
->getElementType()))
883 // Get the base polynomial
884 computePolynomialFromPointer(*LI
->getPointerOperand(), Offset
, BasePtr
, DL
);
886 Result
.BB
= LI
->getParent();
888 Result
.LIs
.insert(LI
);
889 Result
.Is
.insert(LI
);
891 for (unsigned i
= 0; i
< Result
.getDimension(); i
++) {
893 ConstantInt::get(Type::getInt32Ty(LI
->getContext()), 0),
894 ConstantInt::get(Type::getInt32Ty(LI
->getContext()), i
),
896 int64_t Ofs
= DL
.getIndexedOffsetInType(Result
.VTy
, Idx
);
897 Result
.EI
[i
] = ElementInfo(Offset
+ Ofs
, i
== 0 ? LI
: nullptr);
903 /// Recursively compute polynomial of a value.
905 /// \param BO Input binary operation
906 /// \param Result Result polynomial
907 static void computePolynomialBinOp(BinaryOperator
&BO
, Polynomial
&Result
) {
908 Value
*LHS
= BO
.getOperand(0);
909 Value
*RHS
= BO
.getOperand(1);
911 // Find the RHS Constant if any
912 ConstantInt
*C
= dyn_cast
<ConstantInt
>(RHS
);
913 if ((!C
) && BO
.isCommutative()) {
914 C
= dyn_cast
<ConstantInt
>(LHS
);
919 switch (BO
.getOpcode()) {
920 case Instruction::Add
:
924 computePolynomial(*LHS
, Result
);
925 Result
.add(C
->getValue());
928 case Instruction::LShr
:
932 computePolynomial(*LHS
, Result
);
933 Result
.lshr(C
->getValue());
940 Result
= Polynomial(&BO
);
943 /// Recursively compute polynomial of a value
945 /// \param V input value
946 /// \param Result result polynomial
947 static void computePolynomial(Value
&V
, Polynomial
&Result
) {
948 if (auto *BO
= dyn_cast
<BinaryOperator
>(&V
))
949 computePolynomialBinOp(*BO
, Result
);
951 Result
= Polynomial(&V
);
954 /// Compute the Polynomial representation of a Pointer type.
956 /// \param Ptr input pointer value
957 /// \param Result result polynomial
958 /// \param BasePtr pointer the polynomial is based on
959 /// \param DL Datalayout of the target machine
960 static void computePolynomialFromPointer(Value
&Ptr
, Polynomial
&Result
,
962 const DataLayout
&DL
) {
963 // Not a pointer type? Return an undefined polynomial
964 PointerType
*PtrTy
= dyn_cast
<PointerType
>(Ptr
.getType());
966 Result
= Polynomial();
970 unsigned PointerBits
=
971 DL
.getIndexSizeInBits(PtrTy
->getPointerAddressSpace());
973 /// Skip pointer casts. Return Zero polynomial otherwise
974 if (isa
<CastInst
>(&Ptr
)) {
975 CastInst
&CI
= *cast
<CastInst
>(&Ptr
);
976 switch (CI
.getOpcode()) {
977 case Instruction::BitCast
:
978 computePolynomialFromPointer(*CI
.getOperand(0), Result
, BasePtr
, DL
);
982 Polynomial(PointerBits
, 0);
986 /// Resolve GetElementPtrInst.
987 else if (isa
<GetElementPtrInst
>(&Ptr
)) {
988 GetElementPtrInst
&GEP
= *cast
<GetElementPtrInst
>(&Ptr
);
990 APInt
BaseOffset(PointerBits
, 0);
992 // Check if we can compute the Offset with accumulateConstantOffset
993 if (GEP
.accumulateConstantOffset(DL
, BaseOffset
)) {
994 Result
= Polynomial(BaseOffset
);
995 BasePtr
= GEP
.getPointerOperand();
998 // Otherwise we allow that the last index operand of the GEP is
1000 unsigned idxOperand
, e
;
1001 SmallVector
<Value
*, 4> Indices
;
1002 for (idxOperand
= 1, e
= GEP
.getNumOperands(); idxOperand
< e
;
1004 ConstantInt
*IDX
= dyn_cast
<ConstantInt
>(GEP
.getOperand(idxOperand
));
1007 Indices
.push_back(IDX
);
1010 // It must also be the last operand.
1011 if (idxOperand
+ 1 != e
) {
1012 Result
= Polynomial();
1017 // Compute the polynomial of the index operand.
1018 computePolynomial(*GEP
.getOperand(idxOperand
), Result
);
1020 // Compute base offset from zero based index, excluding the last
1021 // variable operand.
1023 DL
.getIndexedOffsetInType(GEP
.getSourceElementType(), Indices
);
1025 // Apply the operations of GEP to the polynomial.
1026 unsigned ResultSize
= DL
.getTypeAllocSize(GEP
.getResultElementType());
1027 Result
.sextOrTrunc(PointerBits
);
1028 Result
.mul(APInt(PointerBits
, ResultSize
));
1029 Result
.add(BaseOffset
);
1030 BasePtr
= GEP
.getPointerOperand();
1033 // All other instructions are handled by using the value as base pointer and
1034 // a zero polynomial.
1037 Polynomial(DL
.getIndexSizeInBits(PtrTy
->getPointerAddressSpace()), 0);
1042 void print(raw_ostream
&OS
) const {
1048 for (unsigned i
= 0; i
< getDimension(); i
++)
1049 OS
<< ((i
== 0) ? "[" : ", ") << EI
[i
].Ofs
;
1055 } // anonymous namespace
1057 bool InterleavedLoadCombineImpl::findPattern(
1058 std::list
<VectorInfo
> &Candidates
, std::list
<VectorInfo
> &InterleavedLoad
,
1059 unsigned Factor
, const DataLayout
&DL
) {
1060 for (auto C0
= Candidates
.begin(), E0
= Candidates
.end(); C0
!= E0
; ++C0
) {
1062 // Try to find an interleaved load using the front of Worklist as first line
1063 unsigned Size
= DL
.getTypeAllocSize(C0
->VTy
->getElementType());
1065 // List containing iterators pointing to the VectorInfos of the candidates
1066 std::vector
<std::list
<VectorInfo
>::iterator
> Res(Factor
, Candidates
.end());
1068 for (auto C
= Candidates
.begin(), E
= Candidates
.end(); C
!= E
; C
++) {
1069 if (C
->VTy
!= C0
->VTy
)
1071 if (C
->BB
!= C0
->BB
)
1073 if (C
->PV
!= C0
->PV
)
1076 // Check the current value matches any of factor - 1 remaining lines
1077 for (i
= 1; i
< Factor
; i
++) {
1078 if (C
->EI
[0].Ofs
.isProvenEqualTo(C0
->EI
[0].Ofs
+ i
* Size
)) {
1083 for (i
= 1; i
< Factor
; i
++) {
1084 if (Res
[i
] == Candidates
.end())
1093 if (Res
[0] != Candidates
.end()) {
1094 // Move the result into the output
1095 for (unsigned i
= 0; i
< Factor
; i
++) {
1096 InterleavedLoad
.splice(InterleavedLoad
.end(), Candidates
, Res
[i
]);
1106 InterleavedLoadCombineImpl::findFirstLoad(const std::set
<LoadInst
*> &LIs
) {
1107 assert(!LIs
.empty() && "No load instructions given.");
1109 // All LIs are within the same BB. Select the first for a reference.
1110 BasicBlock
*BB
= (*LIs
.begin())->getParent();
1111 BasicBlock::iterator FLI
= llvm::find_if(
1112 *BB
, [&LIs
](Instruction
&I
) -> bool { return is_contained(LIs
, &I
); });
1113 assert(FLI
!= BB
->end());
1115 return cast
<LoadInst
>(FLI
);
1118 bool InterleavedLoadCombineImpl::combine(std::list
<VectorInfo
> &InterleavedLoad
,
1119 OptimizationRemarkEmitter
&ORE
) {
1120 LLVM_DEBUG(dbgs() << "Checking interleaved load\n");
1122 // The insertion point is the LoadInst which loads the first values. The
1123 // following tests are used to proof that the combined load can be inserted
1124 // just before InsertionPoint.
1125 LoadInst
*InsertionPoint
= InterleavedLoad
.front().EI
[0].LI
;
1127 // Test if the offset is computed
1128 if (!InsertionPoint
)
1131 std::set
<LoadInst
*> LIs
;
1132 std::set
<Instruction
*> Is
;
1133 std::set
<Instruction
*> SVIs
;
1135 InstructionCost InterleavedCost
;
1136 InstructionCost InstructionCost
= 0;
1137 const TTI::TargetCostKind CostKind
= TTI::TCK_SizeAndLatency
;
1139 // Get the interleave factor
1140 unsigned Factor
= InterleavedLoad
.size();
1142 // Merge all input sets used in analysis
1143 for (auto &VI
: InterleavedLoad
) {
1144 // Generate a set of all load instructions to be combined
1145 LIs
.insert(VI
.LIs
.begin(), VI
.LIs
.end());
1147 // Generate a set of all instructions taking part in load
1148 // interleaved. This list excludes the instructions necessary for the
1149 // polynomial construction.
1150 Is
.insert(VI
.Is
.begin(), VI
.Is
.end());
1152 // Generate the set of the final ShuffleVectorInst.
1153 SVIs
.insert(VI
.SVI
);
1156 // There is nothing to combine.
1160 // Test if all participating instruction will be dead after the
1161 // transformation. If intermediate results are used, no performance gain can
1162 // be expected. Also sum the cost of the Instructions beeing left dead.
1163 for (const auto &I
: Is
) {
1164 // Compute the old cost
1165 InstructionCost
+= TTI
.getInstructionCost(I
, CostKind
);
1167 // The final SVIs are allowed not to be dead, all uses will be replaced
1168 if (SVIs
.find(I
) != SVIs
.end())
1171 // If there are users outside the set to be eliminated, we abort the
1172 // transformation. No gain can be expected.
1173 for (auto *U
: I
->users()) {
1174 if (Is
.find(dyn_cast
<Instruction
>(U
)) == Is
.end())
1179 // We need to have a valid cost in order to proceed.
1180 if (!InstructionCost
.isValid())
1183 // We know that all LoadInst are within the same BB. This guarantees that
1184 // either everything or nothing is loaded.
1185 LoadInst
*First
= findFirstLoad(LIs
);
1187 // To be safe that the loads can be combined, iterate over all loads and test
1188 // that the corresponding defining access dominates first LI. This guarantees
1189 // that there are no aliasing stores in between the loads.
1190 auto FMA
= MSSA
.getMemoryAccess(First
);
1191 for (auto *LI
: LIs
) {
1192 auto MADef
= MSSA
.getMemoryAccess(LI
)->getDefiningAccess();
1193 if (!MSSA
.dominates(MADef
, FMA
))
1196 assert(!LIs
.empty() && "There are no LoadInst to combine");
1198 // It is necessary that insertion point dominates all final ShuffleVectorInst.
1199 for (auto &VI
: InterleavedLoad
) {
1200 if (!DT
.dominates(InsertionPoint
, VI
.SVI
))
1204 // All checks are done. Add instructions detectable by InterleavedAccessPass
1205 // The old instruction will are left dead.
1206 IRBuilder
<> Builder(InsertionPoint
);
1207 Type
*ETy
= InterleavedLoad
.front().SVI
->getType()->getElementType();
1208 unsigned ElementsPerSVI
=
1209 cast
<FixedVectorType
>(InterleavedLoad
.front().SVI
->getType())
1211 FixedVectorType
*ILTy
= FixedVectorType::get(ETy
, Factor
* ElementsPerSVI
);
1213 auto Indices
= llvm::to_vector
<4>(llvm::seq
<unsigned>(0, Factor
));
1214 InterleavedCost
= TTI
.getInterleavedMemoryOpCost(
1215 Instruction::Load
, ILTy
, Factor
, Indices
, InsertionPoint
->getAlign(),
1216 InsertionPoint
->getPointerAddressSpace(), CostKind
);
1218 if (InterleavedCost
>= InstructionCost
) {
1222 // Create the wide load and update the MemorySSA.
1223 auto Ptr
= InsertionPoint
->getPointerOperand();
1224 auto LI
= Builder
.CreateAlignedLoad(ILTy
, Ptr
, InsertionPoint
->getAlign(),
1225 "interleaved.wide.load");
1226 auto MSSAU
= MemorySSAUpdater(&MSSA
);
1227 MemoryUse
*MSSALoad
= cast
<MemoryUse
>(MSSAU
.createMemoryAccessBefore(
1228 LI
, nullptr, MSSA
.getMemoryAccess(InsertionPoint
)));
1229 MSSAU
.insertUse(MSSALoad
, /*RenameUses=*/ true);
1231 // Create the final SVIs and replace all uses.
1233 for (auto &VI
: InterleavedLoad
) {
1234 SmallVector
<int, 4> Mask
;
1235 for (unsigned j
= 0; j
< ElementsPerSVI
; j
++)
1236 Mask
.push_back(i
+ j
* Factor
);
1238 Builder
.SetInsertPoint(VI
.SVI
);
1239 auto SVI
= Builder
.CreateShuffleVector(LI
, Mask
, "interleaved.shuffle");
1240 VI
.SVI
->replaceAllUsesWith(SVI
);
1244 NumInterleavedLoadCombine
++;
1246 return OptimizationRemark(DEBUG_TYPE
, "Combined Interleaved Load", LI
)
1247 << "Load interleaved combined with factor "
1248 << ore::NV("Factor", Factor
);
1254 bool InterleavedLoadCombineImpl::run() {
1255 OptimizationRemarkEmitter
ORE(&F
);
1256 bool changed
= false;
1257 unsigned MaxFactor
= TLI
.getMaxSupportedInterleaveFactor();
1259 auto &DL
= F
.getDataLayout();
1261 // Start with the highest factor to avoid combining and recombining.
1262 for (unsigned Factor
= MaxFactor
; Factor
>= 2; Factor
--) {
1263 std::list
<VectorInfo
> Candidates
;
1265 for (BasicBlock
&BB
: F
) {
1266 for (Instruction
&I
: BB
) {
1267 if (auto SVI
= dyn_cast
<ShuffleVectorInst
>(&I
)) {
1268 // We don't support scalable vectors in this pass.
1269 if (isa
<ScalableVectorType
>(SVI
->getType()))
1272 Candidates
.emplace_back(cast
<FixedVectorType
>(SVI
->getType()));
1274 if (!VectorInfo::computeFromSVI(SVI
, Candidates
.back(), DL
)) {
1275 Candidates
.pop_back();
1279 if (!Candidates
.back().isInterleaved(Factor
, DL
)) {
1280 Candidates
.pop_back();
1286 std::list
<VectorInfo
> InterleavedLoad
;
1287 while (findPattern(Candidates
, InterleavedLoad
, Factor
, DL
)) {
1288 if (combine(InterleavedLoad
, ORE
)) {
1291 // Remove the first element of the Interleaved Load but put the others
1292 // back on the list and continue searching
1293 Candidates
.splice(Candidates
.begin(), InterleavedLoad
,
1294 std::next(InterleavedLoad
.begin()),
1295 InterleavedLoad
.end());
1297 InterleavedLoad
.clear();
1305 /// This pass combines interleaved loads into a pattern detectable by
1306 /// InterleavedAccessPass.
1307 struct InterleavedLoadCombine
: public FunctionPass
{
1310 InterleavedLoadCombine() : FunctionPass(ID
) {
1311 initializeInterleavedLoadCombinePass(*PassRegistry::getPassRegistry());
1314 StringRef
getPassName() const override
{
1315 return "Interleaved Load Combine Pass";
1318 bool runOnFunction(Function
&F
) override
{
1319 if (DisableInterleavedLoadCombine
)
1322 auto *TPC
= getAnalysisIfAvailable
<TargetPassConfig
>();
1326 LLVM_DEBUG(dbgs() << "*** " << getPassName() << ": " << F
.getName()
1329 return InterleavedLoadCombineImpl(
1330 F
, getAnalysis
<DominatorTreeWrapperPass
>().getDomTree(),
1331 getAnalysis
<MemorySSAWrapperPass
>().getMSSA(),
1332 getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
),
1333 TPC
->getTM
<TargetMachine
>())
1337 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
1338 AU
.addRequired
<MemorySSAWrapperPass
>();
1339 AU
.addRequired
<DominatorTreeWrapperPass
>();
1340 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
1341 FunctionPass::getAnalysisUsage(AU
);
1346 } // anonymous namespace
1349 InterleavedLoadCombinePass::run(Function
&F
, FunctionAnalysisManager
&FAM
) {
1351 auto &DT
= FAM
.getResult
<DominatorTreeAnalysis
>(F
);
1352 auto &MemSSA
= FAM
.getResult
<MemorySSAAnalysis
>(F
).getMSSA();
1353 auto &TTI
= FAM
.getResult
<TargetIRAnalysis
>(F
);
1354 bool Changed
= InterleavedLoadCombineImpl(F
, DT
, MemSSA
, TTI
, *TM
).run();
1355 return Changed
? PreservedAnalyses::none() : PreservedAnalyses::all();
1358 char InterleavedLoadCombine::ID
= 0;
1360 INITIALIZE_PASS_BEGIN(
1361 InterleavedLoadCombine
, DEBUG_TYPE
,
1362 "Combine interleaved loads into wide loads and shufflevector instructions",
1364 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
1365 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass
)
1366 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
1367 INITIALIZE_PASS_END(
1368 InterleavedLoadCombine
, DEBUG_TYPE
,
1369 "Combine interleaved loads into wide loads and shufflevector instructions",
1373 llvm::createInterleavedLoadCombinePass() {
1374 auto P
= new InterleavedLoadCombine();