1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
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 //===----------------------------------------------------------------------===//
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/CodeMetrics.h"
37 #include "llvm/Analysis/DemandedBits.h"
38 #include "llvm/Analysis/GlobalsModRef.h"
39 #include "llvm/Analysis/LoopAccessAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryLocation.h"
42 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
43 #include "llvm/Analysis/ScalarEvolution.h"
44 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
45 #include "llvm/Analysis/TargetLibraryInfo.h"
46 #include "llvm/Analysis/TargetTransformInfo.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Analysis/VectorUtils.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/Constant.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/IRBuilder.h"
59 #include "llvm/IR/InstrTypes.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/Intrinsics.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/NoFolder.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PassManager.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #include "llvm/IR/Verifier.h"
75 #include "llvm/Pass.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/DOTGraphTraits.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/GraphWriter.h"
83 #include "llvm/Support/KnownBits.h"
84 #include "llvm/Support/MathExtras.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Transforms/Utils/LoopUtils.h"
87 #include "llvm/Transforms/Vectorize.h"
100 using namespace llvm::PatternMatch
;
101 using namespace slpvectorizer
;
103 #define SV_NAME "slp-vectorizer"
104 #define DEBUG_TYPE "SLP"
106 STATISTIC(NumVectorInstructions
, "Number of vector instructions generated");
109 llvm::RunSLPVectorization("vectorize-slp", cl::init(false), cl::Hidden
,
110 cl::desc("Run the SLP vectorization passes"));
113 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden
,
114 cl::desc("Only vectorize if you gain more than this "
118 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden
,
119 cl::desc("Attempt to vectorize horizontal reductions"));
121 static cl::opt
<bool> ShouldStartVectorizeHorAtStore(
122 "slp-vectorize-hor-store", cl::init(false), cl::Hidden
,
124 "Attempt to vectorize horizontal reductions feeding into a store"));
127 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden
,
128 cl::desc("Attempt to vectorize for this register size in bits"));
130 /// Limits the size of scheduling regions in a block.
131 /// It avoid long compile times for _very_ large blocks where vector
132 /// instructions are spread over a wide range.
133 /// This limit is way higher than needed by real-world functions.
135 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden
,
136 cl::desc("Limit the size of the SLP scheduling region per block"));
138 static cl::opt
<int> MinVectorRegSizeOption(
139 "slp-min-reg-size", cl::init(128), cl::Hidden
,
140 cl::desc("Attempt to vectorize for this register size in bits"));
142 static cl::opt
<unsigned> RecursionMaxDepth(
143 "slp-recursion-max-depth", cl::init(12), cl::Hidden
,
144 cl::desc("Limit the recursion depth when building a vectorizable tree"));
146 static cl::opt
<unsigned> MinTreeSize(
147 "slp-min-tree-size", cl::init(3), cl::Hidden
,
148 cl::desc("Only vectorize small trees if they are fully vectorizable"));
151 ViewSLPTree("view-slp-tree", cl::Hidden
,
152 cl::desc("Display the SLP trees with Graphviz"));
154 // Limit the number of alias checks. The limit is chosen so that
155 // it has no negative effect on the llvm benchmarks.
156 static const unsigned AliasedCheckLimit
= 10;
158 // Another limit for the alias checks: The maximum distance between load/store
159 // instructions where alias checks are done.
160 // This limit is useful for very large basic blocks.
161 static const unsigned MaxMemDepDistance
= 160;
163 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
164 /// regions to be handled.
165 static const int MinScheduleRegionSize
= 16;
167 /// Predicate for the element types that the SLP vectorizer supports.
169 /// The most important thing to filter here are types which are invalid in LLVM
170 /// vectors. We also filter target specific types which have absolutely no
171 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
172 /// avoids spending time checking the cost model and realizing that they will
173 /// be inevitably scalarized.
174 static bool isValidElementType(Type
*Ty
) {
175 return VectorType::isValidElementType(Ty
) && !Ty
->isX86_FP80Ty() &&
176 !Ty
->isPPC_FP128Ty();
179 /// \returns true if all of the instructions in \p VL are in the same block or
181 static bool allSameBlock(ArrayRef
<Value
*> VL
) {
182 Instruction
*I0
= dyn_cast
<Instruction
>(VL
[0]);
185 BasicBlock
*BB
= I0
->getParent();
186 for (int i
= 1, e
= VL
.size(); i
< e
; i
++) {
187 Instruction
*I
= dyn_cast
<Instruction
>(VL
[i
]);
191 if (BB
!= I
->getParent())
197 /// \returns True if all of the values in \p VL are constants (but not
198 /// globals/constant expressions).
199 static bool allConstant(ArrayRef
<Value
*> VL
) {
200 // Constant expressions and globals can't be vectorized like normal integer/FP
203 if (!isa
<Constant
>(i
) || isa
<ConstantExpr
>(i
) || isa
<GlobalValue
>(i
))
208 /// \returns True if all of the values in \p VL are identical.
209 static bool isSplat(ArrayRef
<Value
*> VL
) {
210 for (unsigned i
= 1, e
= VL
.size(); i
< e
; ++i
)
216 /// \returns True if \p I is commutative, handles CmpInst as well as Instruction.
217 static bool isCommutative(Instruction
*I
) {
218 if (auto *IC
= dyn_cast
<CmpInst
>(I
))
219 return IC
->isCommutative();
220 return I
->isCommutative();
223 /// Checks if the vector of instructions can be represented as a shuffle, like:
224 /// %x0 = extractelement <4 x i8> %x, i32 0
225 /// %x3 = extractelement <4 x i8> %x, i32 3
226 /// %y1 = extractelement <4 x i8> %y, i32 1
227 /// %y2 = extractelement <4 x i8> %y, i32 2
228 /// %x0x0 = mul i8 %x0, %x0
229 /// %x3x3 = mul i8 %x3, %x3
230 /// %y1y1 = mul i8 %y1, %y1
231 /// %y2y2 = mul i8 %y2, %y2
232 /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
233 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
234 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
235 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
236 /// ret <4 x i8> %ins4
237 /// can be transformed into:
238 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
240 /// %2 = mul <4 x i8> %1, %1
242 /// We convert this initially to something like:
243 /// %x0 = extractelement <4 x i8> %x, i32 0
244 /// %x3 = extractelement <4 x i8> %x, i32 3
245 /// %y1 = extractelement <4 x i8> %y, i32 1
246 /// %y2 = extractelement <4 x i8> %y, i32 2
247 /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
248 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
249 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
250 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
251 /// %5 = mul <4 x i8> %4, %4
252 /// %6 = extractelement <4 x i8> %5, i32 0
253 /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
254 /// %7 = extractelement <4 x i8> %5, i32 1
255 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
256 /// %8 = extractelement <4 x i8> %5, i32 2
257 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
258 /// %9 = extractelement <4 x i8> %5, i32 3
259 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
260 /// ret <4 x i8> %ins4
261 /// InstCombiner transforms this into a shuffle and vector mul
262 /// TODO: Can we split off and reuse the shuffle mask detection from
263 /// TargetTransformInfo::getInstructionThroughput?
264 static Optional
<TargetTransformInfo::ShuffleKind
>
265 isShuffle(ArrayRef
<Value
*> VL
) {
266 auto *EI0
= cast
<ExtractElementInst
>(VL
[0]);
267 unsigned Size
= EI0
->getVectorOperandType()->getVectorNumElements();
268 Value
*Vec1
= nullptr;
269 Value
*Vec2
= nullptr;
270 enum ShuffleMode
{ Unknown
, Select
, Permute
};
271 ShuffleMode CommonShuffleMode
= Unknown
;
272 for (unsigned I
= 0, E
= VL
.size(); I
< E
; ++I
) {
273 auto *EI
= cast
<ExtractElementInst
>(VL
[I
]);
274 auto *Vec
= EI
->getVectorOperand();
275 // All vector operands must have the same number of vector elements.
276 if (Vec
->getType()->getVectorNumElements() != Size
)
278 auto *Idx
= dyn_cast
<ConstantInt
>(EI
->getIndexOperand());
281 // Undefined behavior if Idx is negative or >= Size.
282 if (Idx
->getValue().uge(Size
))
284 unsigned IntIdx
= Idx
->getValue().getZExtValue();
285 // We can extractelement from undef vector.
286 if (isa
<UndefValue
>(Vec
))
288 // For correct shuffling we have to have at most 2 different vector operands
289 // in all extractelement instructions.
290 if (!Vec1
|| Vec1
== Vec
)
292 else if (!Vec2
|| Vec2
== Vec
)
296 if (CommonShuffleMode
== Permute
)
298 // If the extract index is not the same as the operation number, it is a
301 CommonShuffleMode
= Permute
;
304 CommonShuffleMode
= Select
;
306 // If we're not crossing lanes in different vectors, consider it as blending.
307 if (CommonShuffleMode
== Select
&& Vec2
)
308 return TargetTransformInfo::SK_Select
;
309 // If Vec2 was never used, we have a permutation of a single vector, otherwise
310 // we have permutation of 2 vectors.
311 return Vec2
? TargetTransformInfo::SK_PermuteTwoSrc
312 : TargetTransformInfo::SK_PermuteSingleSrc
;
317 /// Main data required for vectorization of instructions.
318 struct InstructionsState
{
319 /// The very first instruction in the list with the main opcode.
320 Value
*OpValue
= nullptr;
322 /// The main/alternate instruction.
323 Instruction
*MainOp
= nullptr;
324 Instruction
*AltOp
= nullptr;
326 /// The main/alternate opcodes for the list of instructions.
327 unsigned getOpcode() const {
328 return MainOp
? MainOp
->getOpcode() : 0;
331 unsigned getAltOpcode() const {
332 return AltOp
? AltOp
->getOpcode() : 0;
335 /// Some of the instructions in the list have alternate opcodes.
336 bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
338 bool isOpcodeOrAlt(Instruction
*I
) const {
339 unsigned CheckedOpcode
= I
->getOpcode();
340 return getOpcode() == CheckedOpcode
|| getAltOpcode() == CheckedOpcode
;
343 InstructionsState() = delete;
344 InstructionsState(Value
*OpValue
, Instruction
*MainOp
, Instruction
*AltOp
)
345 : OpValue(OpValue
), MainOp(MainOp
), AltOp(AltOp
) {}
348 } // end anonymous namespace
350 /// Chooses the correct key for scheduling data. If \p Op has the same (or
351 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
353 static Value
*isOneOf(const InstructionsState
&S
, Value
*Op
) {
354 auto *I
= dyn_cast
<Instruction
>(Op
);
355 if (I
&& S
.isOpcodeOrAlt(I
))
360 /// \returns analysis of the Instructions in \p VL described in
361 /// InstructionsState, the Opcode that we suppose the whole list
362 /// could be vectorized even if its structure is diverse.
363 static InstructionsState
getSameOpcode(ArrayRef
<Value
*> VL
,
364 unsigned BaseIndex
= 0) {
365 // Make sure these are all Instructions.
366 if (llvm::any_of(VL
, [](Value
*V
) { return !isa
<Instruction
>(V
); }))
367 return InstructionsState(VL
[BaseIndex
], nullptr, nullptr);
369 bool IsCastOp
= isa
<CastInst
>(VL
[BaseIndex
]);
370 bool IsBinOp
= isa
<BinaryOperator
>(VL
[BaseIndex
]);
371 unsigned Opcode
= cast
<Instruction
>(VL
[BaseIndex
])->getOpcode();
372 unsigned AltOpcode
= Opcode
;
373 unsigned AltIndex
= BaseIndex
;
375 // Check for one alternate opcode from another BinaryOperator.
376 // TODO - generalize to support all operators (types, calls etc.).
377 for (int Cnt
= 0, E
= VL
.size(); Cnt
< E
; Cnt
++) {
378 unsigned InstOpcode
= cast
<Instruction
>(VL
[Cnt
])->getOpcode();
379 if (IsBinOp
&& isa
<BinaryOperator
>(VL
[Cnt
])) {
380 if (InstOpcode
== Opcode
|| InstOpcode
== AltOpcode
)
382 if (Opcode
== AltOpcode
) {
383 AltOpcode
= InstOpcode
;
387 } else if (IsCastOp
&& isa
<CastInst
>(VL
[Cnt
])) {
388 Type
*Ty0
= cast
<Instruction
>(VL
[BaseIndex
])->getOperand(0)->getType();
389 Type
*Ty1
= cast
<Instruction
>(VL
[Cnt
])->getOperand(0)->getType();
391 if (InstOpcode
== Opcode
|| InstOpcode
== AltOpcode
)
393 if (Opcode
== AltOpcode
) {
394 AltOpcode
= InstOpcode
;
399 } else if (InstOpcode
== Opcode
|| InstOpcode
== AltOpcode
)
401 return InstructionsState(VL
[BaseIndex
], nullptr, nullptr);
404 return InstructionsState(VL
[BaseIndex
], cast
<Instruction
>(VL
[BaseIndex
]),
405 cast
<Instruction
>(VL
[AltIndex
]));
408 /// \returns true if all of the values in \p VL have the same type or false
410 static bool allSameType(ArrayRef
<Value
*> VL
) {
411 Type
*Ty
= VL
[0]->getType();
412 for (int i
= 1, e
= VL
.size(); i
< e
; i
++)
413 if (VL
[i
]->getType() != Ty
)
419 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
420 static Optional
<unsigned> getExtractIndex(Instruction
*E
) {
421 unsigned Opcode
= E
->getOpcode();
422 assert((Opcode
== Instruction::ExtractElement
||
423 Opcode
== Instruction::ExtractValue
) &&
424 "Expected extractelement or extractvalue instruction.");
425 if (Opcode
== Instruction::ExtractElement
) {
426 auto *CI
= dyn_cast
<ConstantInt
>(E
->getOperand(1));
429 return CI
->getZExtValue();
431 ExtractValueInst
*EI
= cast
<ExtractValueInst
>(E
);
432 if (EI
->getNumIndices() != 1)
434 return *EI
->idx_begin();
437 /// \returns True if in-tree use also needs extract. This refers to
438 /// possible scalar operand in vectorized instruction.
439 static bool InTreeUserNeedToExtract(Value
*Scalar
, Instruction
*UserInst
,
440 TargetLibraryInfo
*TLI
) {
441 unsigned Opcode
= UserInst
->getOpcode();
443 case Instruction::Load
: {
444 LoadInst
*LI
= cast
<LoadInst
>(UserInst
);
445 return (LI
->getPointerOperand() == Scalar
);
447 case Instruction::Store
: {
448 StoreInst
*SI
= cast
<StoreInst
>(UserInst
);
449 return (SI
->getPointerOperand() == Scalar
);
451 case Instruction::Call
: {
452 CallInst
*CI
= cast
<CallInst
>(UserInst
);
453 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
454 for (unsigned i
= 0, e
= CI
->getNumArgOperands(); i
!= e
; ++i
) {
455 if (hasVectorInstrinsicScalarOpd(ID
, i
))
456 return (CI
->getArgOperand(i
) == Scalar
);
465 /// \returns the AA location that is being access by the instruction.
466 static MemoryLocation
getLocation(Instruction
*I
, AliasAnalysis
*AA
) {
467 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(I
))
468 return MemoryLocation::get(SI
);
469 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
))
470 return MemoryLocation::get(LI
);
471 return MemoryLocation();
474 /// \returns True if the instruction is not a volatile or atomic load/store.
475 static bool isSimple(Instruction
*I
) {
476 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
))
477 return LI
->isSimple();
478 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(I
))
479 return SI
->isSimple();
480 if (MemIntrinsic
*MI
= dyn_cast
<MemIntrinsic
>(I
))
481 return !MI
->isVolatile();
487 namespace slpvectorizer
{
489 /// Bottom Up SLP Vectorizer.
495 using ValueList
= SmallVector
<Value
*, 8>;
496 using InstrList
= SmallVector
<Instruction
*, 16>;
497 using ValueSet
= SmallPtrSet
<Value
*, 16>;
498 using StoreList
= SmallVector
<StoreInst
*, 8>;
499 using ExtraValueToDebugLocsMap
=
500 MapVector
<Value
*, SmallVector
<Instruction
*, 2>>;
502 BoUpSLP(Function
*Func
, ScalarEvolution
*Se
, TargetTransformInfo
*Tti
,
503 TargetLibraryInfo
*TLi
, AliasAnalysis
*Aa
, LoopInfo
*Li
,
504 DominatorTree
*Dt
, AssumptionCache
*AC
, DemandedBits
*DB
,
505 const DataLayout
*DL
, OptimizationRemarkEmitter
*ORE
)
506 : F(Func
), SE(Se
), TTI(Tti
), TLI(TLi
), AA(Aa
), LI(Li
), DT(Dt
), AC(AC
),
507 DB(DB
), DL(DL
), ORE(ORE
), Builder(Se
->getContext()) {
508 CodeMetrics::collectEphemeralValues(F
, AC
, EphValues
);
509 // Use the vector register size specified by the target unless overridden
510 // by a command-line option.
511 // TODO: It would be better to limit the vectorization factor based on
512 // data type rather than just register size. For example, x86 AVX has
513 // 256-bit registers, but it does not support integer operations
514 // at that width (that requires AVX2).
515 if (MaxVectorRegSizeOption
.getNumOccurrences())
516 MaxVecRegSize
= MaxVectorRegSizeOption
;
518 MaxVecRegSize
= TTI
->getRegisterBitWidth(true);
520 if (MinVectorRegSizeOption
.getNumOccurrences())
521 MinVecRegSize
= MinVectorRegSizeOption
;
523 MinVecRegSize
= TTI
->getMinVectorRegisterBitWidth();
526 /// Vectorize the tree that starts with the elements in \p VL.
527 /// Returns the vectorized root.
528 Value
*vectorizeTree();
530 /// Vectorize the tree but with the list of externally used values \p
531 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
532 /// generated extractvalue instructions.
533 Value
*vectorizeTree(ExtraValueToDebugLocsMap
&ExternallyUsedValues
);
535 /// \returns the cost incurred by unwanted spills and fills, caused by
536 /// holding live values over call sites.
537 int getSpillCost() const;
539 /// \returns the vectorization cost of the subtree that starts at \p VL.
540 /// A negative number means that this is profitable.
543 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
544 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
545 void buildTree(ArrayRef
<Value
*> Roots
,
546 ArrayRef
<Value
*> UserIgnoreLst
= None
);
548 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
549 /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
550 /// into account (anf updating it, if required) list of externally used
551 /// values stored in \p ExternallyUsedValues.
552 void buildTree(ArrayRef
<Value
*> Roots
,
553 ExtraValueToDebugLocsMap
&ExternallyUsedValues
,
554 ArrayRef
<Value
*> UserIgnoreLst
= None
);
556 /// Clear the internal data structures that are created by 'buildTree'.
558 VectorizableTree
.clear();
559 ScalarToTreeEntry
.clear();
561 ExternalUses
.clear();
562 NumOpsWantToKeepOrder
.clear();
563 NumOpsWantToKeepOriginalOrder
= 0;
564 for (auto &Iter
: BlocksSchedules
) {
565 BlockScheduling
*BS
= Iter
.second
.get();
571 unsigned getTreeSize() const { return VectorizableTree
.size(); }
573 /// Perform LICM and CSE on the newly generated gather sequences.
574 void optimizeGatherSequence();
576 /// \returns The best order of instructions for vectorization.
577 Optional
<ArrayRef
<unsigned>> bestOrder() const {
578 auto I
= std::max_element(
579 NumOpsWantToKeepOrder
.begin(), NumOpsWantToKeepOrder
.end(),
580 [](const decltype(NumOpsWantToKeepOrder
)::value_type
&D1
,
581 const decltype(NumOpsWantToKeepOrder
)::value_type
&D2
) {
582 return D1
.second
< D2
.second
;
584 if (I
== NumOpsWantToKeepOrder
.end() ||
585 I
->getSecond() <= NumOpsWantToKeepOriginalOrder
)
588 return makeArrayRef(I
->getFirst());
591 /// \return The vector element size in bits to use when vectorizing the
592 /// expression tree ending at \p V. If V is a store, the size is the width of
593 /// the stored value. Otherwise, the size is the width of the largest loaded
594 /// value reaching V. This method is used by the vectorizer to calculate
595 /// vectorization factors.
596 unsigned getVectorElementSize(Value
*V
) const;
598 /// Compute the minimum type sizes required to represent the entries in a
599 /// vectorizable tree.
600 void computeMinimumValueSizes();
602 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
603 unsigned getMaxVecRegSize() const {
604 return MaxVecRegSize
;
607 // \returns minimum vector register size as set by cl::opt.
608 unsigned getMinVecRegSize() const {
609 return MinVecRegSize
;
612 /// Check if ArrayType or StructType is isomorphic to some VectorType.
614 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
615 unsigned canMapToVector(Type
*T
, const DataLayout
&DL
) const;
617 /// \returns True if the VectorizableTree is both tiny and not fully
618 /// vectorizable. We do not vectorize such trees.
619 bool isTreeTinyAndNotFullyVectorizable() const;
621 OptimizationRemarkEmitter
*getORE() { return ORE
; }
623 /// This structure holds any data we need about the edges being traversed
624 /// during buildTree_rec(). We keep track of:
625 /// (i) the user TreeEntry index, and
626 /// (ii) the index of the edge.
628 EdgeInfo() = default;
629 EdgeInfo(TreeEntry
*UserTE
, unsigned EdgeIdx
)
630 : UserTE(UserTE
), EdgeIdx(EdgeIdx
) {}
631 /// The user TreeEntry.
632 TreeEntry
*UserTE
= nullptr;
633 /// The operand index of the use.
634 unsigned EdgeIdx
= UINT_MAX
;
636 friend inline raw_ostream
&operator<<(raw_ostream
&OS
,
637 const BoUpSLP::EdgeInfo
&EI
) {
642 void dump(raw_ostream
&OS
) const {
643 OS
<< "{User:" << (UserTE
? std::to_string(UserTE
->Idx
) : "null")
644 << " EdgeIdx:" << EdgeIdx
<< "}";
646 LLVM_DUMP_METHOD
void dump() const { dump(dbgs()); }
650 /// A helper data structure to hold the operands of a vector of instructions.
651 /// This supports a fixed vector length for all operand vectors.
653 /// For each operand we need (i) the value, and (ii) the opcode that it
654 /// would be attached to if the expression was in a left-linearized form.
655 /// This is required to avoid illegal operand reordering.
660 /// Op1 Op2 Linearized + Op2
661 /// \ / ----------> |/
664 /// Op1 - Op2 (0 + Op1) - Op2
667 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
669 /// Another way to think of this is to track all the operations across the
670 /// path from the operand all the way to the root of the tree and to
671 /// calculate the operation that corresponds to this path. For example, the
672 /// path from Op2 to the root crosses the RHS of the '-', therefore the
673 /// corresponding operation is a '-' (which matches the one in the
674 /// linearized tree, as shown above).
676 /// For lack of a better term, we refer to this operation as Accumulated
677 /// Path Operation (APO).
679 OperandData() = default;
680 OperandData(Value
*V
, bool APO
, bool IsUsed
)
681 : V(V
), APO(APO
), IsUsed(IsUsed
) {}
682 /// The operand value.
684 /// TreeEntries only allow a single opcode, or an alternate sequence of
685 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
686 /// APO. It is set to 'true' if 'V' is attached to an inverse operation
687 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
690 /// Helper data for the reordering function.
694 /// During operand reordering, we are trying to select the operand at lane
695 /// that matches best with the operand at the neighboring lane. Our
696 /// selection is based on the type of value we are looking for. For example,
697 /// if the neighboring lane has a load, we need to look for a load that is
698 /// accessing a consecutive address. These strategies are summarized in the
699 /// 'ReorderingMode' enumerator.
700 enum class ReorderingMode
{
701 Load
, ///< Matching loads to consecutive memory addresses
702 Opcode
, ///< Matching instructions based on opcode (same or alternate)
703 Constant
, ///< Matching constants
704 Splat
, ///< Matching the same instruction multiple times (broadcast)
705 Failed
, ///< We failed to create a vectorizable group
708 using OperandDataVec
= SmallVector
<OperandData
, 2>;
710 /// A vector of operand vectors.
711 SmallVector
<OperandDataVec
, 4> OpsVec
;
713 const DataLayout
&DL
;
716 /// \returns the operand data at \p OpIdx and \p Lane.
717 OperandData
&getData(unsigned OpIdx
, unsigned Lane
) {
718 return OpsVec
[OpIdx
][Lane
];
721 /// \returns the operand data at \p OpIdx and \p Lane. Const version.
722 const OperandData
&getData(unsigned OpIdx
, unsigned Lane
) const {
723 return OpsVec
[OpIdx
][Lane
];
726 /// Clears the used flag for all entries.
728 for (unsigned OpIdx
= 0, NumOperands
= getNumOperands();
729 OpIdx
!= NumOperands
; ++OpIdx
)
730 for (unsigned Lane
= 0, NumLanes
= getNumLanes(); Lane
!= NumLanes
;
732 OpsVec
[OpIdx
][Lane
].IsUsed
= false;
735 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
736 void swap(unsigned OpIdx1
, unsigned OpIdx2
, unsigned Lane
) {
737 std::swap(OpsVec
[OpIdx1
][Lane
], OpsVec
[OpIdx2
][Lane
]);
740 // Search all operands in Ops[*][Lane] for the one that matches best
741 // Ops[OpIdx][LastLane] and return its opreand index.
742 // If no good match can be found, return None.
744 getBestOperand(unsigned OpIdx
, int Lane
, int LastLane
,
745 ArrayRef
<ReorderingMode
> ReorderingModes
) {
746 unsigned NumOperands
= getNumOperands();
748 // The operand of the previous lane at OpIdx.
749 Value
*OpLastLane
= getData(OpIdx
, LastLane
).V
;
751 // Our strategy mode for OpIdx.
752 ReorderingMode RMode
= ReorderingModes
[OpIdx
];
754 // The linearized opcode of the operand at OpIdx, Lane.
755 bool OpIdxAPO
= getData(OpIdx
, Lane
).APO
;
757 const unsigned BestScore
= 2;
758 const unsigned GoodScore
= 1;
760 // The best operand index and its score.
761 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
762 // are using the score to differentiate between the two.
764 Optional
<unsigned> Idx
= None
;
768 // Iterate through all unused operands and look for the best.
769 for (unsigned Idx
= 0; Idx
!= NumOperands
; ++Idx
) {
770 // Get the operand at Idx and Lane.
771 OperandData
&OpData
= getData(Idx
, Lane
);
772 Value
*Op
= OpData
.V
;
773 bool OpAPO
= OpData
.APO
;
775 // Skip already selected operands.
779 // Skip if we are trying to move the operand to a position with a
780 // different opcode in the linearized tree form. This would break the
782 if (OpAPO
!= OpIdxAPO
)
785 // Look for an operand that matches the current mode.
787 case ReorderingMode::Load
:
788 if (isa
<LoadInst
>(Op
)) {
789 // Figure out which is left and right, so that we can check for
791 bool LeftToRight
= Lane
> LastLane
;
792 Value
*OpLeft
= (LeftToRight
) ? OpLastLane
: Op
;
793 Value
*OpRight
= (LeftToRight
) ? Op
: OpLastLane
;
794 if (isConsecutiveAccess(cast
<LoadInst
>(OpLeft
),
795 cast
<LoadInst
>(OpRight
), DL
, SE
))
799 case ReorderingMode::Opcode
:
800 // We accept both Instructions and Undefs, but with different scores.
801 if ((isa
<Instruction
>(Op
) && isa
<Instruction
>(OpLastLane
) &&
802 cast
<Instruction
>(Op
)->getOpcode() ==
803 cast
<Instruction
>(OpLastLane
)->getOpcode()) ||
804 (isa
<UndefValue
>(OpLastLane
) && isa
<Instruction
>(Op
)) ||
805 isa
<UndefValue
>(Op
)) {
806 // An instruction has a higher score than an undef.
807 unsigned Score
= (isa
<UndefValue
>(Op
)) ? GoodScore
: BestScore
;
808 if (Score
> BestOp
.Score
) {
810 BestOp
.Score
= Score
;
814 case ReorderingMode::Constant
:
815 if (isa
<Constant
>(Op
)) {
816 unsigned Score
= (isa
<UndefValue
>(Op
)) ? GoodScore
: BestScore
;
817 if (Score
> BestOp
.Score
) {
819 BestOp
.Score
= Score
;
823 case ReorderingMode::Splat
:
824 if (Op
== OpLastLane
)
827 case ReorderingMode::Failed
:
833 getData(BestOp
.Idx
.getValue(), Lane
).IsUsed
= true;
836 // If we could not find a good match return None.
840 /// Helper for reorderOperandVecs. \Returns the lane that we should start
841 /// reordering from. This is the one which has the least number of operands
842 /// that can freely move about.
843 unsigned getBestLaneToStartReordering() const {
844 unsigned BestLane
= 0;
845 unsigned Min
= UINT_MAX
;
846 for (unsigned Lane
= 0, NumLanes
= getNumLanes(); Lane
!= NumLanes
;
848 unsigned NumFreeOps
= getMaxNumOperandsThatCanBeReordered(Lane
);
849 if (NumFreeOps
< Min
) {
857 /// \Returns the maximum number of operands that are allowed to be reordered
858 /// for \p Lane. This is used as a heuristic for selecting the first lane to
859 /// start operand reordering.
860 unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane
) const {
861 unsigned CntTrue
= 0;
862 unsigned NumOperands
= getNumOperands();
863 // Operands with the same APO can be reordered. We therefore need to count
864 // how many of them we have for each APO, like this: Cnt[APO] = x.
865 // Since we only have two APOs, namely true and false, we can avoid using
866 // a map. Instead we can simply count the number of operands that
867 // correspond to one of them (in this case the 'true' APO), and calculate
868 // the other by subtracting it from the total number of operands.
869 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
)
870 if (getData(OpIdx
, Lane
).APO
)
872 unsigned CntFalse
= NumOperands
- CntTrue
;
873 return std::max(CntTrue
, CntFalse
);
876 /// Go through the instructions in VL and append their operands.
877 void appendOperandsOfVL(ArrayRef
<Value
*> VL
) {
878 assert(!VL
.empty() && "Bad VL");
879 assert((empty() || VL
.size() == getNumLanes()) &&
880 "Expected same number of lanes");
881 assert(isa
<Instruction
>(VL
[0]) && "Expected instruction");
882 unsigned NumOperands
= cast
<Instruction
>(VL
[0])->getNumOperands();
883 OpsVec
.resize(NumOperands
);
884 unsigned NumLanes
= VL
.size();
885 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
) {
886 OpsVec
[OpIdx
].resize(NumLanes
);
887 for (unsigned Lane
= 0; Lane
!= NumLanes
; ++Lane
) {
888 assert(isa
<Instruction
>(VL
[Lane
]) && "Expected instruction");
889 // Our tree has just 3 nodes: the root and two operands.
890 // It is therefore trivial to get the APO. We only need to check the
891 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
892 // RHS operand. The LHS operand of both add and sub is never attached
893 // to an inversese operation in the linearized form, therefore its APO
894 // is false. The RHS is true only if VL[Lane] is an inverse operation.
896 // Since operand reordering is performed on groups of commutative
897 // operations or alternating sequences (e.g., +, -), we can safely
898 // tell the inverse operations by checking commutativity.
899 bool IsInverseOperation
= !isCommutative(cast
<Instruction
>(VL
[Lane
]));
900 bool APO
= (OpIdx
== 0) ? false : IsInverseOperation
;
901 OpsVec
[OpIdx
][Lane
] = {cast
<Instruction
>(VL
[Lane
])->getOperand(OpIdx
),
907 /// \returns the number of operands.
908 unsigned getNumOperands() const { return OpsVec
.size(); }
910 /// \returns the number of lanes.
911 unsigned getNumLanes() const { return OpsVec
[0].size(); }
913 /// \returns the operand value at \p OpIdx and \p Lane.
914 Value
*getValue(unsigned OpIdx
, unsigned Lane
) const {
915 return getData(OpIdx
, Lane
).V
;
918 /// \returns true if the data structure is empty.
919 bool empty() const { return OpsVec
.empty(); }
922 void clear() { OpsVec
.clear(); }
924 /// \Returns true if there are enough operands identical to \p Op to fill
925 /// the whole vector.
926 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
927 bool shouldBroadcast(Value
*Op
, unsigned OpIdx
, unsigned Lane
) {
928 bool OpAPO
= getData(OpIdx
, Lane
).APO
;
929 for (unsigned Ln
= 0, Lns
= getNumLanes(); Ln
!= Lns
; ++Ln
) {
932 // This is set to true if we found a candidate for broadcast at Lane.
933 bool FoundCandidate
= false;
934 for (unsigned OpI
= 0, OpE
= getNumOperands(); OpI
!= OpE
; ++OpI
) {
935 OperandData
&Data
= getData(OpI
, Ln
);
936 if (Data
.APO
!= OpAPO
|| Data
.IsUsed
)
939 FoundCandidate
= true;
951 /// Initialize with all the operands of the instruction vector \p RootVL.
952 VLOperands(ArrayRef
<Value
*> RootVL
, const DataLayout
&DL
,
955 // Append all the operands of RootVL.
956 appendOperandsOfVL(RootVL
);
959 /// \Returns a value vector with the operands across all lanes for the
960 /// opearnd at \p OpIdx.
961 ValueList
getVL(unsigned OpIdx
) const {
962 ValueList
OpVL(OpsVec
[OpIdx
].size());
963 assert(OpsVec
[OpIdx
].size() == getNumLanes() &&
964 "Expected same num of lanes across all operands");
965 for (unsigned Lane
= 0, Lanes
= getNumLanes(); Lane
!= Lanes
; ++Lane
)
966 OpVL
[Lane
] = OpsVec
[OpIdx
][Lane
].V
;
970 // Performs operand reordering for 2 or more operands.
971 // The original operands are in OrigOps[OpIdx][Lane].
972 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
974 unsigned NumOperands
= getNumOperands();
975 unsigned NumLanes
= getNumLanes();
976 // Each operand has its own mode. We are using this mode to help us select
977 // the instructions for each lane, so that they match best with the ones
978 // we have selected so far.
979 SmallVector
<ReorderingMode
, 2> ReorderingModes(NumOperands
);
981 // This is a greedy single-pass algorithm. We are going over each lane
982 // once and deciding on the best order right away with no back-tracking.
983 // However, in order to increase its effectiveness, we start with the lane
984 // that has operands that can move the least. For example, given the
986 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
987 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
988 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
989 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
990 // we will start at Lane 1, since the operands of the subtraction cannot
991 // be reordered. Then we will visit the rest of the lanes in a circular
992 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
994 // Find the first lane that we will start our search from.
995 unsigned FirstLane
= getBestLaneToStartReordering();
997 // Initialize the modes.
998 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
) {
999 Value
*OpLane0
= getValue(OpIdx
, FirstLane
);
1000 // Keep track if we have instructions with all the same opcode on one
1002 if (isa
<LoadInst
>(OpLane0
))
1003 ReorderingModes
[OpIdx
] = ReorderingMode::Load
;
1004 else if (isa
<Instruction
>(OpLane0
)) {
1005 // Check if OpLane0 should be broadcast.
1006 if (shouldBroadcast(OpLane0
, OpIdx
, FirstLane
))
1007 ReorderingModes
[OpIdx
] = ReorderingMode::Splat
;
1009 ReorderingModes
[OpIdx
] = ReorderingMode::Opcode
;
1011 else if (isa
<Constant
>(OpLane0
))
1012 ReorderingModes
[OpIdx
] = ReorderingMode::Constant
;
1013 else if (isa
<Argument
>(OpLane0
))
1014 // Our best hope is a Splat. It may save some cost in some cases.
1015 ReorderingModes
[OpIdx
] = ReorderingMode::Splat
;
1017 // NOTE: This should be unreachable.
1018 ReorderingModes
[OpIdx
] = ReorderingMode::Failed
;
1021 // If the initial strategy fails for any of the operand indexes, then we
1022 // perform reordering again in a second pass. This helps avoid assigning
1023 // high priority to the failed strategy, and should improve reordering for
1024 // the non-failed operand indexes.
1025 for (int Pass
= 0; Pass
!= 2; ++Pass
) {
1026 // Skip the second pass if the first pass did not fail.
1027 bool StrategyFailed
= false;
1028 // Mark all operand data as free to use.
1030 // We keep the original operand order for the FirstLane, so reorder the
1031 // rest of the lanes. We are visiting the nodes in a circular fashion,
1032 // using FirstLane as the center point and increasing the radius
1034 for (unsigned Distance
= 1; Distance
!= NumLanes
; ++Distance
) {
1035 // Visit the lane on the right and then the lane on the left.
1036 for (int Direction
: {+1, -1}) {
1037 int Lane
= FirstLane
+ Direction
* Distance
;
1038 if (Lane
< 0 || Lane
>= (int)NumLanes
)
1040 int LastLane
= Lane
- Direction
;
1041 assert(LastLane
>= 0 && LastLane
< (int)NumLanes
&&
1043 // Look for a good match for each operand.
1044 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
) {
1045 // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1046 Optional
<unsigned> BestIdx
=
1047 getBestOperand(OpIdx
, Lane
, LastLane
, ReorderingModes
);
1048 // By not selecting a value, we allow the operands that follow to
1049 // select a better matching value. We will get a non-null value in
1050 // the next run of getBestOperand().
1052 // Swap the current operand with the one returned by
1053 // getBestOperand().
1054 swap(OpIdx
, BestIdx
.getValue(), Lane
);
1056 // We failed to find a best operand, set mode to 'Failed'.
1057 ReorderingModes
[OpIdx
] = ReorderingMode::Failed
;
1058 // Enable the second pass.
1059 StrategyFailed
= true;
1064 // Skip second pass if the strategy did not fail.
1065 if (!StrategyFailed
)
1070 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1071 LLVM_DUMP_METHOD
static StringRef
getModeStr(ReorderingMode RMode
) {
1073 case ReorderingMode::Load
:
1075 case ReorderingMode::Opcode
:
1077 case ReorderingMode::Constant
:
1079 case ReorderingMode::Splat
:
1081 case ReorderingMode::Failed
:
1084 llvm_unreachable("Unimplemented Reordering Type");
1087 LLVM_DUMP_METHOD
static raw_ostream
&printMode(ReorderingMode RMode
,
1089 return OS
<< getModeStr(RMode
);
1093 LLVM_DUMP_METHOD
static void dumpMode(ReorderingMode RMode
) {
1094 printMode(RMode
, dbgs());
1097 friend raw_ostream
&operator<<(raw_ostream
&OS
, ReorderingMode RMode
) {
1098 return printMode(RMode
, OS
);
1101 LLVM_DUMP_METHOD raw_ostream
&print(raw_ostream
&OS
) const {
1102 const unsigned Indent
= 2;
1104 for (const OperandDataVec
&OpDataVec
: OpsVec
) {
1105 OS
<< "Operand " << Cnt
++ << "\n";
1106 for (const OperandData
&OpData
: OpDataVec
) {
1107 OS
.indent(Indent
) << "{";
1108 if (Value
*V
= OpData
.V
)
1112 OS
<< ", APO:" << OpData
.APO
<< "}\n";
1120 LLVM_DUMP_METHOD
void dump() const { print(dbgs()); }
1125 /// Checks if all users of \p I are the part of the vectorization tree.
1126 bool areAllUsersVectorized(Instruction
*I
) const;
1128 /// \returns the cost of the vectorizable entry.
1129 int getEntryCost(TreeEntry
*E
);
1131 /// This is the recursive part of buildTree.
1132 void buildTree_rec(ArrayRef
<Value
*> Roots
, unsigned Depth
,
1133 const EdgeInfo
&EI
);
1135 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1136 /// be vectorized to use the original vector (or aggregate "bitcast" to a
1137 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1138 /// returns false, setting \p CurrentOrder to either an empty vector or a
1139 /// non-identity permutation that allows to reuse extract instructions.
1140 bool canReuseExtract(ArrayRef
<Value
*> VL
, Value
*OpValue
,
1141 SmallVectorImpl
<unsigned> &CurrentOrder
) const;
1143 /// Vectorize a single entry in the tree.
1144 Value
*vectorizeTree(TreeEntry
*E
);
1146 /// Vectorize a single entry in the tree, starting in \p VL.
1147 Value
*vectorizeTree(ArrayRef
<Value
*> VL
);
1149 /// \returns the scalarization cost for this type. Scalarization in this
1150 /// context means the creation of vectors from a group of scalars.
1151 int getGatherCost(Type
*Ty
, const DenseSet
<unsigned> &ShuffledIndices
) const;
1153 /// \returns the scalarization cost for this list of values. Assuming that
1154 /// this subtree gets vectorized, we may need to extract the values from the
1155 /// roots. This method calculates the cost of extracting the values.
1156 int getGatherCost(ArrayRef
<Value
*> VL
) const;
1158 /// Set the Builder insert point to one after the last instruction in
1160 void setInsertPointAfterBundle(TreeEntry
*E
);
1162 /// \returns a vector from a collection of scalars in \p VL.
1163 Value
*Gather(ArrayRef
<Value
*> VL
, VectorType
*Ty
);
1165 /// \returns whether the VectorizableTree is fully vectorizable and will
1166 /// be beneficial even the tree height is tiny.
1167 bool isFullyVectorizableTinyTree() const;
1169 /// Reorder commutative or alt operands to get better probability of
1170 /// generating vectorized code.
1171 static void reorderInputsAccordingToOpcode(ArrayRef
<Value
*> VL
,
1172 SmallVectorImpl
<Value
*> &Left
,
1173 SmallVectorImpl
<Value
*> &Right
,
1174 const DataLayout
&DL
,
1175 ScalarEvolution
&SE
);
1177 using VecTreeTy
= SmallVector
<std::unique_ptr
<TreeEntry
>, 8>;
1178 TreeEntry(VecTreeTy
&Container
) : Container(Container
) {}
1180 /// \returns true if the scalars in VL are equal to this entry.
1181 bool isSame(ArrayRef
<Value
*> VL
) const {
1182 if (VL
.size() == Scalars
.size())
1183 return std::equal(VL
.begin(), VL
.end(), Scalars
.begin());
1184 return VL
.size() == ReuseShuffleIndices
.size() &&
1186 VL
.begin(), VL
.end(), ReuseShuffleIndices
.begin(),
1187 [this](Value
*V
, unsigned Idx
) { return V
== Scalars
[Idx
]; });
1190 /// A vector of scalars.
1193 /// The Scalars are vectorized into this value. It is initialized to Null.
1194 Value
*VectorizedValue
= nullptr;
1196 /// Do we need to gather this sequence ?
1197 bool NeedToGather
= false;
1199 /// Does this sequence require some shuffling?
1200 SmallVector
<unsigned, 4> ReuseShuffleIndices
;
1202 /// Does this entry require reordering?
1203 ArrayRef
<unsigned> ReorderIndices
;
1205 /// Points back to the VectorizableTree.
1207 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
1208 /// to be a pointer and needs to be able to initialize the child iterator.
1209 /// Thus we need a reference back to the container to translate the indices
1211 VecTreeTy
&Container
;
1213 /// The TreeEntry index containing the user of this entry. We can actually
1214 /// have multiple users so the data structure is not truly a tree.
1215 SmallVector
<EdgeInfo
, 1> UserTreeIndices
;
1217 /// The index of this treeEntry in VectorizableTree.
1221 /// The operands of each instruction in each lane Operands[op_index][lane].
1222 /// Note: This helps avoid the replication of the code that performs the
1223 /// reordering of operands during buildTree_rec() and vectorizeTree().
1224 SmallVector
<ValueList
, 2> Operands
;
1226 /// The main/alternate instruction.
1227 Instruction
*MainOp
= nullptr;
1228 Instruction
*AltOp
= nullptr;
1231 /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1232 void setOperand(unsigned OpIdx
, ArrayRef
<Value
*> OpVL
) {
1233 if (Operands
.size() < OpIdx
+ 1)
1234 Operands
.resize(OpIdx
+ 1);
1235 assert(Operands
[OpIdx
].size() == 0 && "Already resized?");
1236 Operands
[OpIdx
].resize(Scalars
.size());
1237 for (unsigned Lane
= 0, E
= Scalars
.size(); Lane
!= E
; ++Lane
)
1238 Operands
[OpIdx
][Lane
] = OpVL
[Lane
];
1241 /// Set the operands of this bundle in their original order.
1242 void setOperandsInOrder() {
1243 assert(Operands
.empty() && "Already initialized?");
1244 auto *I0
= cast
<Instruction
>(Scalars
[0]);
1245 Operands
.resize(I0
->getNumOperands());
1246 unsigned NumLanes
= Scalars
.size();
1247 for (unsigned OpIdx
= 0, NumOperands
= I0
->getNumOperands();
1248 OpIdx
!= NumOperands
; ++OpIdx
) {
1249 Operands
[OpIdx
].resize(NumLanes
);
1250 for (unsigned Lane
= 0; Lane
!= NumLanes
; ++Lane
) {
1251 auto *I
= cast
<Instruction
>(Scalars
[Lane
]);
1252 assert(I
->getNumOperands() == NumOperands
&&
1253 "Expected same number of operands");
1254 Operands
[OpIdx
][Lane
] = I
->getOperand(OpIdx
);
1259 /// \returns the \p OpIdx operand of this TreeEntry.
1260 ValueList
&getOperand(unsigned OpIdx
) {
1261 assert(OpIdx
< Operands
.size() && "Off bounds");
1262 return Operands
[OpIdx
];
1265 /// \returns the number of operands.
1266 unsigned getNumOperands() const { return Operands
.size(); }
1268 /// \return the single \p OpIdx operand.
1269 Value
*getSingleOperand(unsigned OpIdx
) const {
1270 assert(OpIdx
< Operands
.size() && "Off bounds");
1271 assert(!Operands
[OpIdx
].empty() && "No operand available");
1272 return Operands
[OpIdx
][0];
1275 /// Some of the instructions in the list have alternate opcodes.
1276 bool isAltShuffle() const {
1277 return getOpcode() != getAltOpcode();
1280 bool isOpcodeOrAlt(Instruction
*I
) const {
1281 unsigned CheckedOpcode
= I
->getOpcode();
1282 return (getOpcode() == CheckedOpcode
||
1283 getAltOpcode() == CheckedOpcode
);
1286 /// Chooses the correct key for scheduling data. If \p Op has the same (or
1287 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
1289 Value
*isOneOf(Value
*Op
) const {
1290 auto *I
= dyn_cast
<Instruction
>(Op
);
1291 if (I
&& isOpcodeOrAlt(I
))
1296 void setOperations(const InstructionsState
&S
) {
1301 Instruction
*getMainOp() const {
1305 Instruction
*getAltOp() const {
1309 /// The main/alternate opcodes for the list of instructions.
1310 unsigned getOpcode() const {
1311 return MainOp
? MainOp
->getOpcode() : 0;
1314 unsigned getAltOpcode() const {
1315 return AltOp
? AltOp
->getOpcode() : 0;
1318 /// Update operations state of this entry if reorder occurred.
1319 bool updateStateIfReorder() {
1320 if (ReorderIndices
.empty())
1322 InstructionsState S
= getSameOpcode(Scalars
, ReorderIndices
.front());
1329 LLVM_DUMP_METHOD
void dump() const {
1330 dbgs() << Idx
<< ".\n";
1331 for (unsigned OpI
= 0, OpE
= Operands
.size(); OpI
!= OpE
; ++OpI
) {
1332 dbgs() << "Operand " << OpI
<< ":\n";
1333 for (const Value
*V
: Operands
[OpI
])
1334 dbgs().indent(2) << *V
<< "\n";
1336 dbgs() << "Scalars: \n";
1337 for (Value
*V
: Scalars
)
1338 dbgs().indent(2) << *V
<< "\n";
1339 dbgs() << "NeedToGather: " << NeedToGather
<< "\n";
1340 dbgs() << "MainOp: " << *MainOp
<< "\n";
1341 dbgs() << "AltOp: " << *AltOp
<< "\n";
1342 dbgs() << "VectorizedValue: ";
1343 if (VectorizedValue
)
1344 dbgs() << *VectorizedValue
;
1348 dbgs() << "ReuseShuffleIndices: ";
1349 if (ReuseShuffleIndices
.empty())
1352 for (unsigned ReuseIdx
: ReuseShuffleIndices
)
1353 dbgs() << ReuseIdx
<< ", ";
1355 dbgs() << "ReorderIndices: ";
1356 for (unsigned ReorderIdx
: ReorderIndices
)
1357 dbgs() << ReorderIdx
<< ", ";
1359 dbgs() << "UserTreeIndices: ";
1360 for (const auto &EInfo
: UserTreeIndices
)
1361 dbgs() << EInfo
<< ", ";
1367 /// Create a new VectorizableTree entry.
1368 TreeEntry
*newTreeEntry(ArrayRef
<Value
*> VL
, Optional
<ScheduleData
*> Bundle
,
1369 const InstructionsState
&S
,
1370 const EdgeInfo
&UserTreeIdx
,
1371 ArrayRef
<unsigned> ReuseShuffleIndices
= None
,
1372 ArrayRef
<unsigned> ReorderIndices
= None
) {
1373 bool Vectorized
= (bool)Bundle
;
1374 VectorizableTree
.push_back(std::make_unique
<TreeEntry
>(VectorizableTree
));
1375 TreeEntry
*Last
= VectorizableTree
.back().get();
1376 Last
->Idx
= VectorizableTree
.size() - 1;
1377 Last
->Scalars
.insert(Last
->Scalars
.begin(), VL
.begin(), VL
.end());
1378 Last
->NeedToGather
= !Vectorized
;
1379 Last
->ReuseShuffleIndices
.append(ReuseShuffleIndices
.begin(),
1380 ReuseShuffleIndices
.end());
1381 Last
->ReorderIndices
= ReorderIndices
;
1382 Last
->setOperations(S
);
1384 for (int i
= 0, e
= VL
.size(); i
!= e
; ++i
) {
1385 assert(!getTreeEntry(VL
[i
]) && "Scalar already in tree!");
1386 ScalarToTreeEntry
[VL
[i
]] = Last
;
1388 // Update the scheduler bundle to point to this TreeEntry.
1390 for (ScheduleData
*BundleMember
= Bundle
.getValue(); BundleMember
;
1391 BundleMember
= BundleMember
->NextInBundle
) {
1392 BundleMember
->TE
= Last
;
1393 BundleMember
->Lane
= Lane
;
1396 assert((!Bundle
.getValue() || Lane
== VL
.size()) &&
1397 "Bundle and VL out of sync");
1399 MustGather
.insert(VL
.begin(), VL
.end());
1402 if (UserTreeIdx
.UserTE
)
1403 Last
->UserTreeIndices
.push_back(UserTreeIdx
);
1408 /// -- Vectorization State --
1409 /// Holds all of the tree entries.
1410 TreeEntry::VecTreeTy VectorizableTree
;
1414 LLVM_DUMP_METHOD
void dumpVectorizableTree() const {
1415 for (unsigned Id
= 0, IdE
= VectorizableTree
.size(); Id
!= IdE
; ++Id
) {
1416 VectorizableTree
[Id
]->dump();
1422 TreeEntry
*getTreeEntry(Value
*V
) {
1423 auto I
= ScalarToTreeEntry
.find(V
);
1424 if (I
!= ScalarToTreeEntry
.end())
1429 const TreeEntry
*getTreeEntry(Value
*V
) const {
1430 auto I
= ScalarToTreeEntry
.find(V
);
1431 if (I
!= ScalarToTreeEntry
.end())
1436 /// Maps a specific scalar to its tree entry.
1437 SmallDenseMap
<Value
*, TreeEntry
*> ScalarToTreeEntry
;
1439 /// A list of scalars that we found that we need to keep as scalars.
1440 ValueSet MustGather
;
1442 /// This POD struct describes one external user in the vectorized tree.
1443 struct ExternalUser
{
1444 ExternalUser(Value
*S
, llvm::User
*U
, int L
)
1445 : Scalar(S
), User(U
), Lane(L
) {}
1447 // Which scalar in our function.
1450 // Which user that uses the scalar.
1453 // Which lane does the scalar belong to.
1456 using UserList
= SmallVector
<ExternalUser
, 16>;
1458 /// Checks if two instructions may access the same memory.
1460 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
1461 /// is invariant in the calling loop.
1462 bool isAliased(const MemoryLocation
&Loc1
, Instruction
*Inst1
,
1463 Instruction
*Inst2
) {
1464 // First check if the result is already in the cache.
1465 AliasCacheKey key
= std::make_pair(Inst1
, Inst2
);
1466 Optional
<bool> &result
= AliasCache
[key
];
1467 if (result
.hasValue()) {
1468 return result
.getValue();
1470 MemoryLocation Loc2
= getLocation(Inst2
, AA
);
1471 bool aliased
= true;
1472 if (Loc1
.Ptr
&& Loc2
.Ptr
&& isSimple(Inst1
) && isSimple(Inst2
)) {
1473 // Do the alias check.
1474 aliased
= AA
->alias(Loc1
, Loc2
);
1476 // Store the result in the cache.
1481 using AliasCacheKey
= std::pair
<Instruction
*, Instruction
*>;
1483 /// Cache for alias results.
1484 /// TODO: consider moving this to the AliasAnalysis itself.
1485 DenseMap
<AliasCacheKey
, Optional
<bool>> AliasCache
;
1487 /// Removes an instruction from its block and eventually deletes it.
1488 /// It's like Instruction::eraseFromParent() except that the actual deletion
1489 /// is delayed until BoUpSLP is destructed.
1490 /// This is required to ensure that there are no incorrect collisions in the
1491 /// AliasCache, which can happen if a new instruction is allocated at the
1492 /// same address as a previously deleted instruction.
1493 void eraseInstruction(Instruction
*I
) {
1494 I
->removeFromParent();
1495 I
->dropAllReferences();
1496 DeletedInstructions
.emplace_back(I
);
1499 /// Temporary store for deleted instructions. Instructions will be deleted
1500 /// eventually when the BoUpSLP is destructed.
1501 SmallVector
<unique_value
, 8> DeletedInstructions
;
1503 /// A list of values that need to extracted out of the tree.
1504 /// This list holds pairs of (Internal Scalar : External User). External User
1505 /// can be nullptr, it means that this Internal Scalar will be used later,
1506 /// after vectorization.
1507 UserList ExternalUses
;
1509 /// Values used only by @llvm.assume calls.
1510 SmallPtrSet
<const Value
*, 32> EphValues
;
1512 /// Holds all of the instructions that we gathered.
1513 SetVector
<Instruction
*> GatherSeq
;
1515 /// A list of blocks that we are going to CSE.
1516 SetVector
<BasicBlock
*> CSEBlocks
;
1518 /// Contains all scheduling relevant data for an instruction.
1519 /// A ScheduleData either represents a single instruction or a member of an
1520 /// instruction bundle (= a group of instructions which is combined into a
1521 /// vector instruction).
1522 struct ScheduleData
{
1523 // The initial value for the dependency counters. It means that the
1524 // dependencies are not calculated yet.
1525 enum { InvalidDeps
= -1 };
1527 ScheduleData() = default;
1529 void init(int BlockSchedulingRegionID
, Value
*OpVal
) {
1530 FirstInBundle
= this;
1531 NextInBundle
= nullptr;
1532 NextLoadStore
= nullptr;
1533 IsScheduled
= false;
1534 SchedulingRegionID
= BlockSchedulingRegionID
;
1535 UnscheduledDepsInBundle
= UnscheduledDeps
;
1536 clearDependencies();
1542 /// Returns true if the dependency information has been calculated.
1543 bool hasValidDependencies() const { return Dependencies
!= InvalidDeps
; }
1545 /// Returns true for single instructions and for bundle representatives
1546 /// (= the head of a bundle).
1547 bool isSchedulingEntity() const { return FirstInBundle
== this; }
1549 /// Returns true if it represents an instruction bundle and not only a
1550 /// single instruction.
1551 bool isPartOfBundle() const {
1552 return NextInBundle
!= nullptr || FirstInBundle
!= this;
1555 /// Returns true if it is ready for scheduling, i.e. it has no more
1556 /// unscheduled depending instructions/bundles.
1557 bool isReady() const {
1558 assert(isSchedulingEntity() &&
1559 "can't consider non-scheduling entity for ready list");
1560 return UnscheduledDepsInBundle
== 0 && !IsScheduled
;
1563 /// Modifies the number of unscheduled dependencies, also updating it for
1564 /// the whole bundle.
1565 int incrementUnscheduledDeps(int Incr
) {
1566 UnscheduledDeps
+= Incr
;
1567 return FirstInBundle
->UnscheduledDepsInBundle
+= Incr
;
1570 /// Sets the number of unscheduled dependencies to the number of
1572 void resetUnscheduledDeps() {
1573 incrementUnscheduledDeps(Dependencies
- UnscheduledDeps
);
1576 /// Clears all dependency information.
1577 void clearDependencies() {
1578 Dependencies
= InvalidDeps
;
1579 resetUnscheduledDeps();
1580 MemoryDependencies
.clear();
1583 void dump(raw_ostream
&os
) const {
1584 if (!isSchedulingEntity()) {
1585 os
<< "/ " << *Inst
;
1586 } else if (NextInBundle
) {
1588 ScheduleData
*SD
= NextInBundle
;
1590 os
<< ';' << *SD
->Inst
;
1591 SD
= SD
->NextInBundle
;
1599 Instruction
*Inst
= nullptr;
1601 /// Points to the head in an instruction bundle (and always to this for
1602 /// single instructions).
1603 ScheduleData
*FirstInBundle
= nullptr;
1605 /// Single linked list of all instructions in a bundle. Null if it is a
1606 /// single instruction.
1607 ScheduleData
*NextInBundle
= nullptr;
1609 /// Single linked list of all memory instructions (e.g. load, store, call)
1610 /// in the block - until the end of the scheduling region.
1611 ScheduleData
*NextLoadStore
= nullptr;
1613 /// The dependent memory instructions.
1614 /// This list is derived on demand in calculateDependencies().
1615 SmallVector
<ScheduleData
*, 4> MemoryDependencies
;
1617 /// This ScheduleData is in the current scheduling region if this matches
1618 /// the current SchedulingRegionID of BlockScheduling.
1619 int SchedulingRegionID
= 0;
1621 /// Used for getting a "good" final ordering of instructions.
1622 int SchedulingPriority
= 0;
1624 /// The number of dependencies. Constitutes of the number of users of the
1625 /// instruction plus the number of dependent memory instructions (if any).
1626 /// This value is calculated on demand.
1627 /// If InvalidDeps, the number of dependencies is not calculated yet.
1628 int Dependencies
= InvalidDeps
;
1630 /// The number of dependencies minus the number of dependencies of scheduled
1631 /// instructions. As soon as this is zero, the instruction/bundle gets ready
1633 /// Note that this is negative as long as Dependencies is not calculated.
1634 int UnscheduledDeps
= InvalidDeps
;
1636 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
1637 /// single instructions.
1638 int UnscheduledDepsInBundle
= InvalidDeps
;
1640 /// True if this instruction is scheduled (or considered as scheduled in the
1642 bool IsScheduled
= false;
1644 /// Opcode of the current instruction in the schedule data.
1645 Value
*OpValue
= nullptr;
1647 /// The TreeEntry that this instruction corresponds to.
1648 TreeEntry
*TE
= nullptr;
1650 /// The lane of this node in the TreeEntry.
1655 friend inline raw_ostream
&operator<<(raw_ostream
&os
,
1656 const BoUpSLP::ScheduleData
&SD
) {
1662 friend struct GraphTraits
<BoUpSLP
*>;
1663 friend struct DOTGraphTraits
<BoUpSLP
*>;
1665 /// Contains all scheduling data for a basic block.
1666 struct BlockScheduling
{
1667 BlockScheduling(BasicBlock
*BB
)
1668 : BB(BB
), ChunkSize(BB
->size()), ChunkPos(ChunkSize
) {}
1672 ScheduleStart
= nullptr;
1673 ScheduleEnd
= nullptr;
1674 FirstLoadStoreInRegion
= nullptr;
1675 LastLoadStoreInRegion
= nullptr;
1677 // Reduce the maximum schedule region size by the size of the
1678 // previous scheduling run.
1679 ScheduleRegionSizeLimit
-= ScheduleRegionSize
;
1680 if (ScheduleRegionSizeLimit
< MinScheduleRegionSize
)
1681 ScheduleRegionSizeLimit
= MinScheduleRegionSize
;
1682 ScheduleRegionSize
= 0;
1684 // Make a new scheduling region, i.e. all existing ScheduleData is not
1685 // in the new region yet.
1686 ++SchedulingRegionID
;
1689 ScheduleData
*getScheduleData(Value
*V
) {
1690 ScheduleData
*SD
= ScheduleDataMap
[V
];
1691 if (SD
&& SD
->SchedulingRegionID
== SchedulingRegionID
)
1696 ScheduleData
*getScheduleData(Value
*V
, Value
*Key
) {
1698 return getScheduleData(V
);
1699 auto I
= ExtraScheduleDataMap
.find(V
);
1700 if (I
!= ExtraScheduleDataMap
.end()) {
1701 ScheduleData
*SD
= I
->second
[Key
];
1702 if (SD
&& SD
->SchedulingRegionID
== SchedulingRegionID
)
1708 bool isInSchedulingRegion(ScheduleData
*SD
) {
1709 return SD
->SchedulingRegionID
== SchedulingRegionID
;
1712 /// Marks an instruction as scheduled and puts all dependent ready
1713 /// instructions into the ready-list.
1714 template <typename ReadyListType
>
1715 void schedule(ScheduleData
*SD
, ReadyListType
&ReadyList
) {
1716 SD
->IsScheduled
= true;
1717 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD
<< "\n");
1719 ScheduleData
*BundleMember
= SD
;
1720 while (BundleMember
) {
1721 if (BundleMember
->Inst
!= BundleMember
->OpValue
) {
1722 BundleMember
= BundleMember
->NextInBundle
;
1725 // Handle the def-use chain dependencies.
1727 // Decrement the unscheduled counter and insert to ready list if ready.
1728 auto &&DecrUnsched
= [this, &ReadyList
](Instruction
*I
) {
1729 doForAllOpcodes(I
, [&ReadyList
](ScheduleData
*OpDef
) {
1730 if (OpDef
&& OpDef
->hasValidDependencies() &&
1731 OpDef
->incrementUnscheduledDeps(-1) == 0) {
1732 // There are no more unscheduled dependencies after
1733 // decrementing, so we can put the dependent instruction
1734 // into the ready list.
1735 ScheduleData
*DepBundle
= OpDef
->FirstInBundle
;
1736 assert(!DepBundle
->IsScheduled
&&
1737 "already scheduled bundle gets ready");
1738 ReadyList
.insert(DepBundle
);
1740 << "SLP: gets ready (def): " << *DepBundle
<< "\n");
1745 // If BundleMember is a vector bundle, its operands may have been
1746 // reordered duiring buildTree(). We therefore need to get its operands
1747 // through the TreeEntry.
1748 if (TreeEntry
*TE
= BundleMember
->TE
) {
1749 int Lane
= BundleMember
->Lane
;
1750 assert(Lane
>= 0 && "Lane not set");
1751 for (unsigned OpIdx
= 0, NumOperands
= TE
->getNumOperands();
1752 OpIdx
!= NumOperands
; ++OpIdx
)
1753 if (auto *I
= dyn_cast
<Instruction
>(TE
->getOperand(OpIdx
)[Lane
]))
1756 // If BundleMember is a stand-alone instruction, no operand reordering
1757 // has taken place, so we directly access its operands.
1758 for (Use
&U
: BundleMember
->Inst
->operands())
1759 if (auto *I
= dyn_cast
<Instruction
>(U
.get()))
1762 // Handle the memory dependencies.
1763 for (ScheduleData
*MemoryDepSD
: BundleMember
->MemoryDependencies
) {
1764 if (MemoryDepSD
->incrementUnscheduledDeps(-1) == 0) {
1765 // There are no more unscheduled dependencies after decrementing,
1766 // so we can put the dependent instruction into the ready list.
1767 ScheduleData
*DepBundle
= MemoryDepSD
->FirstInBundle
;
1768 assert(!DepBundle
->IsScheduled
&&
1769 "already scheduled bundle gets ready");
1770 ReadyList
.insert(DepBundle
);
1772 << "SLP: gets ready (mem): " << *DepBundle
<< "\n");
1775 BundleMember
= BundleMember
->NextInBundle
;
1779 void doForAllOpcodes(Value
*V
,
1780 function_ref
<void(ScheduleData
*SD
)> Action
) {
1781 if (ScheduleData
*SD
= getScheduleData(V
))
1783 auto I
= ExtraScheduleDataMap
.find(V
);
1784 if (I
!= ExtraScheduleDataMap
.end())
1785 for (auto &P
: I
->second
)
1786 if (P
.second
->SchedulingRegionID
== SchedulingRegionID
)
1790 /// Put all instructions into the ReadyList which are ready for scheduling.
1791 template <typename ReadyListType
>
1792 void initialFillReadyList(ReadyListType
&ReadyList
) {
1793 for (auto *I
= ScheduleStart
; I
!= ScheduleEnd
; I
= I
->getNextNode()) {
1794 doForAllOpcodes(I
, [&](ScheduleData
*SD
) {
1795 if (SD
->isSchedulingEntity() && SD
->isReady()) {
1796 ReadyList
.insert(SD
);
1798 << "SLP: initially in ready list: " << *I
<< "\n");
1804 /// Checks if a bundle of instructions can be scheduled, i.e. has no
1805 /// cyclic dependencies. This is only a dry-run, no instructions are
1806 /// actually moved at this stage.
1807 /// \returns the scheduling bundle. The returned Optional value is non-None
1808 /// if \p VL is allowed to be scheduled.
1809 Optional
<ScheduleData
*>
1810 tryScheduleBundle(ArrayRef
<Value
*> VL
, BoUpSLP
*SLP
,
1811 const InstructionsState
&S
);
1813 /// Un-bundles a group of instructions.
1814 void cancelScheduling(ArrayRef
<Value
*> VL
, Value
*OpValue
);
1816 /// Allocates schedule data chunk.
1817 ScheduleData
*allocateScheduleDataChunks();
1819 /// Extends the scheduling region so that V is inside the region.
1820 /// \returns true if the region size is within the limit.
1821 bool extendSchedulingRegion(Value
*V
, const InstructionsState
&S
);
1823 /// Initialize the ScheduleData structures for new instructions in the
1824 /// scheduling region.
1825 void initScheduleData(Instruction
*FromI
, Instruction
*ToI
,
1826 ScheduleData
*PrevLoadStore
,
1827 ScheduleData
*NextLoadStore
);
1829 /// Updates the dependency information of a bundle and of all instructions/
1830 /// bundles which depend on the original bundle.
1831 void calculateDependencies(ScheduleData
*SD
, bool InsertInReadyList
,
1834 /// Sets all instruction in the scheduling region to un-scheduled.
1835 void resetSchedule();
1839 /// Simple memory allocation for ScheduleData.
1840 std::vector
<std::unique_ptr
<ScheduleData
[]>> ScheduleDataChunks
;
1842 /// The size of a ScheduleData array in ScheduleDataChunks.
1845 /// The allocator position in the current chunk, which is the last entry
1846 /// of ScheduleDataChunks.
1849 /// Attaches ScheduleData to Instruction.
1850 /// Note that the mapping survives during all vectorization iterations, i.e.
1851 /// ScheduleData structures are recycled.
1852 DenseMap
<Value
*, ScheduleData
*> ScheduleDataMap
;
1854 /// Attaches ScheduleData to Instruction with the leading key.
1855 DenseMap
<Value
*, SmallDenseMap
<Value
*, ScheduleData
*>>
1856 ExtraScheduleDataMap
;
1858 struct ReadyList
: SmallVector
<ScheduleData
*, 8> {
1859 void insert(ScheduleData
*SD
) { push_back(SD
); }
1862 /// The ready-list for scheduling (only used for the dry-run).
1863 ReadyList ReadyInsts
;
1865 /// The first instruction of the scheduling region.
1866 Instruction
*ScheduleStart
= nullptr;
1868 /// The first instruction _after_ the scheduling region.
1869 Instruction
*ScheduleEnd
= nullptr;
1871 /// The first memory accessing instruction in the scheduling region
1873 ScheduleData
*FirstLoadStoreInRegion
= nullptr;
1875 /// The last memory accessing instruction in the scheduling region
1877 ScheduleData
*LastLoadStoreInRegion
= nullptr;
1879 /// The current size of the scheduling region.
1880 int ScheduleRegionSize
= 0;
1882 /// The maximum size allowed for the scheduling region.
1883 int ScheduleRegionSizeLimit
= ScheduleRegionSizeBudget
;
1885 /// The ID of the scheduling region. For a new vectorization iteration this
1886 /// is incremented which "removes" all ScheduleData from the region.
1887 // Make sure that the initial SchedulingRegionID is greater than the
1888 // initial SchedulingRegionID in ScheduleData (which is 0).
1889 int SchedulingRegionID
= 1;
1892 /// Attaches the BlockScheduling structures to basic blocks.
1893 MapVector
<BasicBlock
*, std::unique_ptr
<BlockScheduling
>> BlocksSchedules
;
1895 /// Performs the "real" scheduling. Done before vectorization is actually
1896 /// performed in a basic block.
1897 void scheduleBlock(BlockScheduling
*BS
);
1899 /// List of users to ignore during scheduling and that don't need extracting.
1900 ArrayRef
<Value
*> UserIgnoreList
;
1902 using OrdersType
= SmallVector
<unsigned, 4>;
1903 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
1904 /// sorted SmallVectors of unsigned.
1905 struct OrdersTypeDenseMapInfo
{
1906 static OrdersType
getEmptyKey() {
1912 static OrdersType
getTombstoneKey() {
1918 static unsigned getHashValue(const OrdersType
&V
) {
1919 return static_cast<unsigned>(hash_combine_range(V
.begin(), V
.end()));
1922 static bool isEqual(const OrdersType
&LHS
, const OrdersType
&RHS
) {
1927 /// Contains orders of operations along with the number of bundles that have
1928 /// operations in this order. It stores only those orders that require
1929 /// reordering, if reordering is not required it is counted using \a
1930 /// NumOpsWantToKeepOriginalOrder.
1931 DenseMap
<OrdersType
, unsigned, OrdersTypeDenseMapInfo
> NumOpsWantToKeepOrder
;
1932 /// Number of bundles that do not require reordering.
1933 unsigned NumOpsWantToKeepOriginalOrder
= 0;
1935 // Analysis and block reference.
1937 ScalarEvolution
*SE
;
1938 TargetTransformInfo
*TTI
;
1939 TargetLibraryInfo
*TLI
;
1943 AssumptionCache
*AC
;
1945 const DataLayout
*DL
;
1946 OptimizationRemarkEmitter
*ORE
;
1948 unsigned MaxVecRegSize
; // This is set by TTI or overridden by cl::opt.
1949 unsigned MinVecRegSize
; // Set by cl::opt (default: 128).
1951 /// Instruction builder to construct the vectorized tree.
1952 IRBuilder
<> Builder
;
1954 /// A map of scalar integer values to the smallest bit width with which they
1955 /// can legally be represented. The values map to (width, signed) pairs,
1956 /// where "width" indicates the minimum bit width and "signed" is True if the
1957 /// value must be signed-extended, rather than zero-extended, back to its
1959 MapVector
<Value
*, std::pair
<uint64_t, bool>> MinBWs
;
1962 } // end namespace slpvectorizer
1964 template <> struct GraphTraits
<BoUpSLP
*> {
1965 using TreeEntry
= BoUpSLP::TreeEntry
;
1967 /// NodeRef has to be a pointer per the GraphWriter.
1968 using NodeRef
= TreeEntry
*;
1970 using ContainerTy
= BoUpSLP::TreeEntry::VecTreeTy
;
1972 /// Add the VectorizableTree to the index iterator to be able to return
1973 /// TreeEntry pointers.
1974 struct ChildIteratorType
1975 : public iterator_adaptor_base
<
1976 ChildIteratorType
, SmallVector
<BoUpSLP::EdgeInfo
, 1>::iterator
> {
1977 ContainerTy
&VectorizableTree
;
1979 ChildIteratorType(SmallVector
<BoUpSLP::EdgeInfo
, 1>::iterator W
,
1981 : ChildIteratorType::iterator_adaptor_base(W
), VectorizableTree(VT
) {}
1983 NodeRef
operator*() { return I
->UserTE
; }
1986 static NodeRef
getEntryNode(BoUpSLP
&R
) {
1987 return R
.VectorizableTree
[0].get();
1990 static ChildIteratorType
child_begin(NodeRef N
) {
1991 return {N
->UserTreeIndices
.begin(), N
->Container
};
1994 static ChildIteratorType
child_end(NodeRef N
) {
1995 return {N
->UserTreeIndices
.end(), N
->Container
};
1998 /// For the node iterator we just need to turn the TreeEntry iterator into a
1999 /// TreeEntry* iterator so that it dereferences to NodeRef.
2000 class nodes_iterator
{
2001 using ItTy
= ContainerTy::iterator
;
2005 nodes_iterator(const ItTy
&It2
) : It(It2
) {}
2006 NodeRef
operator*() { return It
->get(); }
2007 nodes_iterator
operator++() {
2011 bool operator!=(const nodes_iterator
&N2
) const { return N2
.It
!= It
; }
2014 static nodes_iterator
nodes_begin(BoUpSLP
*R
) {
2015 return nodes_iterator(R
->VectorizableTree
.begin());
2018 static nodes_iterator
nodes_end(BoUpSLP
*R
) {
2019 return nodes_iterator(R
->VectorizableTree
.end());
2022 static unsigned size(BoUpSLP
*R
) { return R
->VectorizableTree
.size(); }
2025 template <> struct DOTGraphTraits
<BoUpSLP
*> : public DefaultDOTGraphTraits
{
2026 using TreeEntry
= BoUpSLP::TreeEntry
;
2028 DOTGraphTraits(bool isSimple
= false) : DefaultDOTGraphTraits(isSimple
) {}
2030 std::string
getNodeLabel(const TreeEntry
*Entry
, const BoUpSLP
*R
) {
2032 raw_string_ostream
OS(Str
);
2033 if (isSplat(Entry
->Scalars
)) {
2034 OS
<< "<splat> " << *Entry
->Scalars
[0];
2037 for (auto V
: Entry
->Scalars
) {
2040 R
->ExternalUses
.begin(), R
->ExternalUses
.end(),
2041 [&](const BoUpSLP::ExternalUser
&EU
) { return EU
.Scalar
== V
; }))
2048 static std::string
getNodeAttributes(const TreeEntry
*Entry
,
2050 if (Entry
->NeedToGather
)
2056 } // end namespace llvm
2058 void BoUpSLP::buildTree(ArrayRef
<Value
*> Roots
,
2059 ArrayRef
<Value
*> UserIgnoreLst
) {
2060 ExtraValueToDebugLocsMap ExternallyUsedValues
;
2061 buildTree(Roots
, ExternallyUsedValues
, UserIgnoreLst
);
2064 void BoUpSLP::buildTree(ArrayRef
<Value
*> Roots
,
2065 ExtraValueToDebugLocsMap
&ExternallyUsedValues
,
2066 ArrayRef
<Value
*> UserIgnoreLst
) {
2068 UserIgnoreList
= UserIgnoreLst
;
2069 if (!allSameType(Roots
))
2071 buildTree_rec(Roots
, 0, EdgeInfo());
2073 // Collect the values that we need to extract from the tree.
2074 for (auto &TEPtr
: VectorizableTree
) {
2075 TreeEntry
*Entry
= TEPtr
.get();
2077 // No need to handle users of gathered values.
2078 if (Entry
->NeedToGather
)
2082 for (int Lane
= 0, LE
= Entry
->Scalars
.size(); Lane
!= LE
; ++Lane
) {
2083 Value
*Scalar
= Entry
->Scalars
[Lane
];
2084 int FoundLane
= Lane
;
2085 if (!Entry
->ReuseShuffleIndices
.empty()) {
2087 std::distance(Entry
->ReuseShuffleIndices
.begin(),
2088 llvm::find(Entry
->ReuseShuffleIndices
, FoundLane
));
2091 // Check if the scalar is externally used as an extra arg.
2092 auto ExtI
= ExternallyUsedValues
.find(Scalar
);
2093 if (ExtI
!= ExternallyUsedValues
.end()) {
2094 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
2095 << Lane
<< " from " << *Scalar
<< ".\n");
2096 ExternalUses
.emplace_back(Scalar
, nullptr, FoundLane
);
2098 for (User
*U
: Scalar
->users()) {
2099 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U
<< ".\n");
2101 Instruction
*UserInst
= dyn_cast
<Instruction
>(U
);
2105 // Skip in-tree scalars that become vectors
2106 if (TreeEntry
*UseEntry
= getTreeEntry(U
)) {
2107 Value
*UseScalar
= UseEntry
->Scalars
[0];
2108 // Some in-tree scalars will remain as scalar in vectorized
2109 // instructions. If that is the case, the one in Lane 0 will
2111 if (UseScalar
!= U
||
2112 !InTreeUserNeedToExtract(Scalar
, UserInst
, TLI
)) {
2113 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
2115 assert(!UseEntry
->NeedToGather
&& "Bad state");
2120 // Ignore users in the user ignore list.
2121 if (is_contained(UserIgnoreList
, UserInst
))
2124 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U
<< " from lane "
2125 << Lane
<< " from " << *Scalar
<< ".\n");
2126 ExternalUses
.push_back(ExternalUser(Scalar
, U
, FoundLane
));
2132 void BoUpSLP::buildTree_rec(ArrayRef
<Value
*> VL
, unsigned Depth
,
2133 const EdgeInfo
&UserTreeIdx
) {
2134 assert((allConstant(VL
) || allSameType(VL
)) && "Invalid types!");
2136 InstructionsState S
= getSameOpcode(VL
);
2137 if (Depth
== RecursionMaxDepth
) {
2138 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
2139 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2143 // Don't handle vectors.
2144 if (S
.OpValue
->getType()->isVectorTy()) {
2145 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
2146 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2150 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(S
.OpValue
))
2151 if (SI
->getValueOperand()->getType()->isVectorTy()) {
2152 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
2153 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2157 // If all of the operands are identical or constant we have a simple solution.
2158 if (allConstant(VL
) || isSplat(VL
) || !allSameBlock(VL
) || !S
.getOpcode()) {
2159 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
2160 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2164 // We now know that this is a vector of instructions of the same type from
2167 // Don't vectorize ephemeral values.
2168 for (Value
*V
: VL
) {
2169 if (EphValues
.count(V
)) {
2170 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2171 << ") is ephemeral.\n");
2172 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2177 // Check if this is a duplicate of another entry.
2178 if (TreeEntry
*E
= getTreeEntry(S
.OpValue
)) {
2179 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S
.OpValue
<< ".\n");
2180 if (!E
->isSame(VL
)) {
2181 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
2182 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2185 // Record the reuse of the tree node. FIXME, currently this is only used to
2186 // properly draw the graph rather than for the actual vectorization.
2187 E
->UserTreeIndices
.push_back(UserTreeIdx
);
2188 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S
.OpValue
2193 // Check that none of the instructions in the bundle are already in the tree.
2194 for (Value
*V
: VL
) {
2195 auto *I
= dyn_cast
<Instruction
>(V
);
2198 if (getTreeEntry(I
)) {
2199 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2200 << ") is already in tree.\n");
2201 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2206 // If any of the scalars is marked as a value that needs to stay scalar, then
2207 // we need to gather the scalars.
2208 // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
2209 for (Value
*V
: VL
) {
2210 if (MustGather
.count(V
) || is_contained(UserIgnoreList
, V
)) {
2211 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
2212 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2217 // Check that all of the users of the scalars that we want to vectorize are
2219 auto *VL0
= cast
<Instruction
>(S
.OpValue
);
2220 BasicBlock
*BB
= VL0
->getParent();
2222 if (!DT
->isReachableFromEntry(BB
)) {
2223 // Don't go into unreachable blocks. They may contain instructions with
2224 // dependency cycles which confuse the final scheduling.
2225 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
2226 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2230 // Check that every instruction appears once in this bundle.
2231 SmallVector
<unsigned, 4> ReuseShuffleIndicies
;
2232 SmallVector
<Value
*, 4> UniqueValues
;
2233 DenseMap
<Value
*, unsigned> UniquePositions
;
2234 for (Value
*V
: VL
) {
2235 auto Res
= UniquePositions
.try_emplace(V
, UniqueValues
.size());
2236 ReuseShuffleIndicies
.emplace_back(Res
.first
->second
);
2238 UniqueValues
.emplace_back(V
);
2240 size_t NumUniqueScalarValues
= UniqueValues
.size();
2241 if (NumUniqueScalarValues
== VL
.size()) {
2242 ReuseShuffleIndicies
.clear();
2244 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
2245 if (NumUniqueScalarValues
<= 1 ||
2246 !llvm::isPowerOf2_32(NumUniqueScalarValues
)) {
2247 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
2248 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2254 auto &BSRef
= BlocksSchedules
[BB
];
2256 BSRef
= std::make_unique
<BlockScheduling
>(BB
);
2258 BlockScheduling
&BS
= *BSRef
.get();
2260 Optional
<ScheduleData
*> Bundle
= BS
.tryScheduleBundle(VL
, this, S
);
2262 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
2263 assert((!BS
.getScheduleData(VL0
) ||
2264 !BS
.getScheduleData(VL0
)->isPartOfBundle()) &&
2265 "tryScheduleBundle should cancelScheduling on failure");
2266 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2267 ReuseShuffleIndicies
);
2270 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
2272 unsigned ShuffleOrOp
= S
.isAltShuffle() ?
2273 (unsigned) Instruction::ShuffleVector
: S
.getOpcode();
2274 switch (ShuffleOrOp
) {
2275 case Instruction::PHI
: {
2276 auto *PH
= cast
<PHINode
>(VL0
);
2278 // Check for terminator values (e.g. invoke).
2279 for (unsigned j
= 0; j
< VL
.size(); ++j
)
2280 for (unsigned i
= 0, e
= PH
->getNumIncomingValues(); i
< e
; ++i
) {
2281 Instruction
*Term
= dyn_cast
<Instruction
>(
2282 cast
<PHINode
>(VL
[j
])->getIncomingValueForBlock(
2283 PH
->getIncomingBlock(i
)));
2284 if (Term
&& Term
->isTerminator()) {
2286 << "SLP: Need to swizzle PHINodes (terminator use).\n");
2287 BS
.cancelScheduling(VL
, VL0
);
2288 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2289 ReuseShuffleIndicies
);
2295 newTreeEntry(VL
, Bundle
, S
, UserTreeIdx
, ReuseShuffleIndicies
);
2296 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
2298 // Keeps the reordered operands to avoid code duplication.
2299 SmallVector
<ValueList
, 2> OperandsVec
;
2300 for (unsigned i
= 0, e
= PH
->getNumIncomingValues(); i
< e
; ++i
) {
2302 // Prepare the operand vector.
2304 Operands
.push_back(cast
<PHINode
>(j
)->getIncomingValueForBlock(
2305 PH
->getIncomingBlock(i
)));
2306 TE
->setOperand(i
, Operands
);
2307 OperandsVec
.push_back(Operands
);
2309 for (unsigned OpIdx
= 0, OpE
= OperandsVec
.size(); OpIdx
!= OpE
; ++OpIdx
)
2310 buildTree_rec(OperandsVec
[OpIdx
], Depth
+ 1, {TE
, OpIdx
});
2313 case Instruction::ExtractValue
:
2314 case Instruction::ExtractElement
: {
2315 OrdersType CurrentOrder
;
2316 bool Reuse
= canReuseExtract(VL
, VL0
, CurrentOrder
);
2318 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
2319 ++NumOpsWantToKeepOriginalOrder
;
2320 newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2321 ReuseShuffleIndicies
);
2322 // This is a special case, as it does not gather, but at the same time
2323 // we are not extending buildTree_rec() towards the operands.
2325 Op0
.assign(VL
.size(), VL0
->getOperand(0));
2326 VectorizableTree
.back()->setOperand(0, Op0
);
2329 if (!CurrentOrder
.empty()) {
2331 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
2333 for (unsigned Idx
: CurrentOrder
)
2334 dbgs() << " " << Idx
;
2337 // Insert new order with initial value 0, if it does not exist,
2338 // otherwise return the iterator to the existing one.
2339 auto StoredCurrentOrderAndNum
=
2340 NumOpsWantToKeepOrder
.try_emplace(CurrentOrder
).first
;
2341 ++StoredCurrentOrderAndNum
->getSecond();
2342 newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2343 ReuseShuffleIndicies
,
2344 StoredCurrentOrderAndNum
->getFirst());
2345 // This is a special case, as it does not gather, but at the same time
2346 // we are not extending buildTree_rec() towards the operands.
2348 Op0
.assign(VL
.size(), VL0
->getOperand(0));
2349 VectorizableTree
.back()->setOperand(0, Op0
);
2352 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
2353 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2354 ReuseShuffleIndicies
);
2355 BS
.cancelScheduling(VL
, VL0
);
2358 case Instruction::Load
: {
2359 // Check that a vectorized load would load the same memory as a scalar
2360 // load. For example, we don't want to vectorize loads that are smaller
2361 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
2362 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
2363 // from such a struct, we read/write packed bits disagreeing with the
2364 // unvectorized version.
2365 Type
*ScalarTy
= VL0
->getType();
2367 if (DL
->getTypeSizeInBits(ScalarTy
) !=
2368 DL
->getTypeAllocSizeInBits(ScalarTy
)) {
2369 BS
.cancelScheduling(VL
, VL0
);
2370 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2371 ReuseShuffleIndicies
);
2372 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
2376 // Make sure all loads in the bundle are simple - we can't vectorize
2377 // atomic or volatile loads.
2378 SmallVector
<Value
*, 4> PointerOps(VL
.size());
2379 auto POIter
= PointerOps
.begin();
2380 for (Value
*V
: VL
) {
2381 auto *L
= cast
<LoadInst
>(V
);
2382 if (!L
->isSimple()) {
2383 BS
.cancelScheduling(VL
, VL0
);
2384 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2385 ReuseShuffleIndicies
);
2386 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
2389 *POIter
= L
->getPointerOperand();
2393 OrdersType CurrentOrder
;
2394 // Check the order of pointer operands.
2395 if (llvm::sortPtrAccesses(PointerOps
, *DL
, *SE
, CurrentOrder
)) {
2398 if (CurrentOrder
.empty()) {
2399 Ptr0
= PointerOps
.front();
2400 PtrN
= PointerOps
.back();
2402 Ptr0
= PointerOps
[CurrentOrder
.front()];
2403 PtrN
= PointerOps
[CurrentOrder
.back()];
2405 const SCEV
*Scev0
= SE
->getSCEV(Ptr0
);
2406 const SCEV
*ScevN
= SE
->getSCEV(PtrN
);
2408 dyn_cast
<SCEVConstant
>(SE
->getMinusSCEV(ScevN
, Scev0
));
2409 uint64_t Size
= DL
->getTypeAllocSize(ScalarTy
);
2410 // Check that the sorted loads are consecutive.
2411 if (Diff
&& Diff
->getAPInt().getZExtValue() == (VL
.size() - 1) * Size
) {
2412 if (CurrentOrder
.empty()) {
2413 // Original loads are consecutive and does not require reordering.
2414 ++NumOpsWantToKeepOriginalOrder
;
2415 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
,
2416 UserTreeIdx
, ReuseShuffleIndicies
);
2417 TE
->setOperandsInOrder();
2418 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
2421 auto I
= NumOpsWantToKeepOrder
.try_emplace(CurrentOrder
).first
;
2424 newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2425 ReuseShuffleIndicies
, I
->getFirst());
2426 TE
->setOperandsInOrder();
2427 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
2433 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
2434 BS
.cancelScheduling(VL
, VL0
);
2435 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2436 ReuseShuffleIndicies
);
2439 case Instruction::ZExt
:
2440 case Instruction::SExt
:
2441 case Instruction::FPToUI
:
2442 case Instruction::FPToSI
:
2443 case Instruction::FPExt
:
2444 case Instruction::PtrToInt
:
2445 case Instruction::IntToPtr
:
2446 case Instruction::SIToFP
:
2447 case Instruction::UIToFP
:
2448 case Instruction::Trunc
:
2449 case Instruction::FPTrunc
:
2450 case Instruction::BitCast
: {
2451 Type
*SrcTy
= VL0
->getOperand(0)->getType();
2452 for (Value
*V
: VL
) {
2453 Type
*Ty
= cast
<Instruction
>(V
)->getOperand(0)->getType();
2454 if (Ty
!= SrcTy
|| !isValidElementType(Ty
)) {
2455 BS
.cancelScheduling(VL
, VL0
);
2456 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2457 ReuseShuffleIndicies
);
2459 << "SLP: Gathering casts with different src types.\n");
2463 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2464 ReuseShuffleIndicies
);
2465 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
2467 TE
->setOperandsInOrder();
2468 for (unsigned i
= 0, e
= VL0
->getNumOperands(); i
< e
; ++i
) {
2470 // Prepare the operand vector.
2472 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(i
));
2474 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2478 case Instruction::ICmp
:
2479 case Instruction::FCmp
: {
2480 // Check that all of the compares have the same predicate.
2481 CmpInst::Predicate P0
= cast
<CmpInst
>(VL0
)->getPredicate();
2482 CmpInst::Predicate SwapP0
= CmpInst::getSwappedPredicate(P0
);
2483 Type
*ComparedTy
= VL0
->getOperand(0)->getType();
2484 for (Value
*V
: VL
) {
2485 CmpInst
*Cmp
= cast
<CmpInst
>(V
);
2486 if ((Cmp
->getPredicate() != P0
&& Cmp
->getPredicate() != SwapP0
) ||
2487 Cmp
->getOperand(0)->getType() != ComparedTy
) {
2488 BS
.cancelScheduling(VL
, VL0
);
2489 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2490 ReuseShuffleIndicies
);
2492 << "SLP: Gathering cmp with different predicate.\n");
2497 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2498 ReuseShuffleIndicies
);
2499 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
2501 ValueList Left
, Right
;
2502 if (cast
<CmpInst
>(VL0
)->isCommutative()) {
2503 // Commutative predicate - collect + sort operands of the instructions
2504 // so that each side is more likely to have the same opcode.
2505 assert(P0
== SwapP0
&& "Commutative Predicate mismatch");
2506 reorderInputsAccordingToOpcode(VL
, Left
, Right
, *DL
, *SE
);
2508 // Collect operands - commute if it uses the swapped predicate.
2509 for (Value
*V
: VL
) {
2510 auto *Cmp
= cast
<CmpInst
>(V
);
2511 Value
*LHS
= Cmp
->getOperand(0);
2512 Value
*RHS
= Cmp
->getOperand(1);
2513 if (Cmp
->getPredicate() != P0
)
2514 std::swap(LHS
, RHS
);
2515 Left
.push_back(LHS
);
2516 Right
.push_back(RHS
);
2519 TE
->setOperand(0, Left
);
2520 TE
->setOperand(1, Right
);
2521 buildTree_rec(Left
, Depth
+ 1, {TE
, 0});
2522 buildTree_rec(Right
, Depth
+ 1, {TE
, 1});
2525 case Instruction::Select
:
2526 case Instruction::FNeg
:
2527 case Instruction::Add
:
2528 case Instruction::FAdd
:
2529 case Instruction::Sub
:
2530 case Instruction::FSub
:
2531 case Instruction::Mul
:
2532 case Instruction::FMul
:
2533 case Instruction::UDiv
:
2534 case Instruction::SDiv
:
2535 case Instruction::FDiv
:
2536 case Instruction::URem
:
2537 case Instruction::SRem
:
2538 case Instruction::FRem
:
2539 case Instruction::Shl
:
2540 case Instruction::LShr
:
2541 case Instruction::AShr
:
2542 case Instruction::And
:
2543 case Instruction::Or
:
2544 case Instruction::Xor
: {
2545 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2546 ReuseShuffleIndicies
);
2547 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
2549 // Sort operands of the instructions so that each side is more likely to
2550 // have the same opcode.
2551 if (isa
<BinaryOperator
>(VL0
) && VL0
->isCommutative()) {
2552 ValueList Left
, Right
;
2553 reorderInputsAccordingToOpcode(VL
, Left
, Right
, *DL
, *SE
);
2554 TE
->setOperand(0, Left
);
2555 TE
->setOperand(1, Right
);
2556 buildTree_rec(Left
, Depth
+ 1, {TE
, 0});
2557 buildTree_rec(Right
, Depth
+ 1, {TE
, 1});
2561 TE
->setOperandsInOrder();
2562 for (unsigned i
= 0, e
= VL0
->getNumOperands(); i
< e
; ++i
) {
2564 // Prepare the operand vector.
2566 Operands
.push_back(cast
<Instruction
>(j
)->getOperand(i
));
2568 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2572 case Instruction::GetElementPtr
: {
2573 // We don't combine GEPs with complicated (nested) indexing.
2574 for (Value
*V
: VL
) {
2575 if (cast
<Instruction
>(V
)->getNumOperands() != 2) {
2576 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
2577 BS
.cancelScheduling(VL
, VL0
);
2578 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2579 ReuseShuffleIndicies
);
2584 // We can't combine several GEPs into one vector if they operate on
2586 Type
*Ty0
= VL0
->getOperand(0)->getType();
2587 for (Value
*V
: VL
) {
2588 Type
*CurTy
= cast
<Instruction
>(V
)->getOperand(0)->getType();
2591 << "SLP: not-vectorizable GEP (different types).\n");
2592 BS
.cancelScheduling(VL
, VL0
);
2593 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2594 ReuseShuffleIndicies
);
2599 // We don't combine GEPs with non-constant indexes.
2600 for (Value
*V
: VL
) {
2601 auto Op
= cast
<Instruction
>(V
)->getOperand(1);
2602 if (!isa
<ConstantInt
>(Op
)) {
2604 << "SLP: not-vectorizable GEP (non-constant indexes).\n");
2605 BS
.cancelScheduling(VL
, VL0
);
2606 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2607 ReuseShuffleIndicies
);
2612 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2613 ReuseShuffleIndicies
);
2614 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
2615 TE
->setOperandsInOrder();
2616 for (unsigned i
= 0, e
= 2; i
< e
; ++i
) {
2618 // Prepare the operand vector.
2620 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(i
));
2622 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2626 case Instruction::Store
: {
2627 // Check if the stores are consecutive or if we need to swizzle them.
2628 for (unsigned i
= 0, e
= VL
.size() - 1; i
< e
; ++i
)
2629 if (!isConsecutiveAccess(VL
[i
], VL
[i
+ 1], *DL
, *SE
)) {
2630 BS
.cancelScheduling(VL
, VL0
);
2631 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2632 ReuseShuffleIndicies
);
2633 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
2637 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2638 ReuseShuffleIndicies
);
2639 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
2643 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(0));
2644 TE
->setOperandsInOrder();
2645 buildTree_rec(Operands
, Depth
+ 1, {TE
, 0});
2648 case Instruction::Call
: {
2649 // Check if the calls are all to the same vectorizable intrinsic.
2650 CallInst
*CI
= cast
<CallInst
>(VL0
);
2651 // Check if this is an Intrinsic call or something that can be
2652 // represented by an intrinsic call
2653 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
2654 if (!isTriviallyVectorizable(ID
)) {
2655 BS
.cancelScheduling(VL
, VL0
);
2656 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2657 ReuseShuffleIndicies
);
2658 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
2661 Function
*Int
= CI
->getCalledFunction();
2662 unsigned NumArgs
= CI
->getNumArgOperands();
2663 SmallVector
<Value
*, 4> ScalarArgs(NumArgs
, nullptr);
2664 for (unsigned j
= 0; j
!= NumArgs
; ++j
)
2665 if (hasVectorInstrinsicScalarOpd(ID
, j
))
2666 ScalarArgs
[j
] = CI
->getArgOperand(j
);
2667 for (Value
*V
: VL
) {
2668 CallInst
*CI2
= dyn_cast
<CallInst
>(V
);
2669 if (!CI2
|| CI2
->getCalledFunction() != Int
||
2670 getVectorIntrinsicIDForCall(CI2
, TLI
) != ID
||
2671 !CI
->hasIdenticalOperandBundleSchema(*CI2
)) {
2672 BS
.cancelScheduling(VL
, VL0
);
2673 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2674 ReuseShuffleIndicies
);
2675 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI
<< "!=" << *V
2679 // Some intrinsics have scalar arguments and should be same in order for
2680 // them to be vectorized.
2681 for (unsigned j
= 0; j
!= NumArgs
; ++j
) {
2682 if (hasVectorInstrinsicScalarOpd(ID
, j
)) {
2683 Value
*A1J
= CI2
->getArgOperand(j
);
2684 if (ScalarArgs
[j
] != A1J
) {
2685 BS
.cancelScheduling(VL
, VL0
);
2686 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2687 ReuseShuffleIndicies
);
2688 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
2689 << " argument " << ScalarArgs
[j
] << "!=" << A1J
2695 // Verify that the bundle operands are identical between the two calls.
2696 if (CI
->hasOperandBundles() &&
2697 !std::equal(CI
->op_begin() + CI
->getBundleOperandsStartIndex(),
2698 CI
->op_begin() + CI
->getBundleOperandsEndIndex(),
2699 CI2
->op_begin() + CI2
->getBundleOperandsStartIndex())) {
2700 BS
.cancelScheduling(VL
, VL0
);
2701 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2702 ReuseShuffleIndicies
);
2703 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
2704 << *CI
<< "!=" << *V
<< '\n');
2709 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2710 ReuseShuffleIndicies
);
2711 TE
->setOperandsInOrder();
2712 for (unsigned i
= 0, e
= CI
->getNumArgOperands(); i
!= e
; ++i
) {
2714 // Prepare the operand vector.
2715 for (Value
*V
: VL
) {
2716 auto *CI2
= cast
<CallInst
>(V
);
2717 Operands
.push_back(CI2
->getArgOperand(i
));
2719 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2723 case Instruction::ShuffleVector
: {
2724 // If this is not an alternate sequence of opcode like add-sub
2725 // then do not vectorize this instruction.
2726 if (!S
.isAltShuffle()) {
2727 BS
.cancelScheduling(VL
, VL0
);
2728 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2729 ReuseShuffleIndicies
);
2730 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
2733 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2734 ReuseShuffleIndicies
);
2735 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
2737 // Reorder operands if reordering would enable vectorization.
2738 if (isa
<BinaryOperator
>(VL0
)) {
2739 ValueList Left
, Right
;
2740 reorderInputsAccordingToOpcode(VL
, Left
, Right
, *DL
, *SE
);
2741 TE
->setOperand(0, Left
);
2742 TE
->setOperand(1, Right
);
2743 buildTree_rec(Left
, Depth
+ 1, {TE
, 0});
2744 buildTree_rec(Right
, Depth
+ 1, {TE
, 1});
2748 TE
->setOperandsInOrder();
2749 for (unsigned i
= 0, e
= VL0
->getNumOperands(); i
< e
; ++i
) {
2751 // Prepare the operand vector.
2753 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(i
));
2755 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2760 BS
.cancelScheduling(VL
, VL0
);
2761 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2762 ReuseShuffleIndicies
);
2763 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
2768 unsigned BoUpSLP::canMapToVector(Type
*T
, const DataLayout
&DL
) const {
2771 auto *ST
= dyn_cast
<StructType
>(T
);
2773 N
= ST
->getNumElements();
2774 EltTy
= *ST
->element_begin();
2776 N
= cast
<ArrayType
>(T
)->getNumElements();
2777 EltTy
= cast
<ArrayType
>(T
)->getElementType();
2779 if (!isValidElementType(EltTy
))
2781 uint64_t VTSize
= DL
.getTypeStoreSizeInBits(VectorType::get(EltTy
, N
));
2782 if (VTSize
< MinVecRegSize
|| VTSize
> MaxVecRegSize
|| VTSize
!= DL
.getTypeStoreSizeInBits(T
))
2785 // Check that struct is homogeneous.
2786 for (const auto *Ty
: ST
->elements())
2793 bool BoUpSLP::canReuseExtract(ArrayRef
<Value
*> VL
, Value
*OpValue
,
2794 SmallVectorImpl
<unsigned> &CurrentOrder
) const {
2795 Instruction
*E0
= cast
<Instruction
>(OpValue
);
2796 assert(E0
->getOpcode() == Instruction::ExtractElement
||
2797 E0
->getOpcode() == Instruction::ExtractValue
);
2798 assert(E0
->getOpcode() == getSameOpcode(VL
).getOpcode() && "Invalid opcode");
2799 // Check if all of the extracts come from the same vector and from the
2801 Value
*Vec
= E0
->getOperand(0);
2803 CurrentOrder
.clear();
2805 // We have to extract from a vector/aggregate with the same number of elements.
2807 if (E0
->getOpcode() == Instruction::ExtractValue
) {
2808 const DataLayout
&DL
= E0
->getModule()->getDataLayout();
2809 NElts
= canMapToVector(Vec
->getType(), DL
);
2812 // Check if load can be rewritten as load of vector.
2813 LoadInst
*LI
= dyn_cast
<LoadInst
>(Vec
);
2814 if (!LI
|| !LI
->isSimple() || !LI
->hasNUses(VL
.size()))
2817 NElts
= Vec
->getType()->getVectorNumElements();
2820 if (NElts
!= VL
.size())
2823 // Check that all of the indices extract from the correct offset.
2824 bool ShouldKeepOrder
= true;
2825 unsigned E
= VL
.size();
2826 // Assign to all items the initial value E + 1 so we can check if the extract
2827 // instruction index was used already.
2828 // Also, later we can check that all the indices are used and we have a
2829 // consecutive access in the extract instructions, by checking that no
2830 // element of CurrentOrder still has value E + 1.
2831 CurrentOrder
.assign(E
, E
+ 1);
2833 for (; I
< E
; ++I
) {
2834 auto *Inst
= cast
<Instruction
>(VL
[I
]);
2835 if (Inst
->getOperand(0) != Vec
)
2837 Optional
<unsigned> Idx
= getExtractIndex(Inst
);
2840 const unsigned ExtIdx
= *Idx
;
2842 if (ExtIdx
>= E
|| CurrentOrder
[ExtIdx
] != E
+ 1)
2844 ShouldKeepOrder
= false;
2845 CurrentOrder
[ExtIdx
] = I
;
2847 if (CurrentOrder
[I
] != E
+ 1)
2849 CurrentOrder
[I
] = I
;
2853 CurrentOrder
.clear();
2857 return ShouldKeepOrder
;
2860 bool BoUpSLP::areAllUsersVectorized(Instruction
*I
) const {
2861 return I
->hasOneUse() ||
2862 std::all_of(I
->user_begin(), I
->user_end(), [this](User
*U
) {
2863 return ScalarToTreeEntry
.count(U
) > 0;
2867 int BoUpSLP::getEntryCost(TreeEntry
*E
) {
2868 ArrayRef
<Value
*> VL
= E
->Scalars
;
2870 Type
*ScalarTy
= VL
[0]->getType();
2871 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(VL
[0]))
2872 ScalarTy
= SI
->getValueOperand()->getType();
2873 else if (CmpInst
*CI
= dyn_cast
<CmpInst
>(VL
[0]))
2874 ScalarTy
= CI
->getOperand(0)->getType();
2875 VectorType
*VecTy
= VectorType::get(ScalarTy
, VL
.size());
2877 // If we have computed a smaller type for the expression, update VecTy so
2878 // that the costs will be accurate.
2879 if (MinBWs
.count(VL
[0]))
2880 VecTy
= VectorType::get(
2881 IntegerType::get(F
->getContext(), MinBWs
[VL
[0]].first
), VL
.size());
2883 unsigned ReuseShuffleNumbers
= E
->ReuseShuffleIndices
.size();
2884 bool NeedToShuffleReuses
= !E
->ReuseShuffleIndices
.empty();
2885 int ReuseShuffleCost
= 0;
2886 if (NeedToShuffleReuses
) {
2888 TTI
->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc
, VecTy
);
2890 if (E
->NeedToGather
) {
2891 if (allConstant(VL
))
2894 return ReuseShuffleCost
+
2895 TTI
->getShuffleCost(TargetTransformInfo::SK_Broadcast
, VecTy
, 0);
2897 if (E
->getOpcode() == Instruction::ExtractElement
&&
2898 allSameType(VL
) && allSameBlock(VL
)) {
2899 Optional
<TargetTransformInfo::ShuffleKind
> ShuffleKind
= isShuffle(VL
);
2900 if (ShuffleKind
.hasValue()) {
2901 int Cost
= TTI
->getShuffleCost(ShuffleKind
.getValue(), VecTy
);
2902 for (auto *V
: VL
) {
2903 // If all users of instruction are going to be vectorized and this
2904 // instruction itself is not going to be vectorized, consider this
2905 // instruction as dead and remove its cost from the final cost of the
2907 if (areAllUsersVectorized(cast
<Instruction
>(V
)) &&
2908 !ScalarToTreeEntry
.count(V
)) {
2909 auto *IO
= cast
<ConstantInt
>(
2910 cast
<ExtractElementInst
>(V
)->getIndexOperand());
2911 Cost
-= TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
,
2912 IO
->getZExtValue());
2915 return ReuseShuffleCost
+ Cost
;
2918 return ReuseShuffleCost
+ getGatherCost(VL
);
2920 assert(E
->getOpcode() && allSameType(VL
) && allSameBlock(VL
) && "Invalid VL");
2921 Instruction
*VL0
= E
->getMainOp();
2922 unsigned ShuffleOrOp
=
2923 E
->isAltShuffle() ? (unsigned)Instruction::ShuffleVector
: E
->getOpcode();
2924 switch (ShuffleOrOp
) {
2925 case Instruction::PHI
:
2928 case Instruction::ExtractValue
:
2929 case Instruction::ExtractElement
:
2930 if (NeedToShuffleReuses
) {
2932 for (unsigned I
: E
->ReuseShuffleIndices
) {
2933 if (ShuffleOrOp
== Instruction::ExtractElement
) {
2934 auto *IO
= cast
<ConstantInt
>(
2935 cast
<ExtractElementInst
>(VL
[I
])->getIndexOperand());
2936 Idx
= IO
->getZExtValue();
2937 ReuseShuffleCost
-= TTI
->getVectorInstrCost(
2938 Instruction::ExtractElement
, VecTy
, Idx
);
2940 ReuseShuffleCost
-= TTI
->getVectorInstrCost(
2941 Instruction::ExtractElement
, VecTy
, Idx
);
2945 Idx
= ReuseShuffleNumbers
;
2946 for (Value
*V
: VL
) {
2947 if (ShuffleOrOp
== Instruction::ExtractElement
) {
2948 auto *IO
= cast
<ConstantInt
>(
2949 cast
<ExtractElementInst
>(V
)->getIndexOperand());
2950 Idx
= IO
->getZExtValue();
2955 TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
, Idx
);
2958 if (!E
->NeedToGather
) {
2959 int DeadCost
= ReuseShuffleCost
;
2960 if (!E
->ReorderIndices
.empty()) {
2961 // TODO: Merge this shuffle with the ReuseShuffleCost.
2962 DeadCost
+= TTI
->getShuffleCost(
2963 TargetTransformInfo::SK_PermuteSingleSrc
, VecTy
);
2965 for (unsigned i
= 0, e
= VL
.size(); i
< e
; ++i
) {
2966 Instruction
*E
= cast
<Instruction
>(VL
[i
]);
2967 // If all users are going to be vectorized, instruction can be
2968 // considered as dead.
2969 // The same, if have only one user, it will be vectorized for sure.
2970 if (areAllUsersVectorized(E
)) {
2971 // Take credit for instruction that will become dead.
2972 if (E
->hasOneUse()) {
2973 Instruction
*Ext
= E
->user_back();
2974 if ((isa
<SExtInst
>(Ext
) || isa
<ZExtInst
>(Ext
)) &&
2975 all_of(Ext
->users(),
2976 [](User
*U
) { return isa
<GetElementPtrInst
>(U
); })) {
2977 // Use getExtractWithExtendCost() to calculate the cost of
2978 // extractelement/ext pair.
2979 DeadCost
-= TTI
->getExtractWithExtendCost(
2980 Ext
->getOpcode(), Ext
->getType(), VecTy
, i
);
2981 // Add back the cost of s|zext which is subtracted separately.
2982 DeadCost
+= TTI
->getCastInstrCost(
2983 Ext
->getOpcode(), Ext
->getType(), E
->getType(), Ext
);
2988 TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
, i
);
2993 return ReuseShuffleCost
+ getGatherCost(VL
);
2995 case Instruction::ZExt
:
2996 case Instruction::SExt
:
2997 case Instruction::FPToUI
:
2998 case Instruction::FPToSI
:
2999 case Instruction::FPExt
:
3000 case Instruction::PtrToInt
:
3001 case Instruction::IntToPtr
:
3002 case Instruction::SIToFP
:
3003 case Instruction::UIToFP
:
3004 case Instruction::Trunc
:
3005 case Instruction::FPTrunc
:
3006 case Instruction::BitCast
: {
3007 Type
*SrcTy
= VL0
->getOperand(0)->getType();
3009 TTI
->getCastInstrCost(E
->getOpcode(), ScalarTy
, SrcTy
, VL0
);
3010 if (NeedToShuffleReuses
) {
3011 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3014 // Calculate the cost of this instruction.
3015 int ScalarCost
= VL
.size() * ScalarEltCost
;
3017 VectorType
*SrcVecTy
= VectorType::get(SrcTy
, VL
.size());
3019 // Check if the values are candidates to demote.
3020 if (!MinBWs
.count(VL0
) || VecTy
!= SrcVecTy
) {
3021 VecCost
= ReuseShuffleCost
+
3022 TTI
->getCastInstrCost(E
->getOpcode(), VecTy
, SrcVecTy
, VL0
);
3024 return VecCost
- ScalarCost
;
3026 case Instruction::FCmp
:
3027 case Instruction::ICmp
:
3028 case Instruction::Select
: {
3029 // Calculate the cost of this instruction.
3030 int ScalarEltCost
= TTI
->getCmpSelInstrCost(E
->getOpcode(), ScalarTy
,
3031 Builder
.getInt1Ty(), VL0
);
3032 if (NeedToShuffleReuses
) {
3033 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3035 VectorType
*MaskTy
= VectorType::get(Builder
.getInt1Ty(), VL
.size());
3036 int ScalarCost
= VecTy
->getNumElements() * ScalarEltCost
;
3037 int VecCost
= TTI
->getCmpSelInstrCost(E
->getOpcode(), VecTy
, MaskTy
, VL0
);
3038 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3040 case Instruction::FNeg
:
3041 case Instruction::Add
:
3042 case Instruction::FAdd
:
3043 case Instruction::Sub
:
3044 case Instruction::FSub
:
3045 case Instruction::Mul
:
3046 case Instruction::FMul
:
3047 case Instruction::UDiv
:
3048 case Instruction::SDiv
:
3049 case Instruction::FDiv
:
3050 case Instruction::URem
:
3051 case Instruction::SRem
:
3052 case Instruction::FRem
:
3053 case Instruction::Shl
:
3054 case Instruction::LShr
:
3055 case Instruction::AShr
:
3056 case Instruction::And
:
3057 case Instruction::Or
:
3058 case Instruction::Xor
: {
3059 // Certain instructions can be cheaper to vectorize if they have a
3060 // constant second vector operand.
3061 TargetTransformInfo::OperandValueKind Op1VK
=
3062 TargetTransformInfo::OK_AnyValue
;
3063 TargetTransformInfo::OperandValueKind Op2VK
=
3064 TargetTransformInfo::OK_UniformConstantValue
;
3065 TargetTransformInfo::OperandValueProperties Op1VP
=
3066 TargetTransformInfo::OP_None
;
3067 TargetTransformInfo::OperandValueProperties Op2VP
=
3068 TargetTransformInfo::OP_PowerOf2
;
3070 // If all operands are exactly the same ConstantInt then set the
3071 // operand kind to OK_UniformConstantValue.
3072 // If instead not all operands are constants, then set the operand kind
3073 // to OK_AnyValue. If all operands are constants but not the same,
3074 // then set the operand kind to OK_NonUniformConstantValue.
3075 ConstantInt
*CInt0
= nullptr;
3076 for (unsigned i
= 0, e
= VL
.size(); i
< e
; ++i
) {
3077 const Instruction
*I
= cast
<Instruction
>(VL
[i
]);
3078 unsigned OpIdx
= isa
<BinaryOperator
>(I
) ? 1 : 0;
3079 ConstantInt
*CInt
= dyn_cast
<ConstantInt
>(I
->getOperand(OpIdx
));
3081 Op2VK
= TargetTransformInfo::OK_AnyValue
;
3082 Op2VP
= TargetTransformInfo::OP_None
;
3085 if (Op2VP
== TargetTransformInfo::OP_PowerOf2
&&
3086 !CInt
->getValue().isPowerOf2())
3087 Op2VP
= TargetTransformInfo::OP_None
;
3093 Op2VK
= TargetTransformInfo::OK_NonUniformConstantValue
;
3096 SmallVector
<const Value
*, 4> Operands(VL0
->operand_values());
3097 int ScalarEltCost
= TTI
->getArithmeticInstrCost(
3098 E
->getOpcode(), ScalarTy
, Op1VK
, Op2VK
, Op1VP
, Op2VP
, Operands
);
3099 if (NeedToShuffleReuses
) {
3100 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3102 int ScalarCost
= VecTy
->getNumElements() * ScalarEltCost
;
3103 int VecCost
= TTI
->getArithmeticInstrCost(E
->getOpcode(), VecTy
, Op1VK
,
3104 Op2VK
, Op1VP
, Op2VP
, Operands
);
3105 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3107 case Instruction::GetElementPtr
: {
3108 TargetTransformInfo::OperandValueKind Op1VK
=
3109 TargetTransformInfo::OK_AnyValue
;
3110 TargetTransformInfo::OperandValueKind Op2VK
=
3111 TargetTransformInfo::OK_UniformConstantValue
;
3114 TTI
->getArithmeticInstrCost(Instruction::Add
, ScalarTy
, Op1VK
, Op2VK
);
3115 if (NeedToShuffleReuses
) {
3116 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3118 int ScalarCost
= VecTy
->getNumElements() * ScalarEltCost
;
3120 TTI
->getArithmeticInstrCost(Instruction::Add
, VecTy
, Op1VK
, Op2VK
);
3121 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3123 case Instruction::Load
: {
3124 // Cost of wide load - cost of scalar loads.
3125 unsigned alignment
= cast
<LoadInst
>(VL0
)->getAlignment();
3127 TTI
->getMemoryOpCost(Instruction::Load
, ScalarTy
, alignment
, 0, VL0
);
3128 if (NeedToShuffleReuses
) {
3129 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3131 int ScalarLdCost
= VecTy
->getNumElements() * ScalarEltCost
;
3133 TTI
->getMemoryOpCost(Instruction::Load
, VecTy
, alignment
, 0, VL0
);
3134 if (!E
->ReorderIndices
.empty()) {
3135 // TODO: Merge this shuffle with the ReuseShuffleCost.
3136 VecLdCost
+= TTI
->getShuffleCost(
3137 TargetTransformInfo::SK_PermuteSingleSrc
, VecTy
);
3139 return ReuseShuffleCost
+ VecLdCost
- ScalarLdCost
;
3141 case Instruction::Store
: {
3142 // We know that we can merge the stores. Calculate the cost.
3143 unsigned alignment
= cast
<StoreInst
>(VL0
)->getAlignment();
3145 TTI
->getMemoryOpCost(Instruction::Store
, ScalarTy
, alignment
, 0, VL0
);
3146 if (NeedToShuffleReuses
) {
3147 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3149 int ScalarStCost
= VecTy
->getNumElements() * ScalarEltCost
;
3151 TTI
->getMemoryOpCost(Instruction::Store
, VecTy
, alignment
, 0, VL0
);
3152 return ReuseShuffleCost
+ VecStCost
- ScalarStCost
;
3154 case Instruction::Call
: {
3155 CallInst
*CI
= cast
<CallInst
>(VL0
);
3156 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
3158 // Calculate the cost of the scalar and vector calls.
3159 SmallVector
<Type
*, 4> ScalarTys
;
3160 for (unsigned op
= 0, opc
= CI
->getNumArgOperands(); op
!= opc
; ++op
)
3161 ScalarTys
.push_back(CI
->getArgOperand(op
)->getType());
3164 if (auto *FPMO
= dyn_cast
<FPMathOperator
>(CI
))
3165 FMF
= FPMO
->getFastMathFlags();
3168 TTI
->getIntrinsicInstrCost(ID
, ScalarTy
, ScalarTys
, FMF
);
3169 if (NeedToShuffleReuses
) {
3170 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3172 int ScalarCallCost
= VecTy
->getNumElements() * ScalarEltCost
;
3174 SmallVector
<Value
*, 4> Args(CI
->arg_operands());
3175 int VecCallCost
= TTI
->getIntrinsicInstrCost(ID
, CI
->getType(), Args
, FMF
,
3176 VecTy
->getNumElements());
3178 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost
- ScalarCallCost
3179 << " (" << VecCallCost
<< "-" << ScalarCallCost
<< ")"
3180 << " for " << *CI
<< "\n");
3182 return ReuseShuffleCost
+ VecCallCost
- ScalarCallCost
;
3184 case Instruction::ShuffleVector
: {
3185 assert(E
->isAltShuffle() &&
3186 ((Instruction::isBinaryOp(E
->getOpcode()) &&
3187 Instruction::isBinaryOp(E
->getAltOpcode())) ||
3188 (Instruction::isCast(E
->getOpcode()) &&
3189 Instruction::isCast(E
->getAltOpcode()))) &&
3190 "Invalid Shuffle Vector Operand");
3192 if (NeedToShuffleReuses
) {
3193 for (unsigned Idx
: E
->ReuseShuffleIndices
) {
3194 Instruction
*I
= cast
<Instruction
>(VL
[Idx
]);
3195 ReuseShuffleCost
-= TTI
->getInstructionCost(
3196 I
, TargetTransformInfo::TCK_RecipThroughput
);
3198 for (Value
*V
: VL
) {
3199 Instruction
*I
= cast
<Instruction
>(V
);
3200 ReuseShuffleCost
+= TTI
->getInstructionCost(
3201 I
, TargetTransformInfo::TCK_RecipThroughput
);
3204 for (Value
*V
: VL
) {
3205 Instruction
*I
= cast
<Instruction
>(V
);
3206 assert(E
->isOpcodeOrAlt(I
) && "Unexpected main/alternate opcode");
3207 ScalarCost
+= TTI
->getInstructionCost(
3208 I
, TargetTransformInfo::TCK_RecipThroughput
);
3210 // VecCost is equal to sum of the cost of creating 2 vectors
3211 // and the cost of creating shuffle.
3213 if (Instruction::isBinaryOp(E
->getOpcode())) {
3214 VecCost
= TTI
->getArithmeticInstrCost(E
->getOpcode(), VecTy
);
3215 VecCost
+= TTI
->getArithmeticInstrCost(E
->getAltOpcode(), VecTy
);
3217 Type
*Src0SclTy
= E
->getMainOp()->getOperand(0)->getType();
3218 Type
*Src1SclTy
= E
->getAltOp()->getOperand(0)->getType();
3219 VectorType
*Src0Ty
= VectorType::get(Src0SclTy
, VL
.size());
3220 VectorType
*Src1Ty
= VectorType::get(Src1SclTy
, VL
.size());
3221 VecCost
= TTI
->getCastInstrCost(E
->getOpcode(), VecTy
, Src0Ty
);
3222 VecCost
+= TTI
->getCastInstrCost(E
->getAltOpcode(), VecTy
, Src1Ty
);
3224 VecCost
+= TTI
->getShuffleCost(TargetTransformInfo::SK_Select
, VecTy
, 0);
3225 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3228 llvm_unreachable("Unknown instruction");
3232 bool BoUpSLP::isFullyVectorizableTinyTree() const {
3233 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
3234 << VectorizableTree
.size() << " is fully vectorizable .\n");
3236 // We only handle trees of heights 1 and 2.
3237 if (VectorizableTree
.size() == 1 && !VectorizableTree
[0]->NeedToGather
)
3240 if (VectorizableTree
.size() != 2)
3243 // Handle splat and all-constants stores.
3244 if (!VectorizableTree
[0]->NeedToGather
&&
3245 (allConstant(VectorizableTree
[1]->Scalars
) ||
3246 isSplat(VectorizableTree
[1]->Scalars
)))
3249 // Gathering cost would be too much for tiny trees.
3250 if (VectorizableTree
[0]->NeedToGather
|| VectorizableTree
[1]->NeedToGather
)
3256 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
3257 // We can vectorize the tree if its size is greater than or equal to the
3258 // minimum size specified by the MinTreeSize command line option.
3259 if (VectorizableTree
.size() >= MinTreeSize
)
3262 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
3263 // can vectorize it if we can prove it fully vectorizable.
3264 if (isFullyVectorizableTinyTree())
3267 assert(VectorizableTree
.empty()
3268 ? ExternalUses
.empty()
3269 : true && "We shouldn't have any external users");
3271 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
3276 int BoUpSLP::getSpillCost() const {
3277 // Walk from the bottom of the tree to the top, tracking which values are
3278 // live. When we see a call instruction that is not part of our tree,
3279 // query TTI to see if there is a cost to keeping values live over it
3280 // (for example, if spills and fills are required).
3281 unsigned BundleWidth
= VectorizableTree
.front()->Scalars
.size();
3284 SmallPtrSet
<Instruction
*, 4> LiveValues
;
3285 Instruction
*PrevInst
= nullptr;
3287 for (const auto &TEPtr
: VectorizableTree
) {
3288 Instruction
*Inst
= dyn_cast
<Instruction
>(TEPtr
->Scalars
[0]);
3297 // Update LiveValues.
3298 LiveValues
.erase(PrevInst
);
3299 for (auto &J
: PrevInst
->operands()) {
3300 if (isa
<Instruction
>(&*J
) && getTreeEntry(&*J
))
3301 LiveValues
.insert(cast
<Instruction
>(&*J
));
3305 dbgs() << "SLP: #LV: " << LiveValues
.size();
3306 for (auto *X
: LiveValues
)
3307 dbgs() << " " << X
->getName();
3308 dbgs() << ", Looking at ";
3312 // Now find the sequence of instructions between PrevInst and Inst.
3313 unsigned NumCalls
= 0;
3314 BasicBlock::reverse_iterator InstIt
= ++Inst
->getIterator().getReverse(),
3316 PrevInst
->getIterator().getReverse();
3317 while (InstIt
!= PrevInstIt
) {
3318 if (PrevInstIt
== PrevInst
->getParent()->rend()) {
3319 PrevInstIt
= Inst
->getParent()->rbegin();
3323 // Debug informations don't impact spill cost.
3324 if ((isa
<CallInst
>(&*PrevInstIt
) &&
3325 !isa
<DbgInfoIntrinsic
>(&*PrevInstIt
)) &&
3326 &*PrevInstIt
!= PrevInst
)
3333 SmallVector
<Type
*, 4> V
;
3334 for (auto *II
: LiveValues
)
3335 V
.push_back(VectorType::get(II
->getType(), BundleWidth
));
3336 Cost
+= NumCalls
* TTI
->getCostOfKeepingLiveOverCall(V
);
3345 int BoUpSLP::getTreeCost() {
3347 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
3348 << VectorizableTree
.size() << ".\n");
3350 unsigned BundleWidth
= VectorizableTree
[0]->Scalars
.size();
3352 for (unsigned I
= 0, E
= VectorizableTree
.size(); I
< E
; ++I
) {
3353 TreeEntry
&TE
= *VectorizableTree
[I
].get();
3355 // We create duplicate tree entries for gather sequences that have multiple
3356 // uses. However, we should not compute the cost of duplicate sequences.
3357 // For example, if we have a build vector (i.e., insertelement sequence)
3358 // that is used by more than one vector instruction, we only need to
3359 // compute the cost of the insertelement instructions once. The redundant
3360 // instructions will be eliminated by CSE.
3362 // We should consider not creating duplicate tree entries for gather
3363 // sequences, and instead add additional edges to the tree representing
3364 // their uses. Since such an approach results in fewer total entries,
3365 // existing heuristics based on tree size may yield different results.
3367 if (TE
.NeedToGather
&&
3369 std::next(VectorizableTree
.begin(), I
+ 1), VectorizableTree
.end(),
3370 [TE
](const std::unique_ptr
<TreeEntry
> &EntryPtr
) {
3371 return EntryPtr
->NeedToGather
&& EntryPtr
->isSame(TE
.Scalars
);
3375 int C
= getEntryCost(&TE
);
3376 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
3377 << " for bundle that starts with " << *TE
.Scalars
[0]
3382 SmallPtrSet
<Value
*, 16> ExtractCostCalculated
;
3383 int ExtractCost
= 0;
3384 for (ExternalUser
&EU
: ExternalUses
) {
3385 // We only add extract cost once for the same scalar.
3386 if (!ExtractCostCalculated
.insert(EU
.Scalar
).second
)
3389 // Uses by ephemeral values are free (because the ephemeral value will be
3390 // removed prior to code generation, and so the extraction will be
3391 // removed as well).
3392 if (EphValues
.count(EU
.User
))
3395 // If we plan to rewrite the tree in a smaller type, we will need to sign
3396 // extend the extracted value back to the original type. Here, we account
3397 // for the extract and the added cost of the sign extend if needed.
3398 auto *VecTy
= VectorType::get(EU
.Scalar
->getType(), BundleWidth
);
3399 auto *ScalarRoot
= VectorizableTree
[0]->Scalars
[0];
3400 if (MinBWs
.count(ScalarRoot
)) {
3401 auto *MinTy
= IntegerType::get(F
->getContext(), MinBWs
[ScalarRoot
].first
);
3403 MinBWs
[ScalarRoot
].second
? Instruction::SExt
: Instruction::ZExt
;
3404 VecTy
= VectorType::get(MinTy
, BundleWidth
);
3405 ExtractCost
+= TTI
->getExtractWithExtendCost(Extend
, EU
.Scalar
->getType(),
3409 TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
, EU
.Lane
);
3413 int SpillCost
= getSpillCost();
3414 Cost
+= SpillCost
+ ExtractCost
;
3418 raw_string_ostream
OS(Str
);
3419 OS
<< "SLP: Spill Cost = " << SpillCost
<< ".\n"
3420 << "SLP: Extract Cost = " << ExtractCost
<< ".\n"
3421 << "SLP: Total Cost = " << Cost
<< ".\n";
3423 LLVM_DEBUG(dbgs() << Str
);
3426 ViewGraph(this, "SLP" + F
->getName(), false, Str
);
3431 int BoUpSLP::getGatherCost(Type
*Ty
,
3432 const DenseSet
<unsigned> &ShuffledIndices
) const {
3434 for (unsigned i
= 0, e
= cast
<VectorType
>(Ty
)->getNumElements(); i
< e
; ++i
)
3435 if (!ShuffledIndices
.count(i
))
3436 Cost
+= TTI
->getVectorInstrCost(Instruction::InsertElement
, Ty
, i
);
3437 if (!ShuffledIndices
.empty())
3438 Cost
+= TTI
->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc
, Ty
);
3442 int BoUpSLP::getGatherCost(ArrayRef
<Value
*> VL
) const {
3443 // Find the type of the operands in VL.
3444 Type
*ScalarTy
= VL
[0]->getType();
3445 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(VL
[0]))
3446 ScalarTy
= SI
->getValueOperand()->getType();
3447 VectorType
*VecTy
= VectorType::get(ScalarTy
, VL
.size());
3448 // Find the cost of inserting/extracting values from the vector.
3449 // Check if the same elements are inserted several times and count them as
3450 // shuffle candidates.
3451 DenseSet
<unsigned> ShuffledElements
;
3452 DenseSet
<Value
*> UniqueElements
;
3453 // Iterate in reverse order to consider insert elements with the high cost.
3454 for (unsigned I
= VL
.size(); I
> 0; --I
) {
3455 unsigned Idx
= I
- 1;
3456 if (!UniqueElements
.insert(VL
[Idx
]).second
)
3457 ShuffledElements
.insert(Idx
);
3459 return getGatherCost(VecTy
, ShuffledElements
);
3462 // Perform operand reordering on the instructions in VL and return the reordered
3463 // operands in Left and Right.
3464 void BoUpSLP::reorderInputsAccordingToOpcode(
3465 ArrayRef
<Value
*> VL
, SmallVectorImpl
<Value
*> &Left
,
3466 SmallVectorImpl
<Value
*> &Right
, const DataLayout
&DL
,
3467 ScalarEvolution
&SE
) {
3470 VLOperands
Ops(VL
, DL
, SE
);
3471 // Reorder the operands in place.
3473 Left
= Ops
.getVL(0);
3474 Right
= Ops
.getVL(1);
3477 void BoUpSLP::setInsertPointAfterBundle(TreeEntry
*E
) {
3478 // Get the basic block this bundle is in. All instructions in the bundle
3479 // should be in this block.
3480 auto *Front
= E
->getMainOp();
3481 auto *BB
= Front
->getParent();
3482 assert(llvm::all_of(make_range(E
->Scalars
.begin(), E
->Scalars
.end()),
3483 [=](Value
*V
) -> bool {
3484 auto *I
= cast
<Instruction
>(V
);
3485 return !E
->isOpcodeOrAlt(I
) || I
->getParent() == BB
;
3488 // The last instruction in the bundle in program order.
3489 Instruction
*LastInst
= nullptr;
3491 // Find the last instruction. The common case should be that BB has been
3492 // scheduled, and the last instruction is VL.back(). So we start with
3493 // VL.back() and iterate over schedule data until we reach the end of the
3494 // bundle. The end of the bundle is marked by null ScheduleData.
3495 if (BlocksSchedules
.count(BB
)) {
3497 BlocksSchedules
[BB
]->getScheduleData(E
->isOneOf(E
->Scalars
.back()));
3498 if (Bundle
&& Bundle
->isPartOfBundle())
3499 for (; Bundle
; Bundle
= Bundle
->NextInBundle
)
3500 if (Bundle
->OpValue
== Bundle
->Inst
)
3501 LastInst
= Bundle
->Inst
;
3504 // LastInst can still be null at this point if there's either not an entry
3505 // for BB in BlocksSchedules or there's no ScheduleData available for
3506 // VL.back(). This can be the case if buildTree_rec aborts for various
3507 // reasons (e.g., the maximum recursion depth is reached, the maximum region
3508 // size is reached, etc.). ScheduleData is initialized in the scheduling
3511 // If this happens, we can still find the last instruction by brute force. We
3512 // iterate forwards from Front (inclusive) until we either see all
3513 // instructions in the bundle or reach the end of the block. If Front is the
3514 // last instruction in program order, LastInst will be set to Front, and we
3515 // will visit all the remaining instructions in the block.
3517 // One of the reasons we exit early from buildTree_rec is to place an upper
3518 // bound on compile-time. Thus, taking an additional compile-time hit here is
3519 // not ideal. However, this should be exceedingly rare since it requires that
3520 // we both exit early from buildTree_rec and that the bundle be out-of-order
3521 // (causing us to iterate all the way to the end of the block).
3523 SmallPtrSet
<Value
*, 16> Bundle(E
->Scalars
.begin(), E
->Scalars
.end());
3524 for (auto &I
: make_range(BasicBlock::iterator(Front
), BB
->end())) {
3525 if (Bundle
.erase(&I
) && E
->isOpcodeOrAlt(&I
))
3531 assert(LastInst
&& "Failed to find last instruction in bundle");
3533 // Set the insertion point after the last instruction in the bundle. Set the
3534 // debug location to Front.
3535 Builder
.SetInsertPoint(BB
, ++LastInst
->getIterator());
3536 Builder
.SetCurrentDebugLocation(Front
->getDebugLoc());
3539 Value
*BoUpSLP::Gather(ArrayRef
<Value
*> VL
, VectorType
*Ty
) {
3540 Value
*Vec
= UndefValue::get(Ty
);
3541 // Generate the 'InsertElement' instruction.
3542 for (unsigned i
= 0; i
< Ty
->getNumElements(); ++i
) {
3543 Vec
= Builder
.CreateInsertElement(Vec
, VL
[i
], Builder
.getInt32(i
));
3544 if (Instruction
*Insrt
= dyn_cast
<Instruction
>(Vec
)) {
3545 GatherSeq
.insert(Insrt
);
3546 CSEBlocks
.insert(Insrt
->getParent());
3548 // Add to our 'need-to-extract' list.
3549 if (TreeEntry
*E
= getTreeEntry(VL
[i
])) {
3550 // Find which lane we need to extract.
3552 for (unsigned Lane
= 0, LE
= E
->Scalars
.size(); Lane
!= LE
; ++Lane
) {
3553 // Is this the lane of the scalar that we are looking for ?
3554 if (E
->Scalars
[Lane
] == VL
[i
]) {
3559 assert(FoundLane
>= 0 && "Could not find the correct lane");
3560 if (!E
->ReuseShuffleIndices
.empty()) {
3562 std::distance(E
->ReuseShuffleIndices
.begin(),
3563 llvm::find(E
->ReuseShuffleIndices
, FoundLane
));
3565 ExternalUses
.push_back(ExternalUser(VL
[i
], Insrt
, FoundLane
));
3573 Value
*BoUpSLP::vectorizeTree(ArrayRef
<Value
*> VL
) {
3574 InstructionsState S
= getSameOpcode(VL
);
3575 if (S
.getOpcode()) {
3576 if (TreeEntry
*E
= getTreeEntry(S
.OpValue
)) {
3577 if (E
->isSame(VL
)) {
3578 Value
*V
= vectorizeTree(E
);
3579 if (VL
.size() == E
->Scalars
.size() && !E
->ReuseShuffleIndices
.empty()) {
3580 // We need to get the vectorized value but without shuffle.
3581 if (auto *SV
= dyn_cast
<ShuffleVectorInst
>(V
)) {
3582 V
= SV
->getOperand(0);
3584 // Reshuffle to get only unique values.
3585 SmallVector
<unsigned, 4> UniqueIdxs
;
3586 SmallSet
<unsigned, 4> UsedIdxs
;
3587 for(unsigned Idx
: E
->ReuseShuffleIndices
)
3588 if (UsedIdxs
.insert(Idx
).second
)
3589 UniqueIdxs
.emplace_back(Idx
);
3590 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(V
->getType()),
3599 Type
*ScalarTy
= S
.OpValue
->getType();
3600 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(S
.OpValue
))
3601 ScalarTy
= SI
->getValueOperand()->getType();
3603 // Check that every instruction appears once in this bundle.
3604 SmallVector
<unsigned, 4> ReuseShuffleIndicies
;
3605 SmallVector
<Value
*, 4> UniqueValues
;
3606 if (VL
.size() > 2) {
3607 DenseMap
<Value
*, unsigned> UniquePositions
;
3608 for (Value
*V
: VL
) {
3609 auto Res
= UniquePositions
.try_emplace(V
, UniqueValues
.size());
3610 ReuseShuffleIndicies
.emplace_back(Res
.first
->second
);
3611 if (Res
.second
|| isa
<Constant
>(V
))
3612 UniqueValues
.emplace_back(V
);
3614 // Do not shuffle single element or if number of unique values is not power
3616 if (UniqueValues
.size() == VL
.size() || UniqueValues
.size() <= 1 ||
3617 !llvm::isPowerOf2_32(UniqueValues
.size()))
3618 ReuseShuffleIndicies
.clear();
3622 VectorType
*VecTy
= VectorType::get(ScalarTy
, VL
.size());
3624 Value
*V
= Gather(VL
, VecTy
);
3625 if (!ReuseShuffleIndicies
.empty()) {
3626 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3627 ReuseShuffleIndicies
, "shuffle");
3628 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3629 GatherSeq
.insert(I
);
3630 CSEBlocks
.insert(I
->getParent());
3636 static void inversePermutation(ArrayRef
<unsigned> Indices
,
3637 SmallVectorImpl
<unsigned> &Mask
) {
3639 const unsigned E
= Indices
.size();
3641 for (unsigned I
= 0; I
< E
; ++I
)
3642 Mask
[Indices
[I
]] = I
;
3645 Value
*BoUpSLP::vectorizeTree(TreeEntry
*E
) {
3646 IRBuilder
<>::InsertPointGuard
Guard(Builder
);
3648 if (E
->VectorizedValue
) {
3649 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E
->Scalars
[0] << ".\n");
3650 return E
->VectorizedValue
;
3653 Instruction
*VL0
= E
->getMainOp();
3654 Type
*ScalarTy
= VL0
->getType();
3655 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(VL0
))
3656 ScalarTy
= SI
->getValueOperand()->getType();
3657 VectorType
*VecTy
= VectorType::get(ScalarTy
, E
->Scalars
.size());
3659 bool NeedToShuffleReuses
= !E
->ReuseShuffleIndices
.empty();
3661 if (E
->NeedToGather
) {
3662 setInsertPointAfterBundle(E
);
3663 auto *V
= Gather(E
->Scalars
, VecTy
);
3664 if (NeedToShuffleReuses
) {
3665 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3666 E
->ReuseShuffleIndices
, "shuffle");
3667 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3668 GatherSeq
.insert(I
);
3669 CSEBlocks
.insert(I
->getParent());
3672 E
->VectorizedValue
= V
;
3676 unsigned ShuffleOrOp
=
3677 E
->isAltShuffle() ? (unsigned)Instruction::ShuffleVector
: E
->getOpcode();
3678 switch (ShuffleOrOp
) {
3679 case Instruction::PHI
: {
3680 auto *PH
= cast
<PHINode
>(VL0
);
3681 Builder
.SetInsertPoint(PH
->getParent()->getFirstNonPHI());
3682 Builder
.SetCurrentDebugLocation(PH
->getDebugLoc());
3683 PHINode
*NewPhi
= Builder
.CreatePHI(VecTy
, PH
->getNumIncomingValues());
3685 if (NeedToShuffleReuses
) {
3686 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3687 E
->ReuseShuffleIndices
, "shuffle");
3689 E
->VectorizedValue
= V
;
3691 // PHINodes may have multiple entries from the same block. We want to
3692 // visit every block once.
3693 SmallPtrSet
<BasicBlock
*, 4> VisitedBBs
;
3695 for (unsigned i
= 0, e
= PH
->getNumIncomingValues(); i
< e
; ++i
) {
3697 BasicBlock
*IBB
= PH
->getIncomingBlock(i
);
3699 if (!VisitedBBs
.insert(IBB
).second
) {
3700 NewPhi
->addIncoming(NewPhi
->getIncomingValueForBlock(IBB
), IBB
);
3704 Builder
.SetInsertPoint(IBB
->getTerminator());
3705 Builder
.SetCurrentDebugLocation(PH
->getDebugLoc());
3706 Value
*Vec
= vectorizeTree(E
->getOperand(i
));
3707 NewPhi
->addIncoming(Vec
, IBB
);
3710 assert(NewPhi
->getNumIncomingValues() == PH
->getNumIncomingValues() &&
3711 "Invalid number of incoming values");
3715 case Instruction::ExtractElement
: {
3716 if (!E
->NeedToGather
) {
3717 Value
*V
= E
->getSingleOperand(0);
3718 if (!E
->ReorderIndices
.empty()) {
3720 inversePermutation(E
->ReorderIndices
, Mask
);
3721 Builder
.SetInsertPoint(VL0
);
3722 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
), Mask
,
3725 if (NeedToShuffleReuses
) {
3726 // TODO: Merge this shuffle with the ReorderShuffleMask.
3727 if (E
->ReorderIndices
.empty())
3728 Builder
.SetInsertPoint(VL0
);
3729 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3730 E
->ReuseShuffleIndices
, "shuffle");
3732 E
->VectorizedValue
= V
;
3735 setInsertPointAfterBundle(E
);
3736 auto *V
= Gather(E
->Scalars
, VecTy
);
3737 if (NeedToShuffleReuses
) {
3738 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3739 E
->ReuseShuffleIndices
, "shuffle");
3740 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3741 GatherSeq
.insert(I
);
3742 CSEBlocks
.insert(I
->getParent());
3745 E
->VectorizedValue
= V
;
3748 case Instruction::ExtractValue
: {
3749 if (!E
->NeedToGather
) {
3750 LoadInst
*LI
= cast
<LoadInst
>(E
->getSingleOperand(0));
3751 Builder
.SetInsertPoint(LI
);
3752 PointerType
*PtrTy
= PointerType::get(VecTy
, LI
->getPointerAddressSpace());
3753 Value
*Ptr
= Builder
.CreateBitCast(LI
->getOperand(0), PtrTy
);
3754 LoadInst
*V
= Builder
.CreateAlignedLoad(VecTy
, Ptr
, LI
->getAlignment());
3755 Value
*NewV
= propagateMetadata(V
, E
->Scalars
);
3756 if (!E
->ReorderIndices
.empty()) {
3758 inversePermutation(E
->ReorderIndices
, Mask
);
3759 NewV
= Builder
.CreateShuffleVector(NewV
, UndefValue::get(VecTy
), Mask
,
3762 if (NeedToShuffleReuses
) {
3763 // TODO: Merge this shuffle with the ReorderShuffleMask.
3764 NewV
= Builder
.CreateShuffleVector(
3765 NewV
, UndefValue::get(VecTy
), E
->ReuseShuffleIndices
, "shuffle");
3767 E
->VectorizedValue
= NewV
;
3770 setInsertPointAfterBundle(E
);
3771 auto *V
= Gather(E
->Scalars
, VecTy
);
3772 if (NeedToShuffleReuses
) {
3773 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3774 E
->ReuseShuffleIndices
, "shuffle");
3775 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3776 GatherSeq
.insert(I
);
3777 CSEBlocks
.insert(I
->getParent());
3780 E
->VectorizedValue
= V
;
3783 case Instruction::ZExt
:
3784 case Instruction::SExt
:
3785 case Instruction::FPToUI
:
3786 case Instruction::FPToSI
:
3787 case Instruction::FPExt
:
3788 case Instruction::PtrToInt
:
3789 case Instruction::IntToPtr
:
3790 case Instruction::SIToFP
:
3791 case Instruction::UIToFP
:
3792 case Instruction::Trunc
:
3793 case Instruction::FPTrunc
:
3794 case Instruction::BitCast
: {
3795 setInsertPointAfterBundle(E
);
3797 Value
*InVec
= vectorizeTree(E
->getOperand(0));
3799 if (E
->VectorizedValue
) {
3800 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3801 return E
->VectorizedValue
;
3804 auto *CI
= cast
<CastInst
>(VL0
);
3805 Value
*V
= Builder
.CreateCast(CI
->getOpcode(), InVec
, VecTy
);
3806 if (NeedToShuffleReuses
) {
3807 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3808 E
->ReuseShuffleIndices
, "shuffle");
3810 E
->VectorizedValue
= V
;
3811 ++NumVectorInstructions
;
3814 case Instruction::FCmp
:
3815 case Instruction::ICmp
: {
3816 setInsertPointAfterBundle(E
);
3818 Value
*L
= vectorizeTree(E
->getOperand(0));
3819 Value
*R
= vectorizeTree(E
->getOperand(1));
3821 if (E
->VectorizedValue
) {
3822 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3823 return E
->VectorizedValue
;
3826 CmpInst::Predicate P0
= cast
<CmpInst
>(VL0
)->getPredicate();
3828 if (E
->getOpcode() == Instruction::FCmp
)
3829 V
= Builder
.CreateFCmp(P0
, L
, R
);
3831 V
= Builder
.CreateICmp(P0
, L
, R
);
3833 propagateIRFlags(V
, E
->Scalars
, VL0
);
3834 if (NeedToShuffleReuses
) {
3835 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3836 E
->ReuseShuffleIndices
, "shuffle");
3838 E
->VectorizedValue
= V
;
3839 ++NumVectorInstructions
;
3842 case Instruction::Select
: {
3843 setInsertPointAfterBundle(E
);
3845 Value
*Cond
= vectorizeTree(E
->getOperand(0));
3846 Value
*True
= vectorizeTree(E
->getOperand(1));
3847 Value
*False
= vectorizeTree(E
->getOperand(2));
3849 if (E
->VectorizedValue
) {
3850 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3851 return E
->VectorizedValue
;
3854 Value
*V
= Builder
.CreateSelect(Cond
, True
, False
);
3855 if (NeedToShuffleReuses
) {
3856 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3857 E
->ReuseShuffleIndices
, "shuffle");
3859 E
->VectorizedValue
= V
;
3860 ++NumVectorInstructions
;
3863 case Instruction::FNeg
: {
3864 setInsertPointAfterBundle(E
);
3866 Value
*Op
= vectorizeTree(E
->getOperand(0));
3868 if (E
->VectorizedValue
) {
3869 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3870 return E
->VectorizedValue
;
3873 Value
*V
= Builder
.CreateUnOp(
3874 static_cast<Instruction::UnaryOps
>(E
->getOpcode()), Op
);
3875 propagateIRFlags(V
, E
->Scalars
, VL0
);
3876 if (auto *I
= dyn_cast
<Instruction
>(V
))
3877 V
= propagateMetadata(I
, E
->Scalars
);
3879 if (NeedToShuffleReuses
) {
3880 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3881 E
->ReuseShuffleIndices
, "shuffle");
3883 E
->VectorizedValue
= V
;
3884 ++NumVectorInstructions
;
3888 case Instruction::Add
:
3889 case Instruction::FAdd
:
3890 case Instruction::Sub
:
3891 case Instruction::FSub
:
3892 case Instruction::Mul
:
3893 case Instruction::FMul
:
3894 case Instruction::UDiv
:
3895 case Instruction::SDiv
:
3896 case Instruction::FDiv
:
3897 case Instruction::URem
:
3898 case Instruction::SRem
:
3899 case Instruction::FRem
:
3900 case Instruction::Shl
:
3901 case Instruction::LShr
:
3902 case Instruction::AShr
:
3903 case Instruction::And
:
3904 case Instruction::Or
:
3905 case Instruction::Xor
: {
3906 setInsertPointAfterBundle(E
);
3908 Value
*LHS
= vectorizeTree(E
->getOperand(0));
3909 Value
*RHS
= vectorizeTree(E
->getOperand(1));
3911 if (E
->VectorizedValue
) {
3912 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3913 return E
->VectorizedValue
;
3916 Value
*V
= Builder
.CreateBinOp(
3917 static_cast<Instruction::BinaryOps
>(E
->getOpcode()), LHS
,
3919 propagateIRFlags(V
, E
->Scalars
, VL0
);
3920 if (auto *I
= dyn_cast
<Instruction
>(V
))
3921 V
= propagateMetadata(I
, E
->Scalars
);
3923 if (NeedToShuffleReuses
) {
3924 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3925 E
->ReuseShuffleIndices
, "shuffle");
3927 E
->VectorizedValue
= V
;
3928 ++NumVectorInstructions
;
3932 case Instruction::Load
: {
3933 // Loads are inserted at the head of the tree because we don't want to
3934 // sink them all the way down past store instructions.
3935 bool IsReorder
= E
->updateStateIfReorder();
3937 VL0
= E
->getMainOp();
3938 setInsertPointAfterBundle(E
);
3940 LoadInst
*LI
= cast
<LoadInst
>(VL0
);
3941 Type
*ScalarLoadTy
= LI
->getType();
3942 unsigned AS
= LI
->getPointerAddressSpace();
3944 Value
*VecPtr
= Builder
.CreateBitCast(LI
->getPointerOperand(),
3945 VecTy
->getPointerTo(AS
));
3947 // The pointer operand uses an in-tree scalar so we add the new BitCast to
3948 // ExternalUses list to make sure that an extract will be generated in the
3950 Value
*PO
= LI
->getPointerOperand();
3951 if (getTreeEntry(PO
))
3952 ExternalUses
.push_back(ExternalUser(PO
, cast
<User
>(VecPtr
), 0));
3954 unsigned Alignment
= LI
->getAlignment();
3955 LI
= Builder
.CreateLoad(VecTy
, VecPtr
);
3957 Alignment
= DL
->getABITypeAlignment(ScalarLoadTy
);
3959 LI
->setAlignment(Alignment
);
3960 Value
*V
= propagateMetadata(LI
, E
->Scalars
);
3963 inversePermutation(E
->ReorderIndices
, Mask
);
3964 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(V
->getType()),
3965 Mask
, "reorder_shuffle");
3967 if (NeedToShuffleReuses
) {
3968 // TODO: Merge this shuffle with the ReorderShuffleMask.
3969 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3970 E
->ReuseShuffleIndices
, "shuffle");
3972 E
->VectorizedValue
= V
;
3973 ++NumVectorInstructions
;
3976 case Instruction::Store
: {
3977 StoreInst
*SI
= cast
<StoreInst
>(VL0
);
3978 unsigned Alignment
= SI
->getAlignment();
3979 unsigned AS
= SI
->getPointerAddressSpace();
3981 setInsertPointAfterBundle(E
);
3983 Value
*VecValue
= vectorizeTree(E
->getOperand(0));
3984 Value
*ScalarPtr
= SI
->getPointerOperand();
3985 Value
*VecPtr
= Builder
.CreateBitCast(ScalarPtr
, VecTy
->getPointerTo(AS
));
3986 StoreInst
*ST
= Builder
.CreateStore(VecValue
, VecPtr
);
3988 // The pointer operand uses an in-tree scalar, so add the new BitCast to
3989 // ExternalUses to make sure that an extract will be generated in the
3991 if (getTreeEntry(ScalarPtr
))
3992 ExternalUses
.push_back(ExternalUser(ScalarPtr
, cast
<User
>(VecPtr
), 0));
3995 Alignment
= DL
->getABITypeAlignment(SI
->getValueOperand()->getType());
3997 ST
->setAlignment(Alignment
);
3998 Value
*V
= propagateMetadata(ST
, E
->Scalars
);
3999 if (NeedToShuffleReuses
) {
4000 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4001 E
->ReuseShuffleIndices
, "shuffle");
4003 E
->VectorizedValue
= V
;
4004 ++NumVectorInstructions
;
4007 case Instruction::GetElementPtr
: {
4008 setInsertPointAfterBundle(E
);
4010 Value
*Op0
= vectorizeTree(E
->getOperand(0));
4012 std::vector
<Value
*> OpVecs
;
4013 for (int j
= 1, e
= cast
<GetElementPtrInst
>(VL0
)->getNumOperands(); j
< e
;
4015 Value
*OpVec
= vectorizeTree(E
->getOperand(j
));
4016 OpVecs
.push_back(OpVec
);
4019 Value
*V
= Builder
.CreateGEP(
4020 cast
<GetElementPtrInst
>(VL0
)->getSourceElementType(), Op0
, OpVecs
);
4021 if (Instruction
*I
= dyn_cast
<Instruction
>(V
))
4022 V
= propagateMetadata(I
, E
->Scalars
);
4024 if (NeedToShuffleReuses
) {
4025 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4026 E
->ReuseShuffleIndices
, "shuffle");
4028 E
->VectorizedValue
= V
;
4029 ++NumVectorInstructions
;
4033 case Instruction::Call
: {
4034 CallInst
*CI
= cast
<CallInst
>(VL0
);
4035 setInsertPointAfterBundle(E
);
4037 Intrinsic::ID IID
= Intrinsic::not_intrinsic
;
4038 if (Function
*FI
= CI
->getCalledFunction())
4039 IID
= FI
->getIntrinsicID();
4041 Value
*ScalarArg
= nullptr;
4042 std::vector
<Value
*> OpVecs
;
4043 for (int j
= 0, e
= CI
->getNumArgOperands(); j
< e
; ++j
) {
4045 // Some intrinsics have scalar arguments. This argument should not be
4047 if (hasVectorInstrinsicScalarOpd(IID
, j
)) {
4048 CallInst
*CEI
= cast
<CallInst
>(VL0
);
4049 ScalarArg
= CEI
->getArgOperand(j
);
4050 OpVecs
.push_back(CEI
->getArgOperand(j
));
4054 Value
*OpVec
= vectorizeTree(E
->getOperand(j
));
4055 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j
<< "]: " << *OpVec
<< "\n");
4056 OpVecs
.push_back(OpVec
);
4059 Module
*M
= F
->getParent();
4060 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
4061 Type
*Tys
[] = { VectorType::get(CI
->getType(), E
->Scalars
.size()) };
4062 Function
*CF
= Intrinsic::getDeclaration(M
, ID
, Tys
);
4063 SmallVector
<OperandBundleDef
, 1> OpBundles
;
4064 CI
->getOperandBundlesAsDefs(OpBundles
);
4065 Value
*V
= Builder
.CreateCall(CF
, OpVecs
, OpBundles
);
4067 // The scalar argument uses an in-tree scalar so we add the new vectorized
4068 // call to ExternalUses list to make sure that an extract will be
4069 // generated in the future.
4070 if (ScalarArg
&& getTreeEntry(ScalarArg
))
4071 ExternalUses
.push_back(ExternalUser(ScalarArg
, cast
<User
>(V
), 0));
4073 propagateIRFlags(V
, E
->Scalars
, VL0
);
4074 if (NeedToShuffleReuses
) {
4075 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4076 E
->ReuseShuffleIndices
, "shuffle");
4078 E
->VectorizedValue
= V
;
4079 ++NumVectorInstructions
;
4082 case Instruction::ShuffleVector
: {
4083 assert(E
->isAltShuffle() &&
4084 ((Instruction::isBinaryOp(E
->getOpcode()) &&
4085 Instruction::isBinaryOp(E
->getAltOpcode())) ||
4086 (Instruction::isCast(E
->getOpcode()) &&
4087 Instruction::isCast(E
->getAltOpcode()))) &&
4088 "Invalid Shuffle Vector Operand");
4090 Value
*LHS
= nullptr, *RHS
= nullptr;
4091 if (Instruction::isBinaryOp(E
->getOpcode())) {
4092 setInsertPointAfterBundle(E
);
4093 LHS
= vectorizeTree(E
->getOperand(0));
4094 RHS
= vectorizeTree(E
->getOperand(1));
4096 setInsertPointAfterBundle(E
);
4097 LHS
= vectorizeTree(E
->getOperand(0));
4100 if (E
->VectorizedValue
) {
4101 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
4102 return E
->VectorizedValue
;
4106 if (Instruction::isBinaryOp(E
->getOpcode())) {
4107 V0
= Builder
.CreateBinOp(
4108 static_cast<Instruction::BinaryOps
>(E
->getOpcode()), LHS
, RHS
);
4109 V1
= Builder
.CreateBinOp(
4110 static_cast<Instruction::BinaryOps
>(E
->getAltOpcode()), LHS
, RHS
);
4112 V0
= Builder
.CreateCast(
4113 static_cast<Instruction::CastOps
>(E
->getOpcode()), LHS
, VecTy
);
4114 V1
= Builder
.CreateCast(
4115 static_cast<Instruction::CastOps
>(E
->getAltOpcode()), LHS
, VecTy
);
4118 // Create shuffle to take alternate operations from the vector.
4119 // Also, gather up main and alt scalar ops to propagate IR flags to
4120 // each vector operation.
4121 ValueList OpScalars
, AltScalars
;
4122 unsigned e
= E
->Scalars
.size();
4123 SmallVector
<Constant
*, 8> Mask(e
);
4124 for (unsigned i
= 0; i
< e
; ++i
) {
4125 auto *OpInst
= cast
<Instruction
>(E
->Scalars
[i
]);
4126 assert(E
->isOpcodeOrAlt(OpInst
) && "Unexpected main/alternate opcode");
4127 if (OpInst
->getOpcode() == E
->getAltOpcode()) {
4128 Mask
[i
] = Builder
.getInt32(e
+ i
);
4129 AltScalars
.push_back(E
->Scalars
[i
]);
4131 Mask
[i
] = Builder
.getInt32(i
);
4132 OpScalars
.push_back(E
->Scalars
[i
]);
4136 Value
*ShuffleMask
= ConstantVector::get(Mask
);
4137 propagateIRFlags(V0
, OpScalars
);
4138 propagateIRFlags(V1
, AltScalars
);
4140 Value
*V
= Builder
.CreateShuffleVector(V0
, V1
, ShuffleMask
);
4141 if (Instruction
*I
= dyn_cast
<Instruction
>(V
))
4142 V
= propagateMetadata(I
, E
->Scalars
);
4143 if (NeedToShuffleReuses
) {
4144 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4145 E
->ReuseShuffleIndices
, "shuffle");
4147 E
->VectorizedValue
= V
;
4148 ++NumVectorInstructions
;
4153 llvm_unreachable("unknown inst");
4158 Value
*BoUpSLP::vectorizeTree() {
4159 ExtraValueToDebugLocsMap ExternallyUsedValues
;
4160 return vectorizeTree(ExternallyUsedValues
);
4164 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap
&ExternallyUsedValues
) {
4165 // All blocks must be scheduled before any instructions are inserted.
4166 for (auto &BSIter
: BlocksSchedules
) {
4167 scheduleBlock(BSIter
.second
.get());
4170 Builder
.SetInsertPoint(&F
->getEntryBlock().front());
4171 auto *VectorRoot
= vectorizeTree(VectorizableTree
[0].get());
4173 // If the vectorized tree can be rewritten in a smaller type, we truncate the
4174 // vectorized root. InstCombine will then rewrite the entire expression. We
4175 // sign extend the extracted values below.
4176 auto *ScalarRoot
= VectorizableTree
[0]->Scalars
[0];
4177 if (MinBWs
.count(ScalarRoot
)) {
4178 if (auto *I
= dyn_cast
<Instruction
>(VectorRoot
))
4179 Builder
.SetInsertPoint(&*++BasicBlock::iterator(I
));
4180 auto BundleWidth
= VectorizableTree
[0]->Scalars
.size();
4181 auto *MinTy
= IntegerType::get(F
->getContext(), MinBWs
[ScalarRoot
].first
);
4182 auto *VecTy
= VectorType::get(MinTy
, BundleWidth
);
4183 auto *Trunc
= Builder
.CreateTrunc(VectorRoot
, VecTy
);
4184 VectorizableTree
[0]->VectorizedValue
= Trunc
;
4187 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses
.size()
4190 // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4191 // specified by ScalarType.
4192 auto extend
= [&](Value
*ScalarRoot
, Value
*Ex
, Type
*ScalarType
) {
4193 if (!MinBWs
.count(ScalarRoot
))
4195 if (MinBWs
[ScalarRoot
].second
)
4196 return Builder
.CreateSExt(Ex
, ScalarType
);
4197 return Builder
.CreateZExt(Ex
, ScalarType
);
4200 // Extract all of the elements with the external uses.
4201 for (const auto &ExternalUse
: ExternalUses
) {
4202 Value
*Scalar
= ExternalUse
.Scalar
;
4203 llvm::User
*User
= ExternalUse
.User
;
4205 // Skip users that we already RAUW. This happens when one instruction
4206 // has multiple uses of the same value.
4207 if (User
&& !is_contained(Scalar
->users(), User
))
4209 TreeEntry
*E
= getTreeEntry(Scalar
);
4210 assert(E
&& "Invalid scalar");
4211 assert(!E
->NeedToGather
&& "Extracting from a gather list");
4213 Value
*Vec
= E
->VectorizedValue
;
4214 assert(Vec
&& "Can't find vectorizable value");
4216 Value
*Lane
= Builder
.getInt32(ExternalUse
.Lane
);
4217 // If User == nullptr, the Scalar is used as extra arg. Generate
4218 // ExtractElement instruction and update the record for this scalar in
4219 // ExternallyUsedValues.
4221 assert(ExternallyUsedValues
.count(Scalar
) &&
4222 "Scalar with nullptr as an external user must be registered in "
4223 "ExternallyUsedValues map");
4224 if (auto *VecI
= dyn_cast
<Instruction
>(Vec
)) {
4225 Builder
.SetInsertPoint(VecI
->getParent(),
4226 std::next(VecI
->getIterator()));
4228 Builder
.SetInsertPoint(&F
->getEntryBlock().front());
4230 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4231 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4232 CSEBlocks
.insert(cast
<Instruction
>(Scalar
)->getParent());
4233 auto &Locs
= ExternallyUsedValues
[Scalar
];
4234 ExternallyUsedValues
.insert({Ex
, Locs
});
4235 ExternallyUsedValues
.erase(Scalar
);
4236 // Required to update internally referenced instructions.
4237 Scalar
->replaceAllUsesWith(Ex
);
4241 // Generate extracts for out-of-tree users.
4242 // Find the insertion point for the extractelement lane.
4243 if (auto *VecI
= dyn_cast
<Instruction
>(Vec
)) {
4244 if (PHINode
*PH
= dyn_cast
<PHINode
>(User
)) {
4245 for (int i
= 0, e
= PH
->getNumIncomingValues(); i
!= e
; ++i
) {
4246 if (PH
->getIncomingValue(i
) == Scalar
) {
4247 Instruction
*IncomingTerminator
=
4248 PH
->getIncomingBlock(i
)->getTerminator();
4249 if (isa
<CatchSwitchInst
>(IncomingTerminator
)) {
4250 Builder
.SetInsertPoint(VecI
->getParent(),
4251 std::next(VecI
->getIterator()));
4253 Builder
.SetInsertPoint(PH
->getIncomingBlock(i
)->getTerminator());
4255 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4256 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4257 CSEBlocks
.insert(PH
->getIncomingBlock(i
));
4258 PH
->setOperand(i
, Ex
);
4262 Builder
.SetInsertPoint(cast
<Instruction
>(User
));
4263 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4264 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4265 CSEBlocks
.insert(cast
<Instruction
>(User
)->getParent());
4266 User
->replaceUsesOfWith(Scalar
, Ex
);
4269 Builder
.SetInsertPoint(&F
->getEntryBlock().front());
4270 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4271 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4272 CSEBlocks
.insert(&F
->getEntryBlock());
4273 User
->replaceUsesOfWith(Scalar
, Ex
);
4276 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User
<< ".\n");
4279 // For each vectorized value:
4280 for (auto &TEPtr
: VectorizableTree
) {
4281 TreeEntry
*Entry
= TEPtr
.get();
4283 // No need to handle users of gathered values.
4284 if (Entry
->NeedToGather
)
4287 assert(Entry
->VectorizedValue
&& "Can't find vectorizable value");
4290 for (int Lane
= 0, LE
= Entry
->Scalars
.size(); Lane
!= LE
; ++Lane
) {
4291 Value
*Scalar
= Entry
->Scalars
[Lane
];
4293 Type
*Ty
= Scalar
->getType();
4294 if (!Ty
->isVoidTy()) {
4296 for (User
*U
: Scalar
->users()) {
4297 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U
<< ".\n");
4299 // It is legal to replace users in the ignorelist by undef.
4300 assert((getTreeEntry(U
) || is_contained(UserIgnoreList
, U
)) &&
4301 "Replacing out-of-tree value with undef");
4304 Value
*Undef
= UndefValue::get(Ty
);
4305 Scalar
->replaceAllUsesWith(Undef
);
4307 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar
<< ".\n");
4308 eraseInstruction(cast
<Instruction
>(Scalar
));
4312 Builder
.ClearInsertionPoint();
4314 return VectorizableTree
[0]->VectorizedValue
;
4317 void BoUpSLP::optimizeGatherSequence() {
4318 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq
.size()
4319 << " gather sequences instructions.\n");
4320 // LICM InsertElementInst sequences.
4321 for (Instruction
*I
: GatherSeq
) {
4322 if (!isa
<InsertElementInst
>(I
) && !isa
<ShuffleVectorInst
>(I
))
4325 // Check if this block is inside a loop.
4326 Loop
*L
= LI
->getLoopFor(I
->getParent());
4330 // Check if it has a preheader.
4331 BasicBlock
*PreHeader
= L
->getLoopPreheader();
4335 // If the vector or the element that we insert into it are
4336 // instructions that are defined in this basic block then we can't
4337 // hoist this instruction.
4338 auto *Op0
= dyn_cast
<Instruction
>(I
->getOperand(0));
4339 auto *Op1
= dyn_cast
<Instruction
>(I
->getOperand(1));
4340 if (Op0
&& L
->contains(Op0
))
4342 if (Op1
&& L
->contains(Op1
))
4345 // We can hoist this instruction. Move it to the pre-header.
4346 I
->moveBefore(PreHeader
->getTerminator());
4349 // Make a list of all reachable blocks in our CSE queue.
4350 SmallVector
<const DomTreeNode
*, 8> CSEWorkList
;
4351 CSEWorkList
.reserve(CSEBlocks
.size());
4352 for (BasicBlock
*BB
: CSEBlocks
)
4353 if (DomTreeNode
*N
= DT
->getNode(BB
)) {
4354 assert(DT
->isReachableFromEntry(N
));
4355 CSEWorkList
.push_back(N
);
4358 // Sort blocks by domination. This ensures we visit a block after all blocks
4359 // dominating it are visited.
4360 llvm::stable_sort(CSEWorkList
,
4361 [this](const DomTreeNode
*A
, const DomTreeNode
*B
) {
4362 return DT
->properlyDominates(A
, B
);
4365 // Perform O(N^2) search over the gather sequences and merge identical
4366 // instructions. TODO: We can further optimize this scan if we split the
4367 // instructions into different buckets based on the insert lane.
4368 SmallVector
<Instruction
*, 16> Visited
;
4369 for (auto I
= CSEWorkList
.begin(), E
= CSEWorkList
.end(); I
!= E
; ++I
) {
4370 assert((I
== CSEWorkList
.begin() || !DT
->dominates(*I
, *std::prev(I
))) &&
4371 "Worklist not sorted properly!");
4372 BasicBlock
*BB
= (*I
)->getBlock();
4373 // For all instructions in blocks containing gather sequences:
4374 for (BasicBlock::iterator it
= BB
->begin(), e
= BB
->end(); it
!= e
;) {
4375 Instruction
*In
= &*it
++;
4376 if (!isa
<InsertElementInst
>(In
) && !isa
<ExtractElementInst
>(In
))
4379 // Check if we can replace this instruction with any of the
4380 // visited instructions.
4381 for (Instruction
*v
: Visited
) {
4382 if (In
->isIdenticalTo(v
) &&
4383 DT
->dominates(v
->getParent(), In
->getParent())) {
4384 In
->replaceAllUsesWith(v
);
4385 eraseInstruction(In
);
4391 assert(!is_contained(Visited
, In
));
4392 Visited
.push_back(In
);
4400 // Groups the instructions to a bundle (which is then a single scheduling entity)
4401 // and schedules instructions until the bundle gets ready.
4402 Optional
<BoUpSLP::ScheduleData
*>
4403 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef
<Value
*> VL
, BoUpSLP
*SLP
,
4404 const InstructionsState
&S
) {
4405 if (isa
<PHINode
>(S
.OpValue
))
4408 // Initialize the instruction bundle.
4409 Instruction
*OldScheduleEnd
= ScheduleEnd
;
4410 ScheduleData
*PrevInBundle
= nullptr;
4411 ScheduleData
*Bundle
= nullptr;
4412 bool ReSchedule
= false;
4413 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S
.OpValue
<< "\n");
4415 // Make sure that the scheduling region contains all
4416 // instructions of the bundle.
4417 for (Value
*V
: VL
) {
4418 if (!extendSchedulingRegion(V
, S
))
4422 for (Value
*V
: VL
) {
4423 ScheduleData
*BundleMember
= getScheduleData(V
);
4424 assert(BundleMember
&&
4425 "no ScheduleData for bundle member (maybe not in same basic block)");
4426 if (BundleMember
->IsScheduled
) {
4427 // A bundle member was scheduled as single instruction before and now
4428 // needs to be scheduled as part of the bundle. We just get rid of the
4429 // existing schedule.
4430 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
4431 << " was already scheduled\n");
4434 assert(BundleMember
->isSchedulingEntity() &&
4435 "bundle member already part of other bundle");
4437 PrevInBundle
->NextInBundle
= BundleMember
;
4439 Bundle
= BundleMember
;
4441 BundleMember
->UnscheduledDepsInBundle
= 0;
4442 Bundle
->UnscheduledDepsInBundle
+= BundleMember
->UnscheduledDeps
;
4444 // Group the instructions to a bundle.
4445 BundleMember
->FirstInBundle
= Bundle
;
4446 PrevInBundle
= BundleMember
;
4448 if (ScheduleEnd
!= OldScheduleEnd
) {
4449 // The scheduling region got new instructions at the lower end (or it is a
4450 // new region for the first bundle). This makes it necessary to
4451 // recalculate all dependencies.
4452 // It is seldom that this needs to be done a second time after adding the
4453 // initial bundle to the region.
4454 for (auto *I
= ScheduleStart
; I
!= ScheduleEnd
; I
= I
->getNextNode()) {
4455 doForAllOpcodes(I
, [](ScheduleData
*SD
) {
4456 SD
->clearDependencies();
4463 initialFillReadyList(ReadyInsts
);
4465 assert(Bundle
&& "Failed to find schedule bundle");
4467 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
<< " in block "
4468 << BB
->getName() << "\n");
4470 calculateDependencies(Bundle
, true, SLP
);
4472 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
4473 // means that there are no cyclic dependencies and we can schedule it.
4474 // Note that's important that we don't "schedule" the bundle yet (see
4475 // cancelScheduling).
4476 while (!Bundle
->isReady() && !ReadyInsts
.empty()) {
4478 ScheduleData
*pickedSD
= ReadyInsts
.back();
4479 ReadyInsts
.pop_back();
4481 if (pickedSD
->isSchedulingEntity() && pickedSD
->isReady()) {
4482 schedule(pickedSD
, ReadyInsts
);
4485 if (!Bundle
->isReady()) {
4486 cancelScheduling(VL
, S
.OpValue
);
4492 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef
<Value
*> VL
,
4494 if (isa
<PHINode
>(OpValue
))
4497 ScheduleData
*Bundle
= getScheduleData(OpValue
);
4498 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle
<< "\n");
4499 assert(!Bundle
->IsScheduled
&&
4500 "Can't cancel bundle which is already scheduled");
4501 assert(Bundle
->isSchedulingEntity() && Bundle
->isPartOfBundle() &&
4502 "tried to unbundle something which is not a bundle");
4504 // Un-bundle: make single instructions out of the bundle.
4505 ScheduleData
*BundleMember
= Bundle
;
4506 while (BundleMember
) {
4507 assert(BundleMember
->FirstInBundle
== Bundle
&& "corrupt bundle links");
4508 BundleMember
->FirstInBundle
= BundleMember
;
4509 ScheduleData
*Next
= BundleMember
->NextInBundle
;
4510 BundleMember
->NextInBundle
= nullptr;
4511 BundleMember
->UnscheduledDepsInBundle
= BundleMember
->UnscheduledDeps
;
4512 if (BundleMember
->UnscheduledDepsInBundle
== 0) {
4513 ReadyInsts
.insert(BundleMember
);
4515 BundleMember
= Next
;
4519 BoUpSLP::ScheduleData
*BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
4520 // Allocate a new ScheduleData for the instruction.
4521 if (ChunkPos
>= ChunkSize
) {
4522 ScheduleDataChunks
.push_back(std::make_unique
<ScheduleData
[]>(ChunkSize
));
4525 return &(ScheduleDataChunks
.back()[ChunkPos
++]);
4528 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value
*V
,
4529 const InstructionsState
&S
) {
4530 if (getScheduleData(V
, isOneOf(S
, V
)))
4532 Instruction
*I
= dyn_cast
<Instruction
>(V
);
4533 assert(I
&& "bundle member must be an instruction");
4534 assert(!isa
<PHINode
>(I
) && "phi nodes don't need to be scheduled");
4535 auto &&CheckSheduleForI
= [this, &S
](Instruction
*I
) -> bool {
4536 ScheduleData
*ISD
= getScheduleData(I
);
4539 assert(isInSchedulingRegion(ISD
) &&
4540 "ScheduleData not in scheduling region");
4541 ScheduleData
*SD
= allocateScheduleDataChunks();
4543 SD
->init(SchedulingRegionID
, S
.OpValue
);
4544 ExtraScheduleDataMap
[I
][S
.OpValue
] = SD
;
4547 if (CheckSheduleForI(I
))
4549 if (!ScheduleStart
) {
4550 // It's the first instruction in the new region.
4551 initScheduleData(I
, I
->getNextNode(), nullptr, nullptr);
4553 ScheduleEnd
= I
->getNextNode();
4554 if (isOneOf(S
, I
) != I
)
4555 CheckSheduleForI(I
);
4556 assert(ScheduleEnd
&& "tried to vectorize a terminator?");
4557 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I
<< "\n");
4560 // Search up and down at the same time, because we don't know if the new
4561 // instruction is above or below the existing scheduling region.
4562 BasicBlock::reverse_iterator UpIter
=
4563 ++ScheduleStart
->getIterator().getReverse();
4564 BasicBlock::reverse_iterator UpperEnd
= BB
->rend();
4565 BasicBlock::iterator DownIter
= ScheduleEnd
->getIterator();
4566 BasicBlock::iterator LowerEnd
= BB
->end();
4568 if (++ScheduleRegionSize
> ScheduleRegionSizeLimit
) {
4569 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
4573 if (UpIter
!= UpperEnd
) {
4574 if (&*UpIter
== I
) {
4575 initScheduleData(I
, ScheduleStart
, nullptr, FirstLoadStoreInRegion
);
4577 if (isOneOf(S
, I
) != I
)
4578 CheckSheduleForI(I
);
4579 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I
4585 if (DownIter
!= LowerEnd
) {
4586 if (&*DownIter
== I
) {
4587 initScheduleData(ScheduleEnd
, I
->getNextNode(), LastLoadStoreInRegion
,
4589 ScheduleEnd
= I
->getNextNode();
4590 if (isOneOf(S
, I
) != I
)
4591 CheckSheduleForI(I
);
4592 assert(ScheduleEnd
&& "tried to vectorize a terminator?");
4593 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I
4599 assert((UpIter
!= UpperEnd
|| DownIter
!= LowerEnd
) &&
4600 "instruction not found in block");
4605 void BoUpSLP::BlockScheduling::initScheduleData(Instruction
*FromI
,
4607 ScheduleData
*PrevLoadStore
,
4608 ScheduleData
*NextLoadStore
) {
4609 ScheduleData
*CurrentLoadStore
= PrevLoadStore
;
4610 for (Instruction
*I
= FromI
; I
!= ToI
; I
= I
->getNextNode()) {
4611 ScheduleData
*SD
= ScheduleDataMap
[I
];
4613 SD
= allocateScheduleDataChunks();
4614 ScheduleDataMap
[I
] = SD
;
4617 assert(!isInSchedulingRegion(SD
) &&
4618 "new ScheduleData already in scheduling region");
4619 SD
->init(SchedulingRegionID
, I
);
4621 if (I
->mayReadOrWriteMemory() &&
4622 (!isa
<IntrinsicInst
>(I
) ||
4623 cast
<IntrinsicInst
>(I
)->getIntrinsicID() != Intrinsic::sideeffect
)) {
4624 // Update the linked list of memory accessing instructions.
4625 if (CurrentLoadStore
) {
4626 CurrentLoadStore
->NextLoadStore
= SD
;
4628 FirstLoadStoreInRegion
= SD
;
4630 CurrentLoadStore
= SD
;
4633 if (NextLoadStore
) {
4634 if (CurrentLoadStore
)
4635 CurrentLoadStore
->NextLoadStore
= NextLoadStore
;
4637 LastLoadStoreInRegion
= CurrentLoadStore
;
4641 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData
*SD
,
4642 bool InsertInReadyList
,
4644 assert(SD
->isSchedulingEntity());
4646 SmallVector
<ScheduleData
*, 10> WorkList
;
4647 WorkList
.push_back(SD
);
4649 while (!WorkList
.empty()) {
4650 ScheduleData
*SD
= WorkList
.back();
4651 WorkList
.pop_back();
4653 ScheduleData
*BundleMember
= SD
;
4654 while (BundleMember
) {
4655 assert(isInSchedulingRegion(BundleMember
));
4656 if (!BundleMember
->hasValidDependencies()) {
4658 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember
4660 BundleMember
->Dependencies
= 0;
4661 BundleMember
->resetUnscheduledDeps();
4663 // Handle def-use chain dependencies.
4664 if (BundleMember
->OpValue
!= BundleMember
->Inst
) {
4665 ScheduleData
*UseSD
= getScheduleData(BundleMember
->Inst
);
4666 if (UseSD
&& isInSchedulingRegion(UseSD
->FirstInBundle
)) {
4667 BundleMember
->Dependencies
++;
4668 ScheduleData
*DestBundle
= UseSD
->FirstInBundle
;
4669 if (!DestBundle
->IsScheduled
)
4670 BundleMember
->incrementUnscheduledDeps(1);
4671 if (!DestBundle
->hasValidDependencies())
4672 WorkList
.push_back(DestBundle
);
4675 for (User
*U
: BundleMember
->Inst
->users()) {
4676 if (isa
<Instruction
>(U
)) {
4677 ScheduleData
*UseSD
= getScheduleData(U
);
4678 if (UseSD
&& isInSchedulingRegion(UseSD
->FirstInBundle
)) {
4679 BundleMember
->Dependencies
++;
4680 ScheduleData
*DestBundle
= UseSD
->FirstInBundle
;
4681 if (!DestBundle
->IsScheduled
)
4682 BundleMember
->incrementUnscheduledDeps(1);
4683 if (!DestBundle
->hasValidDependencies())
4684 WorkList
.push_back(DestBundle
);
4687 // I'm not sure if this can ever happen. But we need to be safe.
4688 // This lets the instruction/bundle never be scheduled and
4689 // eventually disable vectorization.
4690 BundleMember
->Dependencies
++;
4691 BundleMember
->incrementUnscheduledDeps(1);
4696 // Handle the memory dependencies.
4697 ScheduleData
*DepDest
= BundleMember
->NextLoadStore
;
4699 Instruction
*SrcInst
= BundleMember
->Inst
;
4700 MemoryLocation SrcLoc
= getLocation(SrcInst
, SLP
->AA
);
4701 bool SrcMayWrite
= BundleMember
->Inst
->mayWriteToMemory();
4702 unsigned numAliased
= 0;
4703 unsigned DistToSrc
= 1;
4706 assert(isInSchedulingRegion(DepDest
));
4708 // We have two limits to reduce the complexity:
4709 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
4710 // SLP->isAliased (which is the expensive part in this loop).
4711 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
4712 // the whole loop (even if the loop is fast, it's quadratic).
4713 // It's important for the loop break condition (see below) to
4714 // check this limit even between two read-only instructions.
4715 if (DistToSrc
>= MaxMemDepDistance
||
4716 ((SrcMayWrite
|| DepDest
->Inst
->mayWriteToMemory()) &&
4717 (numAliased
>= AliasedCheckLimit
||
4718 SLP
->isAliased(SrcLoc
, SrcInst
, DepDest
->Inst
)))) {
4720 // We increment the counter only if the locations are aliased
4721 // (instead of counting all alias checks). This gives a better
4722 // balance between reduced runtime and accurate dependencies.
4725 DepDest
->MemoryDependencies
.push_back(BundleMember
);
4726 BundleMember
->Dependencies
++;
4727 ScheduleData
*DestBundle
= DepDest
->FirstInBundle
;
4728 if (!DestBundle
->IsScheduled
) {
4729 BundleMember
->incrementUnscheduledDeps(1);
4731 if (!DestBundle
->hasValidDependencies()) {
4732 WorkList
.push_back(DestBundle
);
4735 DepDest
= DepDest
->NextLoadStore
;
4737 // Example, explaining the loop break condition: Let's assume our
4738 // starting instruction is i0 and MaxMemDepDistance = 3.
4741 // i0,i1,i2,i3,i4,i5,i6,i7,i8
4744 // MaxMemDepDistance let us stop alias-checking at i3 and we add
4745 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
4746 // Previously we already added dependencies from i3 to i6,i7,i8
4747 // (because of MaxMemDepDistance). As we added a dependency from
4748 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
4749 // and we can abort this loop at i6.
4750 if (DistToSrc
>= 2 * MaxMemDepDistance
)
4756 BundleMember
= BundleMember
->NextInBundle
;
4758 if (InsertInReadyList
&& SD
->isReady()) {
4759 ReadyInsts
.push_back(SD
);
4760 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD
->Inst
4766 void BoUpSLP::BlockScheduling::resetSchedule() {
4767 assert(ScheduleStart
&&
4768 "tried to reset schedule on block which has not been scheduled");
4769 for (Instruction
*I
= ScheduleStart
; I
!= ScheduleEnd
; I
= I
->getNextNode()) {
4770 doForAllOpcodes(I
, [&](ScheduleData
*SD
) {
4771 assert(isInSchedulingRegion(SD
) &&
4772 "ScheduleData not in scheduling region");
4773 SD
->IsScheduled
= false;
4774 SD
->resetUnscheduledDeps();
4780 void BoUpSLP::scheduleBlock(BlockScheduling
*BS
) {
4781 if (!BS
->ScheduleStart
)
4784 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS
->BB
->getName() << "\n");
4786 BS
->resetSchedule();
4788 // For the real scheduling we use a more sophisticated ready-list: it is
4789 // sorted by the original instruction location. This lets the final schedule
4790 // be as close as possible to the original instruction order.
4791 struct ScheduleDataCompare
{
4792 bool operator()(ScheduleData
*SD1
, ScheduleData
*SD2
) const {
4793 return SD2
->SchedulingPriority
< SD1
->SchedulingPriority
;
4796 std::set
<ScheduleData
*, ScheduleDataCompare
> ReadyInsts
;
4798 // Ensure that all dependency data is updated and fill the ready-list with
4799 // initial instructions.
4801 int NumToSchedule
= 0;
4802 for (auto *I
= BS
->ScheduleStart
; I
!= BS
->ScheduleEnd
;
4803 I
= I
->getNextNode()) {
4804 BS
->doForAllOpcodes(I
, [this, &Idx
, &NumToSchedule
, BS
](ScheduleData
*SD
) {
4805 assert(SD
->isPartOfBundle() ==
4806 (getTreeEntry(SD
->Inst
) != nullptr) &&
4807 "scheduler and vectorizer bundle mismatch");
4808 SD
->FirstInBundle
->SchedulingPriority
= Idx
++;
4809 if (SD
->isSchedulingEntity()) {
4810 BS
->calculateDependencies(SD
, false, this);
4815 BS
->initialFillReadyList(ReadyInsts
);
4817 Instruction
*LastScheduledInst
= BS
->ScheduleEnd
;
4819 // Do the "real" scheduling.
4820 while (!ReadyInsts
.empty()) {
4821 ScheduleData
*picked
= *ReadyInsts
.begin();
4822 ReadyInsts
.erase(ReadyInsts
.begin());
4824 // Move the scheduled instruction(s) to their dedicated places, if not
4826 ScheduleData
*BundleMember
= picked
;
4827 while (BundleMember
) {
4828 Instruction
*pickedInst
= BundleMember
->Inst
;
4829 if (LastScheduledInst
->getNextNode() != pickedInst
) {
4830 BS
->BB
->getInstList().remove(pickedInst
);
4831 BS
->BB
->getInstList().insert(LastScheduledInst
->getIterator(),
4834 LastScheduledInst
= pickedInst
;
4835 BundleMember
= BundleMember
->NextInBundle
;
4838 BS
->schedule(picked
, ReadyInsts
);
4841 assert(NumToSchedule
== 0 && "could not schedule all instructions");
4843 // Avoid duplicate scheduling of the block.
4844 BS
->ScheduleStart
= nullptr;
4847 unsigned BoUpSLP::getVectorElementSize(Value
*V
) const {
4848 // If V is a store, just return the width of the stored value without
4849 // traversing the expression tree. This is the common case.
4850 if (auto *Store
= dyn_cast
<StoreInst
>(V
))
4851 return DL
->getTypeSizeInBits(Store
->getValueOperand()->getType());
4853 // If V is not a store, we can traverse the expression tree to find loads
4854 // that feed it. The type of the loaded value may indicate a more suitable
4855 // width than V's type. We want to base the vector element size on the width
4856 // of memory operations where possible.
4857 SmallVector
<Instruction
*, 16> Worklist
;
4858 SmallPtrSet
<Instruction
*, 16> Visited
;
4859 if (auto *I
= dyn_cast
<Instruction
>(V
))
4860 Worklist
.push_back(I
);
4862 // Traverse the expression tree in bottom-up order looking for loads. If we
4863 // encounter an instruction we don't yet handle, we give up.
4865 auto FoundUnknownInst
= false;
4866 while (!Worklist
.empty() && !FoundUnknownInst
) {
4867 auto *I
= Worklist
.pop_back_val();
4870 // We should only be looking at scalar instructions here. If the current
4871 // instruction has a vector type, give up.
4872 auto *Ty
= I
->getType();
4873 if (isa
<VectorType
>(Ty
))
4874 FoundUnknownInst
= true;
4876 // If the current instruction is a load, update MaxWidth to reflect the
4877 // width of the loaded value.
4878 else if (isa
<LoadInst
>(I
))
4879 MaxWidth
= std::max
<unsigned>(MaxWidth
, DL
->getTypeSizeInBits(Ty
));
4881 // Otherwise, we need to visit the operands of the instruction. We only
4882 // handle the interesting cases from buildTree here. If an operand is an
4883 // instruction we haven't yet visited, we add it to the worklist.
4884 else if (isa
<PHINode
>(I
) || isa
<CastInst
>(I
) || isa
<GetElementPtrInst
>(I
) ||
4885 isa
<CmpInst
>(I
) || isa
<SelectInst
>(I
) || isa
<BinaryOperator
>(I
)) {
4886 for (Use
&U
: I
->operands())
4887 if (auto *J
= dyn_cast
<Instruction
>(U
.get()))
4888 if (!Visited
.count(J
))
4889 Worklist
.push_back(J
);
4892 // If we don't yet handle the instruction, give up.
4894 FoundUnknownInst
= true;
4897 // If we didn't encounter a memory access in the expression tree, or if we
4898 // gave up for some reason, just return the width of V.
4899 if (!MaxWidth
|| FoundUnknownInst
)
4900 return DL
->getTypeSizeInBits(V
->getType());
4902 // Otherwise, return the maximum width we found.
4906 // Determine if a value V in a vectorizable expression Expr can be demoted to a
4907 // smaller type with a truncation. We collect the values that will be demoted
4908 // in ToDemote and additional roots that require investigating in Roots.
4909 static bool collectValuesToDemote(Value
*V
, SmallPtrSetImpl
<Value
*> &Expr
,
4910 SmallVectorImpl
<Value
*> &ToDemote
,
4911 SmallVectorImpl
<Value
*> &Roots
) {
4912 // We can always demote constants.
4913 if (isa
<Constant
>(V
)) {
4914 ToDemote
.push_back(V
);
4918 // If the value is not an instruction in the expression with only one use, it
4919 // cannot be demoted.
4920 auto *I
= dyn_cast
<Instruction
>(V
);
4921 if (!I
|| !I
->hasOneUse() || !Expr
.count(I
))
4924 switch (I
->getOpcode()) {
4926 // We can always demote truncations and extensions. Since truncations can
4927 // seed additional demotion, we save the truncated value.
4928 case Instruction::Trunc
:
4929 Roots
.push_back(I
->getOperand(0));
4931 case Instruction::ZExt
:
4932 case Instruction::SExt
:
4935 // We can demote certain binary operations if we can demote both of their
4937 case Instruction::Add
:
4938 case Instruction::Sub
:
4939 case Instruction::Mul
:
4940 case Instruction::And
:
4941 case Instruction::Or
:
4942 case Instruction::Xor
:
4943 if (!collectValuesToDemote(I
->getOperand(0), Expr
, ToDemote
, Roots
) ||
4944 !collectValuesToDemote(I
->getOperand(1), Expr
, ToDemote
, Roots
))
4948 // We can demote selects if we can demote their true and false values.
4949 case Instruction::Select
: {
4950 SelectInst
*SI
= cast
<SelectInst
>(I
);
4951 if (!collectValuesToDemote(SI
->getTrueValue(), Expr
, ToDemote
, Roots
) ||
4952 !collectValuesToDemote(SI
->getFalseValue(), Expr
, ToDemote
, Roots
))
4957 // We can demote phis if we can demote all their incoming operands. Note that
4958 // we don't need to worry about cycles since we ensure single use above.
4959 case Instruction::PHI
: {
4960 PHINode
*PN
= cast
<PHINode
>(I
);
4961 for (Value
*IncValue
: PN
->incoming_values())
4962 if (!collectValuesToDemote(IncValue
, Expr
, ToDemote
, Roots
))
4967 // Otherwise, conservatively give up.
4972 // Record the value that we can demote.
4973 ToDemote
.push_back(V
);
4977 void BoUpSLP::computeMinimumValueSizes() {
4978 // If there are no external uses, the expression tree must be rooted by a
4979 // store. We can't demote in-memory values, so there is nothing to do here.
4980 if (ExternalUses
.empty())
4983 // We only attempt to truncate integer expressions.
4984 auto &TreeRoot
= VectorizableTree
[0]->Scalars
;
4985 auto *TreeRootIT
= dyn_cast
<IntegerType
>(TreeRoot
[0]->getType());
4989 // If the expression is not rooted by a store, these roots should have
4990 // external uses. We will rely on InstCombine to rewrite the expression in
4991 // the narrower type. However, InstCombine only rewrites single-use values.
4992 // This means that if a tree entry other than a root is used externally, it
4993 // must have multiple uses and InstCombine will not rewrite it. The code
4994 // below ensures that only the roots are used externally.
4995 SmallPtrSet
<Value
*, 32> Expr(TreeRoot
.begin(), TreeRoot
.end());
4996 for (auto &EU
: ExternalUses
)
4997 if (!Expr
.erase(EU
.Scalar
))
5002 // Collect the scalar values of the vectorizable expression. We will use this
5003 // context to determine which values can be demoted. If we see a truncation,
5004 // we mark it as seeding another demotion.
5005 for (auto &EntryPtr
: VectorizableTree
)
5006 Expr
.insert(EntryPtr
->Scalars
.begin(), EntryPtr
->Scalars
.end());
5008 // Ensure the roots of the vectorizable tree don't form a cycle. They must
5009 // have a single external user that is not in the vectorizable tree.
5010 for (auto *Root
: TreeRoot
)
5011 if (!Root
->hasOneUse() || Expr
.count(*Root
->user_begin()))
5014 // Conservatively determine if we can actually truncate the roots of the
5015 // expression. Collect the values that can be demoted in ToDemote and
5016 // additional roots that require investigating in Roots.
5017 SmallVector
<Value
*, 32> ToDemote
;
5018 SmallVector
<Value
*, 4> Roots
;
5019 for (auto *Root
: TreeRoot
)
5020 if (!collectValuesToDemote(Root
, Expr
, ToDemote
, Roots
))
5023 // The maximum bit width required to represent all the values that can be
5024 // demoted without loss of precision. It would be safe to truncate the roots
5025 // of the expression to this width.
5026 auto MaxBitWidth
= 8u;
5028 // We first check if all the bits of the roots are demanded. If they're not,
5029 // we can truncate the roots to this narrower type.
5030 for (auto *Root
: TreeRoot
) {
5031 auto Mask
= DB
->getDemandedBits(cast
<Instruction
>(Root
));
5032 MaxBitWidth
= std::max
<unsigned>(
5033 Mask
.getBitWidth() - Mask
.countLeadingZeros(), MaxBitWidth
);
5036 // True if the roots can be zero-extended back to their original type, rather
5037 // than sign-extended. We know that if the leading bits are not demanded, we
5038 // can safely zero-extend. So we initialize IsKnownPositive to True.
5039 bool IsKnownPositive
= true;
5041 // If all the bits of the roots are demanded, we can try a little harder to
5042 // compute a narrower type. This can happen, for example, if the roots are
5043 // getelementptr indices. InstCombine promotes these indices to the pointer
5044 // width. Thus, all their bits are technically demanded even though the
5045 // address computation might be vectorized in a smaller type.
5047 // We start by looking at each entry that can be demoted. We compute the
5048 // maximum bit width required to store the scalar by using ValueTracking to
5049 // compute the number of high-order bits we can truncate.
5050 if (MaxBitWidth
== DL
->getTypeSizeInBits(TreeRoot
[0]->getType()) &&
5051 llvm::all_of(TreeRoot
, [](Value
*R
) {
5052 assert(R
->hasOneUse() && "Root should have only one use!");
5053 return isa
<GetElementPtrInst
>(R
->user_back());
5057 // Determine if the sign bit of all the roots is known to be zero. If not,
5058 // IsKnownPositive is set to False.
5059 IsKnownPositive
= llvm::all_of(TreeRoot
, [&](Value
*R
) {
5060 KnownBits Known
= computeKnownBits(R
, *DL
);
5061 return Known
.isNonNegative();
5064 // Determine the maximum number of bits required to store the scalar
5066 for (auto *Scalar
: ToDemote
) {
5067 auto NumSignBits
= ComputeNumSignBits(Scalar
, *DL
, 0, AC
, nullptr, DT
);
5068 auto NumTypeBits
= DL
->getTypeSizeInBits(Scalar
->getType());
5069 MaxBitWidth
= std::max
<unsigned>(NumTypeBits
- NumSignBits
, MaxBitWidth
);
5072 // If we can't prove that the sign bit is zero, we must add one to the
5073 // maximum bit width to account for the unknown sign bit. This preserves
5074 // the existing sign bit so we can safely sign-extend the root back to the
5075 // original type. Otherwise, if we know the sign bit is zero, we will
5076 // zero-extend the root instead.
5078 // FIXME: This is somewhat suboptimal, as there will be cases where adding
5079 // one to the maximum bit width will yield a larger-than-necessary
5080 // type. In general, we need to add an extra bit only if we can't
5081 // prove that the upper bit of the original type is equal to the
5082 // upper bit of the proposed smaller type. If these two bits are the
5083 // same (either zero or one) we know that sign-extending from the
5084 // smaller type will result in the same value. Here, since we can't
5085 // yet prove this, we are just making the proposed smaller type
5086 // larger to ensure correctness.
5087 if (!IsKnownPositive
)
5091 // Round MaxBitWidth up to the next power-of-two.
5092 if (!isPowerOf2_64(MaxBitWidth
))
5093 MaxBitWidth
= NextPowerOf2(MaxBitWidth
);
5095 // If the maximum bit width we compute is less than the with of the roots'
5096 // type, we can proceed with the narrowing. Otherwise, do nothing.
5097 if (MaxBitWidth
>= TreeRootIT
->getBitWidth())
5100 // If we can truncate the root, we must collect additional values that might
5101 // be demoted as a result. That is, those seeded by truncations we will
5103 while (!Roots
.empty())
5104 collectValuesToDemote(Roots
.pop_back_val(), Expr
, ToDemote
, Roots
);
5106 // Finally, map the values we can demote to the maximum bit with we computed.
5107 for (auto *Scalar
: ToDemote
)
5108 MinBWs
[Scalar
] = std::make_pair(MaxBitWidth
, !IsKnownPositive
);
5113 /// The SLPVectorizer Pass.
5114 struct SLPVectorizer
: public FunctionPass
{
5115 SLPVectorizerPass Impl
;
5117 /// Pass identification, replacement for typeid
5120 explicit SLPVectorizer() : FunctionPass(ID
) {
5121 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5124 bool doInitialization(Module
&M
) override
{
5128 bool runOnFunction(Function
&F
) override
{
5129 if (skipFunction(F
))
5132 auto *SE
= &getAnalysis
<ScalarEvolutionWrapperPass
>().getSE();
5133 auto *TTI
= &getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
5134 auto *TLIP
= getAnalysisIfAvailable
<TargetLibraryInfoWrapperPass
>();
5135 auto *TLI
= TLIP
? &TLIP
->getTLI(F
) : nullptr;
5136 auto *AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
5137 auto *LI
= &getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo();
5138 auto *DT
= &getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
5139 auto *AC
= &getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(F
);
5140 auto *DB
= &getAnalysis
<DemandedBitsWrapperPass
>().getDemandedBits();
5141 auto *ORE
= &getAnalysis
<OptimizationRemarkEmitterWrapperPass
>().getORE();
5143 return Impl
.runImpl(F
, SE
, TTI
, TLI
, AA
, LI
, DT
, AC
, DB
, ORE
);
5146 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
5147 FunctionPass::getAnalysisUsage(AU
);
5148 AU
.addRequired
<AssumptionCacheTracker
>();
5149 AU
.addRequired
<ScalarEvolutionWrapperPass
>();
5150 AU
.addRequired
<AAResultsWrapperPass
>();
5151 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
5152 AU
.addRequired
<LoopInfoWrapperPass
>();
5153 AU
.addRequired
<DominatorTreeWrapperPass
>();
5154 AU
.addRequired
<DemandedBitsWrapperPass
>();
5155 AU
.addRequired
<OptimizationRemarkEmitterWrapperPass
>();
5156 AU
.addPreserved
<LoopInfoWrapperPass
>();
5157 AU
.addPreserved
<DominatorTreeWrapperPass
>();
5158 AU
.addPreserved
<AAResultsWrapperPass
>();
5159 AU
.addPreserved
<GlobalsAAWrapperPass
>();
5160 AU
.setPreservesCFG();
5164 } // end anonymous namespace
5166 PreservedAnalyses
SLPVectorizerPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
5167 auto *SE
= &AM
.getResult
<ScalarEvolutionAnalysis
>(F
);
5168 auto *TTI
= &AM
.getResult
<TargetIRAnalysis
>(F
);
5169 auto *TLI
= AM
.getCachedResult
<TargetLibraryAnalysis
>(F
);
5170 auto *AA
= &AM
.getResult
<AAManager
>(F
);
5171 auto *LI
= &AM
.getResult
<LoopAnalysis
>(F
);
5172 auto *DT
= &AM
.getResult
<DominatorTreeAnalysis
>(F
);
5173 auto *AC
= &AM
.getResult
<AssumptionAnalysis
>(F
);
5174 auto *DB
= &AM
.getResult
<DemandedBitsAnalysis
>(F
);
5175 auto *ORE
= &AM
.getResult
<OptimizationRemarkEmitterAnalysis
>(F
);
5177 bool Changed
= runImpl(F
, SE
, TTI
, TLI
, AA
, LI
, DT
, AC
, DB
, ORE
);
5179 return PreservedAnalyses::all();
5181 PreservedAnalyses PA
;
5182 PA
.preserveSet
<CFGAnalyses
>();
5183 PA
.preserve
<AAManager
>();
5184 PA
.preserve
<GlobalsAA
>();
5188 bool SLPVectorizerPass::runImpl(Function
&F
, ScalarEvolution
*SE_
,
5189 TargetTransformInfo
*TTI_
,
5190 TargetLibraryInfo
*TLI_
, AliasAnalysis
*AA_
,
5191 LoopInfo
*LI_
, DominatorTree
*DT_
,
5192 AssumptionCache
*AC_
, DemandedBits
*DB_
,
5193 OptimizationRemarkEmitter
*ORE_
) {
5202 DL
= &F
.getParent()->getDataLayout();
5206 bool Changed
= false;
5208 // If the target claims to have no vector registers don't attempt
5210 if (!TTI
->getNumberOfRegisters(true))
5213 // Don't vectorize when the attribute NoImplicitFloat is used.
5214 if (F
.hasFnAttribute(Attribute::NoImplicitFloat
))
5217 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F
.getName() << ".\n");
5219 // Use the bottom up slp vectorizer to construct chains that start with
5220 // store instructions.
5221 BoUpSLP
R(&F
, SE
, TTI
, TLI
, AA
, LI
, DT
, AC
, DB
, DL
, ORE_
);
5223 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5224 // delete instructions.
5226 // Scan the blocks in the function in post order.
5227 for (auto BB
: post_order(&F
.getEntryBlock())) {
5228 collectSeedInstructions(BB
);
5230 // Vectorize trees that end at stores.
5231 if (!Stores
.empty()) {
5232 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores
.size()
5233 << " underlying objects.\n");
5234 Changed
|= vectorizeStoreChains(R
);
5237 // Vectorize trees that end at reductions.
5238 Changed
|= vectorizeChainsInBlock(BB
, R
);
5240 // Vectorize the index computations of getelementptr instructions. This
5241 // is primarily intended to catch gather-like idioms ending at
5242 // non-consecutive loads.
5243 if (!GEPs
.empty()) {
5244 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs
.size()
5245 << " underlying objects.\n");
5246 Changed
|= vectorizeGEPIndices(BB
, R
);
5251 R
.optimizeGatherSequence();
5252 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F
.getName() << "\"\n");
5253 LLVM_DEBUG(verifyFunction(F
));
5258 /// Check that the Values in the slice in VL array are still existent in
5259 /// the WeakTrackingVH array.
5260 /// Vectorization of part of the VL array may cause later values in the VL array
5261 /// to become invalid. We track when this has happened in the WeakTrackingVH
5263 static bool hasValueBeenRAUWed(ArrayRef
<Value
*> VL
,
5264 ArrayRef
<WeakTrackingVH
> VH
, unsigned SliceBegin
,
5265 unsigned SliceSize
) {
5266 VL
= VL
.slice(SliceBegin
, SliceSize
);
5267 VH
= VH
.slice(SliceBegin
, SliceSize
);
5268 return !std::equal(VL
.begin(), VL
.end(), VH
.begin());
5271 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef
<Value
*> Chain
, BoUpSLP
&R
,
5272 unsigned VecRegSize
) {
5273 const unsigned ChainLen
= Chain
.size();
5274 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
5276 const unsigned Sz
= R
.getVectorElementSize(Chain
[0]);
5277 const unsigned VF
= VecRegSize
/ Sz
;
5279 if (!isPowerOf2_32(Sz
) || VF
< 2)
5282 // Keep track of values that were deleted by vectorizing in the loop below.
5283 const SmallVector
<WeakTrackingVH
, 8> TrackValues(Chain
.begin(), Chain
.end());
5285 bool Changed
= false;
5286 // Look for profitable vectorizable trees at all offsets, starting at zero.
5287 for (unsigned i
= 0, e
= ChainLen
; i
+ VF
<= e
; ++i
) {
5289 // Check that a previous iteration of this loop did not delete the Value.
5290 if (hasValueBeenRAUWed(Chain
, TrackValues
, i
, VF
))
5293 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF
<< " stores at offset " << i
5295 ArrayRef
<Value
*> Operands
= Chain
.slice(i
, VF
);
5297 R
.buildTree(Operands
);
5298 if (R
.isTreeTinyAndNotFullyVectorizable())
5301 R
.computeMinimumValueSizes();
5303 int Cost
= R
.getTreeCost();
5305 LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost
<< " for VF=" << VF
5307 if (Cost
< -SLPCostThreshold
) {
5308 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost
<< "\n");
5310 using namespace ore
;
5312 R
.getORE()->emit(OptimizationRemark(SV_NAME
, "StoresVectorized",
5313 cast
<StoreInst
>(Chain
[i
]))
5314 << "Stores SLP vectorized with cost " << NV("Cost", Cost
)
5315 << " and with tree size "
5316 << NV("TreeSize", R
.getTreeSize()));
5320 // Move to the next bundle.
5329 bool SLPVectorizerPass::vectorizeStores(ArrayRef
<StoreInst
*> Stores
,
5331 SetVector
<StoreInst
*> Heads
;
5332 SmallDenseSet
<StoreInst
*> Tails
;
5333 SmallDenseMap
<StoreInst
*, StoreInst
*> ConsecutiveChain
;
5335 // We may run into multiple chains that merge into a single chain. We mark the
5336 // stores that we vectorized so that we don't visit the same store twice.
5337 BoUpSLP::ValueSet VectorizedStores
;
5338 bool Changed
= false;
5340 auto &&FindConsecutiveAccess
=
5341 [this, &Stores
, &Heads
, &Tails
, &ConsecutiveChain
] (int K
, int Idx
) {
5342 if (!isConsecutiveAccess(Stores
[K
], Stores
[Idx
], *DL
, *SE
))
5345 Tails
.insert(Stores
[Idx
]);
5346 Heads
.insert(Stores
[K
]);
5347 ConsecutiveChain
[Stores
[K
]] = Stores
[Idx
];
5351 // Do a quadratic search on all of the given stores in reverse order and find
5352 // all of the pairs of stores that follow each other.
5353 int E
= Stores
.size();
5354 for (int Idx
= E
- 1; Idx
>= 0; --Idx
) {
5355 // If a store has multiple consecutive store candidates, search according
5356 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
5357 // This is because usually pairing with immediate succeeding or preceding
5358 // candidate create the best chance to find slp vectorization opportunity.
5359 for (int Offset
= 1, F
= std::max(E
- Idx
, Idx
+ 1); Offset
< F
; ++Offset
)
5360 if ((Idx
>= Offset
&& FindConsecutiveAccess(Idx
- Offset
, Idx
)) ||
5361 (Idx
+ Offset
< E
&& FindConsecutiveAccess(Idx
+ Offset
, Idx
)))
5365 // For stores that start but don't end a link in the chain:
5366 for (auto *SI
: llvm::reverse(Heads
)) {
5367 if (Tails
.count(SI
))
5370 // We found a store instr that starts a chain. Now follow the chain and try
5372 BoUpSLP::ValueList Operands
;
5374 // Collect the chain into a list.
5375 while ((Tails
.count(I
) || Heads
.count(I
)) && !VectorizedStores
.count(I
)) {
5376 Operands
.push_back(I
);
5377 // Move to the next value in the chain.
5378 I
= ConsecutiveChain
[I
];
5381 // FIXME: Is division-by-2 the correct step? Should we assert that the
5382 // register size is a power-of-2?
5383 for (unsigned Size
= R
.getMaxVecRegSize(); Size
>= R
.getMinVecRegSize();
5385 if (vectorizeStoreChain(Operands
, R
, Size
)) {
5386 // Mark the vectorized stores so that we don't vectorize them again.
5387 VectorizedStores
.insert(Operands
.begin(), Operands
.end());
5397 void SLPVectorizerPass::collectSeedInstructions(BasicBlock
*BB
) {
5398 // Initialize the collections. We will make a single pass over the block.
5402 // Visit the store and getelementptr instructions in BB and organize them in
5403 // Stores and GEPs according to the underlying objects of their pointer
5405 for (Instruction
&I
: *BB
) {
5406 // Ignore store instructions that are volatile or have a pointer operand
5407 // that doesn't point to a scalar type.
5408 if (auto *SI
= dyn_cast
<StoreInst
>(&I
)) {
5409 if (!SI
->isSimple())
5411 if (!isValidElementType(SI
->getValueOperand()->getType()))
5413 Stores
[GetUnderlyingObject(SI
->getPointerOperand(), *DL
)].push_back(SI
);
5416 // Ignore getelementptr instructions that have more than one index, a
5417 // constant index, or a pointer operand that doesn't point to a scalar
5419 else if (auto *GEP
= dyn_cast
<GetElementPtrInst
>(&I
)) {
5420 auto Idx
= GEP
->idx_begin()->get();
5421 if (GEP
->getNumIndices() > 1 || isa
<Constant
>(Idx
))
5423 if (!isValidElementType(Idx
->getType()))
5425 if (GEP
->getType()->isVectorTy())
5427 GEPs
[GEP
->getPointerOperand()].push_back(GEP
);
5432 bool SLPVectorizerPass::tryToVectorizePair(Value
*A
, Value
*B
, BoUpSLP
&R
) {
5435 Value
*VL
[] = { A
, B
};
5436 return tryToVectorizeList(VL
, R
, /*UserCost=*/0, true);
5439 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef
<Value
*> VL
, BoUpSLP
&R
,
5440 int UserCost
, bool AllowReorder
) {
5444 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
5445 << VL
.size() << ".\n");
5447 // Check that all of the parts are scalar instructions of the same type,
5448 // we permit an alternate opcode via InstructionsState.
5449 InstructionsState S
= getSameOpcode(VL
);
5453 Instruction
*I0
= cast
<Instruction
>(S
.OpValue
);
5454 unsigned Sz
= R
.getVectorElementSize(I0
);
5455 unsigned MinVF
= std::max(2U, R
.getMinVecRegSize() / Sz
);
5456 unsigned MaxVF
= std::max
<unsigned>(PowerOf2Floor(VL
.size()), MinVF
);
5458 R
.getORE()->emit([&]() {
5459 return OptimizationRemarkMissed(SV_NAME
, "SmallVF", I0
)
5460 << "Cannot SLP vectorize list: vectorization factor "
5461 << "less than 2 is not supported";
5466 for (Value
*V
: VL
) {
5467 Type
*Ty
= V
->getType();
5468 if (!isValidElementType(Ty
)) {
5469 // NOTE: the following will give user internal llvm type name, which may
5471 R
.getORE()->emit([&]() {
5472 std::string type_str
;
5473 llvm::raw_string_ostream
rso(type_str
);
5475 return OptimizationRemarkMissed(SV_NAME
, "UnsupportedType", I0
)
5476 << "Cannot SLP vectorize list: type "
5477 << rso
.str() + " is unsupported by vectorizer";
5483 bool Changed
= false;
5484 bool CandidateFound
= false;
5485 int MinCost
= SLPCostThreshold
;
5487 // Keep track of values that were deleted by vectorizing in the loop below.
5488 SmallVector
<WeakTrackingVH
, 8> TrackValues(VL
.begin(), VL
.end());
5490 unsigned NextInst
= 0, MaxInst
= VL
.size();
5491 for (unsigned VF
= MaxVF
; NextInst
+ 1 < MaxInst
&& VF
>= MinVF
; VF
/= 2) {
5492 // No actual vectorization should happen, if number of parts is the same as
5493 // provided vectorization factor (i.e. the scalar type is used for vector
5494 // code during codegen).
5495 auto *VecTy
= VectorType::get(VL
[0]->getType(), VF
);
5496 if (TTI
->getNumberOfParts(VecTy
) == VF
)
5498 for (unsigned I
= NextInst
; I
< MaxInst
; ++I
) {
5499 unsigned OpsWidth
= 0;
5501 if (I
+ VF
> MaxInst
)
5502 OpsWidth
= MaxInst
- I
;
5506 if (!isPowerOf2_32(OpsWidth
) || OpsWidth
< 2)
5509 // Check that a previous iteration of this loop did not delete the Value.
5510 if (hasValueBeenRAUWed(VL
, TrackValues
, I
, OpsWidth
))
5513 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth
<< " operations "
5515 ArrayRef
<Value
*> Ops
= VL
.slice(I
, OpsWidth
);
5518 Optional
<ArrayRef
<unsigned>> Order
= R
.bestOrder();
5519 // TODO: check if we can allow reordering for more cases.
5520 if (AllowReorder
&& Order
) {
5521 // TODO: reorder tree nodes without tree rebuilding.
5522 // Conceptually, there is nothing actually preventing us from trying to
5523 // reorder a larger list. In fact, we do exactly this when vectorizing
5524 // reductions. However, at this point, we only expect to get here when
5525 // there are exactly two operations.
5526 assert(Ops
.size() == 2);
5527 Value
*ReorderedOps
[] = {Ops
[1], Ops
[0]};
5528 R
.buildTree(ReorderedOps
, None
);
5530 if (R
.isTreeTinyAndNotFullyVectorizable())
5533 R
.computeMinimumValueSizes();
5534 int Cost
= R
.getTreeCost() - UserCost
;
5535 CandidateFound
= true;
5536 MinCost
= std::min(MinCost
, Cost
);
5538 if (Cost
< -SLPCostThreshold
) {
5539 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost
<< ".\n");
5540 R
.getORE()->emit(OptimizationRemark(SV_NAME
, "VectorizedList",
5541 cast
<Instruction
>(Ops
[0]))
5542 << "SLP vectorized with cost " << ore::NV("Cost", Cost
)
5543 << " and with tree size "
5544 << ore::NV("TreeSize", R
.getTreeSize()));
5547 // Move to the next bundle.
5555 if (!Changed
&& CandidateFound
) {
5556 R
.getORE()->emit([&]() {
5557 return OptimizationRemarkMissed(SV_NAME
, "NotBeneficial", I0
)
5558 << "List vectorization was possible but not beneficial with cost "
5559 << ore::NV("Cost", MinCost
) << " >= "
5560 << ore::NV("Treshold", -SLPCostThreshold
);
5562 } else if (!Changed
) {
5563 R
.getORE()->emit([&]() {
5564 return OptimizationRemarkMissed(SV_NAME
, "NotPossible", I0
)
5565 << "Cannot SLP vectorize list: vectorization was impossible"
5566 << " with available vectorization factors";
5572 bool SLPVectorizerPass::tryToVectorize(Instruction
*I
, BoUpSLP
&R
) {
5576 if (!isa
<BinaryOperator
>(I
) && !isa
<CmpInst
>(I
))
5579 Value
*P
= I
->getParent();
5581 // Vectorize in current basic block only.
5582 auto *Op0
= dyn_cast
<Instruction
>(I
->getOperand(0));
5583 auto *Op1
= dyn_cast
<Instruction
>(I
->getOperand(1));
5584 if (!Op0
|| !Op1
|| Op0
->getParent() != P
|| Op1
->getParent() != P
)
5587 // Try to vectorize V.
5588 if (tryToVectorizePair(Op0
, Op1
, R
))
5591 auto *A
= dyn_cast
<BinaryOperator
>(Op0
);
5592 auto *B
= dyn_cast
<BinaryOperator
>(Op1
);
5594 if (B
&& B
->hasOneUse()) {
5595 auto *B0
= dyn_cast
<BinaryOperator
>(B
->getOperand(0));
5596 auto *B1
= dyn_cast
<BinaryOperator
>(B
->getOperand(1));
5597 if (B0
&& B0
->getParent() == P
&& tryToVectorizePair(A
, B0
, R
))
5599 if (B1
&& B1
->getParent() == P
&& tryToVectorizePair(A
, B1
, R
))
5604 if (A
&& A
->hasOneUse()) {
5605 auto *A0
= dyn_cast
<BinaryOperator
>(A
->getOperand(0));
5606 auto *A1
= dyn_cast
<BinaryOperator
>(A
->getOperand(1));
5607 if (A0
&& A0
->getParent() == P
&& tryToVectorizePair(A0
, B
, R
))
5609 if (A1
&& A1
->getParent() == P
&& tryToVectorizePair(A1
, B
, R
))
5615 /// Generate a shuffle mask to be used in a reduction tree.
5617 /// \param VecLen The length of the vector to be reduced.
5618 /// \param NumEltsToRdx The number of elements that should be reduced in the
5620 /// \param IsPairwise Whether the reduction is a pairwise or splitting
5621 /// reduction. A pairwise reduction will generate a mask of
5622 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
5623 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
5624 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
5625 static Value
*createRdxShuffleMask(unsigned VecLen
, unsigned NumEltsToRdx
,
5626 bool IsPairwise
, bool IsLeft
,
5627 IRBuilder
<> &Builder
) {
5628 assert((IsPairwise
|| !IsLeft
) && "Don't support a <0,1,undef,...> mask");
5630 SmallVector
<Constant
*, 32> ShuffleMask(
5631 VecLen
, UndefValue::get(Builder
.getInt32Ty()));
5634 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
5635 for (unsigned i
= 0; i
!= NumEltsToRdx
; ++i
)
5636 ShuffleMask
[i
] = Builder
.getInt32(2 * i
+ !IsLeft
);
5638 // Move the upper half of the vector to the lower half.
5639 for (unsigned i
= 0; i
!= NumEltsToRdx
; ++i
)
5640 ShuffleMask
[i
] = Builder
.getInt32(NumEltsToRdx
+ i
);
5642 return ConstantVector::get(ShuffleMask
);
5647 /// Model horizontal reductions.
5649 /// A horizontal reduction is a tree of reduction operations (currently add and
5650 /// fadd) that has operations that can be put into a vector as its leaf.
5651 /// For example, this tree:
5658 /// This tree has "mul" as its reduced values and "+" as its reduction
5659 /// operations. A reduction might be feeding into a store or a binary operation
5674 class HorizontalReduction
{
5675 using ReductionOpsType
= SmallVector
<Value
*, 16>;
5676 using ReductionOpsListType
= SmallVector
<ReductionOpsType
, 2>;
5677 ReductionOpsListType ReductionOps
;
5678 SmallVector
<Value
*, 32> ReducedVals
;
5679 // Use map vector to make stable output.
5680 MapVector
<Instruction
*, Value
*> ExtraArgs
;
5682 /// Kind of the reduction data.
5683 enum ReductionKind
{
5684 RK_None
, /// Not a reduction.
5685 RK_Arithmetic
, /// Binary reduction data.
5686 RK_Min
, /// Minimum reduction data.
5687 RK_UMin
, /// Unsigned minimum reduction data.
5688 RK_Max
, /// Maximum reduction data.
5689 RK_UMax
, /// Unsigned maximum reduction data.
5692 /// Contains info about operation, like its opcode, left and right operands.
5693 class OperationData
{
5694 /// Opcode of the instruction.
5695 unsigned Opcode
= 0;
5697 /// Left operand of the reduction operation.
5698 Value
*LHS
= nullptr;
5700 /// Right operand of the reduction operation.
5701 Value
*RHS
= nullptr;
5703 /// Kind of the reduction operation.
5704 ReductionKind Kind
= RK_None
;
5706 /// True if float point min/max reduction has no NaNs.
5709 /// Checks if the reduction operation can be vectorized.
5710 bool isVectorizable() const {
5711 return LHS
&& RHS
&&
5712 // We currently only support add/mul/logical && min/max reductions.
5713 ((Kind
== RK_Arithmetic
&&
5714 (Opcode
== Instruction::Add
|| Opcode
== Instruction::FAdd
||
5715 Opcode
== Instruction::Mul
|| Opcode
== Instruction::FMul
||
5716 Opcode
== Instruction::And
|| Opcode
== Instruction::Or
||
5717 Opcode
== Instruction::Xor
)) ||
5718 ((Opcode
== Instruction::ICmp
|| Opcode
== Instruction::FCmp
) &&
5719 (Kind
== RK_Min
|| Kind
== RK_Max
)) ||
5720 (Opcode
== Instruction::ICmp
&&
5721 (Kind
== RK_UMin
|| Kind
== RK_UMax
)));
5724 /// Creates reduction operation with the current opcode.
5725 Value
*createOp(IRBuilder
<> &Builder
, const Twine
&Name
) const {
5726 assert(isVectorizable() &&
5727 "Expected add|fadd or min/max reduction operation.");
5728 Value
*Cmp
= nullptr;
5731 return Builder
.CreateBinOp((Instruction::BinaryOps
)Opcode
, LHS
, RHS
,
5734 Cmp
= Opcode
== Instruction::ICmp
? Builder
.CreateICmpSLT(LHS
, RHS
)
5735 : Builder
.CreateFCmpOLT(LHS
, RHS
);
5738 Cmp
= Opcode
== Instruction::ICmp
? Builder
.CreateICmpSGT(LHS
, RHS
)
5739 : Builder
.CreateFCmpOGT(LHS
, RHS
);
5742 assert(Opcode
== Instruction::ICmp
&& "Expected integer types.");
5743 Cmp
= Builder
.CreateICmpULT(LHS
, RHS
);
5746 assert(Opcode
== Instruction::ICmp
&& "Expected integer types.");
5747 Cmp
= Builder
.CreateICmpUGT(LHS
, RHS
);
5750 llvm_unreachable("Unknown reduction operation.");
5752 return Builder
.CreateSelect(Cmp
, LHS
, RHS
, Name
);
5756 explicit OperationData() = default;
5758 /// Construction for reduced values. They are identified by opcode only and
5759 /// don't have associated LHS/RHS values.
5760 explicit OperationData(Value
*V
) {
5761 if (auto *I
= dyn_cast
<Instruction
>(V
))
5762 Opcode
= I
->getOpcode();
5765 /// Constructor for reduction operations with opcode and its left and
5767 OperationData(unsigned Opcode
, Value
*LHS
, Value
*RHS
, ReductionKind Kind
,
5769 : Opcode(Opcode
), LHS(LHS
), RHS(RHS
), Kind(Kind
), NoNaN(NoNaN
) {
5770 assert(Kind
!= RK_None
&& "One of the reduction operations is expected.");
5773 explicit operator bool() const { return Opcode
; }
5775 /// Get the index of the first operand.
5776 unsigned getFirstOperandIndex() const {
5777 assert(!!*this && "The opcode is not set.");
5791 /// Total number of operands in the reduction operation.
5792 unsigned getNumberOfOperands() const {
5793 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5794 "Expected reduction operation.");
5806 llvm_unreachable("Reduction kind is not set");
5809 /// Checks if the operation has the same parent as \p P.
5810 bool hasSameParent(Instruction
*I
, Value
*P
, bool IsRedOp
) const {
5811 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5812 "Expected reduction operation.");
5814 return I
->getParent() == P
;
5817 // Arithmetic reduction operation must be used once only.
5818 return I
->getParent() == P
;
5823 // SelectInst must be used twice while the condition op must have single
5825 auto *Cmp
= cast
<Instruction
>(cast
<SelectInst
>(I
)->getCondition());
5826 return I
->getParent() == P
&& Cmp
&& Cmp
->getParent() == P
;
5831 llvm_unreachable("Reduction kind is not set");
5833 /// Expected number of uses for reduction operations/reduced values.
5834 bool hasRequiredNumberOfUses(Instruction
*I
, bool IsReductionOp
) const {
5835 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5836 "Expected reduction operation.");
5839 return I
->hasOneUse();
5844 return I
->hasNUses(2) &&
5846 cast
<SelectInst
>(I
)->getCondition()->hasOneUse());
5850 llvm_unreachable("Reduction kind is not set");
5853 /// Initializes the list of reduction operations.
5854 void initReductionOps(ReductionOpsListType
&ReductionOps
) {
5855 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5856 "Expected reduction operation.");
5859 ReductionOps
.assign(1, ReductionOpsType());
5865 ReductionOps
.assign(2, ReductionOpsType());
5868 llvm_unreachable("Reduction kind is not set");
5871 /// Add all reduction operations for the reduction instruction \p I.
5872 void addReductionOps(Instruction
*I
, ReductionOpsListType
&ReductionOps
) {
5873 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5874 "Expected reduction operation.");
5877 ReductionOps
[0].emplace_back(I
);
5883 ReductionOps
[0].emplace_back(cast
<SelectInst
>(I
)->getCondition());
5884 ReductionOps
[1].emplace_back(I
);
5887 llvm_unreachable("Reduction kind is not set");
5891 /// Checks if instruction is associative and can be vectorized.
5892 bool isAssociative(Instruction
*I
) const {
5893 assert(Kind
!= RK_None
&& *this && LHS
&& RHS
&&
5894 "Expected reduction operation.");
5897 return I
->isAssociative();
5900 return Opcode
== Instruction::ICmp
||
5901 cast
<Instruction
>(I
->getOperand(0))->isFast();
5904 assert(Opcode
== Instruction::ICmp
&&
5905 "Only integer compare operation is expected.");
5910 llvm_unreachable("Reduction kind is not set");
5913 /// Checks if the reduction operation can be vectorized.
5914 bool isVectorizable(Instruction
*I
) const {
5915 return isVectorizable() && isAssociative(I
);
5918 /// Checks if two operation data are both a reduction op or both a reduced
5920 bool operator==(const OperationData
&OD
) {
5921 assert(((Kind
!= OD
.Kind
) || ((!LHS
== !OD
.LHS
) && (!RHS
== !OD
.RHS
))) &&
5922 "One of the comparing operations is incorrect.");
5923 return this == &OD
|| (Kind
== OD
.Kind
&& Opcode
== OD
.Opcode
);
5925 bool operator!=(const OperationData
&OD
) { return !(*this == OD
); }
5934 /// Get the opcode of the reduction operation.
5935 unsigned getOpcode() const {
5936 assert(isVectorizable() && "Expected vectorizable operation.");
5940 /// Get kind of reduction data.
5941 ReductionKind
getKind() const { return Kind
; }
5942 Value
*getLHS() const { return LHS
; }
5943 Value
*getRHS() const { return RHS
; }
5944 Type
*getConditionType() const {
5952 return CmpInst::makeCmpResultType(LHS
->getType());
5956 llvm_unreachable("Reduction kind is not set");
5959 /// Creates reduction operation with the current opcode with the IR flags
5960 /// from \p ReductionOps.
5961 Value
*createOp(IRBuilder
<> &Builder
, const Twine
&Name
,
5962 const ReductionOpsListType
&ReductionOps
) const {
5963 assert(isVectorizable() &&
5964 "Expected add|fadd or min/max reduction operation.");
5965 auto *Op
= createOp(Builder
, Name
);
5968 propagateIRFlags(Op
, ReductionOps
[0]);
5974 if (auto *SI
= dyn_cast
<SelectInst
>(Op
))
5975 propagateIRFlags(SI
->getCondition(), ReductionOps
[0]);
5976 propagateIRFlags(Op
, ReductionOps
[1]);
5981 llvm_unreachable("Unknown reduction operation.");
5983 /// Creates reduction operation with the current opcode with the IR flags
5985 Value
*createOp(IRBuilder
<> &Builder
, const Twine
&Name
,
5986 Instruction
*I
) const {
5987 assert(isVectorizable() &&
5988 "Expected add|fadd or min/max reduction operation.");
5989 auto *Op
= createOp(Builder
, Name
);
5992 propagateIRFlags(Op
, I
);
5998 if (auto *SI
= dyn_cast
<SelectInst
>(Op
)) {
5999 propagateIRFlags(SI
->getCondition(),
6000 cast
<SelectInst
>(I
)->getCondition());
6002 propagateIRFlags(Op
, I
);
6007 llvm_unreachable("Unknown reduction operation.");
6010 TargetTransformInfo::ReductionFlags
getFlags() const {
6011 TargetTransformInfo::ReductionFlags Flags
;
6012 Flags
.NoNaN
= NoNaN
;
6017 Flags
.IsSigned
= Opcode
== Instruction::ICmp
;
6018 Flags
.IsMaxOp
= false;
6021 Flags
.IsSigned
= Opcode
== Instruction::ICmp
;
6022 Flags
.IsMaxOp
= true;
6025 Flags
.IsSigned
= false;
6026 Flags
.IsMaxOp
= false;
6029 Flags
.IsSigned
= false;
6030 Flags
.IsMaxOp
= true;
6033 llvm_unreachable("Reduction kind is not set");
6039 WeakTrackingVH ReductionRoot
;
6041 /// The operation data of the reduction operation.
6042 OperationData ReductionData
;
6044 /// The operation data of the values we perform a reduction on.
6045 OperationData ReducedValueData
;
6047 /// Should we model this reduction as a pairwise reduction tree or a tree that
6048 /// splits the vector in halves and adds those halves.
6049 bool IsPairwiseReduction
= false;
6051 /// Checks if the ParentStackElem.first should be marked as a reduction
6052 /// operation with an extra argument or as extra argument itself.
6053 void markExtraArg(std::pair
<Instruction
*, unsigned> &ParentStackElem
,
6055 if (ExtraArgs
.count(ParentStackElem
.first
)) {
6056 ExtraArgs
[ParentStackElem
.first
] = nullptr;
6057 // We ran into something like:
6058 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6059 // The whole ParentStackElem.first should be considered as an extra value
6061 // Do not perform analysis of remaining operands of ParentStackElem.first
6062 // instruction, this whole instruction is an extra argument.
6063 ParentStackElem
.second
= ParentStackElem
.first
->getNumOperands();
6065 // We ran into something like:
6066 // ParentStackElem.first += ... + ExtraArg + ...
6067 ExtraArgs
[ParentStackElem
.first
] = ExtraArg
;
6071 static OperationData
getOperationData(Value
*V
) {
6073 return OperationData();
6077 if (m_BinOp(m_Value(LHS
), m_Value(RHS
)).match(V
)) {
6078 return OperationData(cast
<BinaryOperator
>(V
)->getOpcode(), LHS
, RHS
,
6081 if (auto *Select
= dyn_cast
<SelectInst
>(V
)) {
6082 // Look for a min/max pattern.
6083 if (m_UMin(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6084 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMin
);
6085 } else if (m_SMin(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6086 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Min
);
6087 } else if (m_OrdFMin(m_Value(LHS
), m_Value(RHS
)).match(Select
) ||
6088 m_UnordFMin(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6089 return OperationData(
6090 Instruction::FCmp
, LHS
, RHS
, RK_Min
,
6091 cast
<Instruction
>(Select
->getCondition())->hasNoNaNs());
6092 } else if (m_UMax(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6093 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMax
);
6094 } else if (m_SMax(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6095 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Max
);
6096 } else if (m_OrdFMax(m_Value(LHS
), m_Value(RHS
)).match(Select
) ||
6097 m_UnordFMax(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6098 return OperationData(
6099 Instruction::FCmp
, LHS
, RHS
, RK_Max
,
6100 cast
<Instruction
>(Select
->getCondition())->hasNoNaNs());
6102 // Try harder: look for min/max pattern based on instructions producing
6103 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6104 // During the intermediate stages of SLP, it's very common to have
6105 // pattern like this (since optimizeGatherSequence is run only once
6107 // %1 = extractelement <2 x i32> %a, i32 0
6108 // %2 = extractelement <2 x i32> %a, i32 1
6109 // %cond = icmp sgt i32 %1, %2
6110 // %3 = extractelement <2 x i32> %a, i32 0
6111 // %4 = extractelement <2 x i32> %a, i32 1
6112 // %select = select i1 %cond, i32 %3, i32 %4
6113 CmpInst::Predicate Pred
;
6117 LHS
= Select
->getTrueValue();
6118 RHS
= Select
->getFalseValue();
6119 Value
*Cond
= Select
->getCondition();
6121 // TODO: Support inverse predicates.
6122 if (match(Cond
, m_Cmp(Pred
, m_Specific(LHS
), m_Instruction(L2
)))) {
6123 if (!isa
<ExtractElementInst
>(RHS
) ||
6124 !L2
->isIdenticalTo(cast
<Instruction
>(RHS
)))
6125 return OperationData(V
);
6126 } else if (match(Cond
, m_Cmp(Pred
, m_Instruction(L1
), m_Specific(RHS
)))) {
6127 if (!isa
<ExtractElementInst
>(LHS
) ||
6128 !L1
->isIdenticalTo(cast
<Instruction
>(LHS
)))
6129 return OperationData(V
);
6131 if (!isa
<ExtractElementInst
>(LHS
) || !isa
<ExtractElementInst
>(RHS
))
6132 return OperationData(V
);
6133 if (!match(Cond
, m_Cmp(Pred
, m_Instruction(L1
), m_Instruction(L2
))) ||
6134 !L1
->isIdenticalTo(cast
<Instruction
>(LHS
)) ||
6135 !L2
->isIdenticalTo(cast
<Instruction
>(RHS
)))
6136 return OperationData(V
);
6140 return OperationData(V
);
6142 case CmpInst::ICMP_ULT
:
6143 case CmpInst::ICMP_ULE
:
6144 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMin
);
6146 case CmpInst::ICMP_SLT
:
6147 case CmpInst::ICMP_SLE
:
6148 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Min
);
6150 case CmpInst::FCMP_OLT
:
6151 case CmpInst::FCMP_OLE
:
6152 case CmpInst::FCMP_ULT
:
6153 case CmpInst::FCMP_ULE
:
6154 return OperationData(Instruction::FCmp
, LHS
, RHS
, RK_Min
,
6155 cast
<Instruction
>(Cond
)->hasNoNaNs());
6157 case CmpInst::ICMP_UGT
:
6158 case CmpInst::ICMP_UGE
:
6159 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMax
);
6161 case CmpInst::ICMP_SGT
:
6162 case CmpInst::ICMP_SGE
:
6163 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Max
);
6165 case CmpInst::FCMP_OGT
:
6166 case CmpInst::FCMP_OGE
:
6167 case CmpInst::FCMP_UGT
:
6168 case CmpInst::FCMP_UGE
:
6169 return OperationData(Instruction::FCmp
, LHS
, RHS
, RK_Max
,
6170 cast
<Instruction
>(Cond
)->hasNoNaNs());
6174 return OperationData(V
);
6178 HorizontalReduction() = default;
6180 /// Try to find a reduction tree.
6181 bool matchAssociativeReduction(PHINode
*Phi
, Instruction
*B
) {
6182 assert((!Phi
|| is_contained(Phi
->operands(), B
)) &&
6183 "Thi phi needs to use the binary operator");
6185 ReductionData
= getOperationData(B
);
6187 // We could have a initial reductions that is not an add.
6188 // r *= v1 + v2 + v3 + v4
6189 // In such a case start looking for a tree rooted in the first '+'.
6191 if (ReductionData
.getLHS() == Phi
) {
6193 B
= dyn_cast
<Instruction
>(ReductionData
.getRHS());
6194 ReductionData
= getOperationData(B
);
6195 } else if (ReductionData
.getRHS() == Phi
) {
6197 B
= dyn_cast
<Instruction
>(ReductionData
.getLHS());
6198 ReductionData
= getOperationData(B
);
6202 if (!ReductionData
.isVectorizable(B
))
6205 Type
*Ty
= B
->getType();
6206 if (!isValidElementType(Ty
))
6208 if (!Ty
->isIntOrIntVectorTy() && !Ty
->isFPOrFPVectorTy())
6211 ReducedValueData
.clear();
6214 // Post order traverse the reduction tree starting at B. We only handle true
6215 // trees containing only binary operators.
6216 SmallVector
<std::pair
<Instruction
*, unsigned>, 32> Stack
;
6217 Stack
.push_back(std::make_pair(B
, ReductionData
.getFirstOperandIndex()));
6218 ReductionData
.initReductionOps(ReductionOps
);
6219 while (!Stack
.empty()) {
6220 Instruction
*TreeN
= Stack
.back().first
;
6221 unsigned EdgeToVist
= Stack
.back().second
++;
6222 OperationData OpData
= getOperationData(TreeN
);
6223 bool IsReducedValue
= OpData
!= ReductionData
;
6226 if (IsReducedValue
|| EdgeToVist
== OpData
.getNumberOfOperands()) {
6228 ReducedVals
.push_back(TreeN
);
6230 auto I
= ExtraArgs
.find(TreeN
);
6231 if (I
!= ExtraArgs
.end() && !I
->second
) {
6232 // Check if TreeN is an extra argument of its parent operation.
6233 if (Stack
.size() <= 1) {
6234 // TreeN can't be an extra argument as it is a root reduction
6238 // Yes, TreeN is an extra argument, do not add it to a list of
6239 // reduction operations.
6240 // Stack[Stack.size() - 2] always points to the parent operation.
6241 markExtraArg(Stack
[Stack
.size() - 2], TreeN
);
6242 ExtraArgs
.erase(TreeN
);
6244 ReductionData
.addReductionOps(TreeN
, ReductionOps
);
6251 // Visit left or right.
6252 Value
*NextV
= TreeN
->getOperand(EdgeToVist
);
6254 auto *I
= dyn_cast
<Instruction
>(NextV
);
6255 OpData
= getOperationData(I
);
6256 // Continue analysis if the next operand is a reduction operation or
6257 // (possibly) a reduced value. If the reduced value opcode is not set,
6258 // the first met operation != reduction operation is considered as the
6259 // reduced value class.
6260 if (I
&& (!ReducedValueData
|| OpData
== ReducedValueData
||
6261 OpData
== ReductionData
)) {
6262 const bool IsReductionOperation
= OpData
== ReductionData
;
6263 // Only handle trees in the current basic block.
6264 if (!ReductionData
.hasSameParent(I
, B
->getParent(),
6265 IsReductionOperation
)) {
6266 // I is an extra argument for TreeN (its parent operation).
6267 markExtraArg(Stack
.back(), I
);
6271 // Each tree node needs to have minimal number of users except for the
6272 // ultimate reduction.
6273 if (!ReductionData
.hasRequiredNumberOfUses(I
,
6274 OpData
== ReductionData
) &&
6276 // I is an extra argument for TreeN (its parent operation).
6277 markExtraArg(Stack
.back(), I
);
6281 if (IsReductionOperation
) {
6282 // We need to be able to reassociate the reduction operations.
6283 if (!OpData
.isAssociative(I
)) {
6284 // I is an extra argument for TreeN (its parent operation).
6285 markExtraArg(Stack
.back(), I
);
6288 } else if (ReducedValueData
&&
6289 ReducedValueData
!= OpData
) {
6290 // Make sure that the opcodes of the operations that we are going to
6292 // I is an extra argument for TreeN (its parent operation).
6293 markExtraArg(Stack
.back(), I
);
6295 } else if (!ReducedValueData
)
6296 ReducedValueData
= OpData
;
6298 Stack
.push_back(std::make_pair(I
, OpData
.getFirstOperandIndex()));
6302 // NextV is an extra argument for TreeN (its parent operation).
6303 markExtraArg(Stack
.back(), NextV
);
6308 /// Attempt to vectorize the tree found by
6309 /// matchAssociativeReduction.
6310 bool tryToReduce(BoUpSLP
&V
, TargetTransformInfo
*TTI
) {
6311 if (ReducedVals
.empty())
6314 // If there is a sufficient number of reduction values, reduce
6315 // to a nearby power-of-2. Can safely generate oversized
6316 // vectors and rely on the backend to split them to legal sizes.
6317 unsigned NumReducedVals
= ReducedVals
.size();
6318 if (NumReducedVals
< 4)
6321 unsigned ReduxWidth
= PowerOf2Floor(NumReducedVals
);
6323 Value
*VectorizedTree
= nullptr;
6325 // FIXME: Fast-math-flags should be set based on the instructions in the
6326 // reduction (not all of 'fast' are required).
6327 IRBuilder
<> Builder(cast
<Instruction
>(ReductionRoot
));
6328 FastMathFlags Unsafe
;
6330 Builder
.setFastMathFlags(Unsafe
);
6333 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues
;
6334 // The same extra argument may be used several time, so log each attempt
6336 for (auto &Pair
: ExtraArgs
) {
6337 assert(Pair
.first
&& "DebugLoc must be set.");
6338 ExternallyUsedValues
[Pair
.second
].push_back(Pair
.first
);
6340 // The reduction root is used as the insertion point for new instructions,
6341 // so set it as externally used to prevent it from being deleted.
6342 ExternallyUsedValues
[ReductionRoot
];
6343 SmallVector
<Value
*, 16> IgnoreList
;
6344 for (auto &V
: ReductionOps
)
6345 IgnoreList
.append(V
.begin(), V
.end());
6346 while (i
< NumReducedVals
- ReduxWidth
+ 1 && ReduxWidth
> 2) {
6347 auto VL
= makeArrayRef(&ReducedVals
[i
], ReduxWidth
);
6348 V
.buildTree(VL
, ExternallyUsedValues
, IgnoreList
);
6349 Optional
<ArrayRef
<unsigned>> Order
= V
.bestOrder();
6350 // TODO: Handle orders of size less than number of elements in the vector.
6351 if (Order
&& Order
->size() == VL
.size()) {
6352 // TODO: reorder tree nodes without tree rebuilding.
6353 SmallVector
<Value
*, 4> ReorderedOps(VL
.size());
6354 llvm::transform(*Order
, ReorderedOps
.begin(),
6355 [VL
](const unsigned Idx
) { return VL
[Idx
]; });
6356 V
.buildTree(ReorderedOps
, ExternallyUsedValues
, IgnoreList
);
6358 if (V
.isTreeTinyAndNotFullyVectorizable())
6361 V
.computeMinimumValueSizes();
6364 int TreeCost
= V
.getTreeCost();
6365 int ReductionCost
= getReductionCost(TTI
, ReducedVals
[i
], ReduxWidth
);
6366 int Cost
= TreeCost
+ ReductionCost
;
6367 if (Cost
>= -SLPCostThreshold
) {
6368 V
.getORE()->emit([&]() {
6369 return OptimizationRemarkMissed(
6370 SV_NAME
, "HorSLPNotBeneficial", cast
<Instruction
>(VL
[0]))
6371 << "Vectorizing horizontal reduction is possible"
6372 << "but not beneficial with cost "
6373 << ore::NV("Cost", Cost
) << " and threshold "
6374 << ore::NV("Threshold", -SLPCostThreshold
);
6379 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
6380 << Cost
<< ". (HorRdx)\n");
6381 V
.getORE()->emit([&]() {
6382 return OptimizationRemark(
6383 SV_NAME
, "VectorizedHorizontalReduction", cast
<Instruction
>(VL
[0]))
6384 << "Vectorized horizontal reduction with cost "
6385 << ore::NV("Cost", Cost
) << " and with tree size "
6386 << ore::NV("TreeSize", V
.getTreeSize());
6389 // Vectorize a tree.
6390 DebugLoc Loc
= cast
<Instruction
>(ReducedVals
[i
])->getDebugLoc();
6391 Value
*VectorizedRoot
= V
.vectorizeTree(ExternallyUsedValues
);
6393 // Emit a reduction.
6394 Builder
.SetInsertPoint(cast
<Instruction
>(ReductionRoot
));
6395 Value
*ReducedSubTree
=
6396 emitReduction(VectorizedRoot
, Builder
, ReduxWidth
, TTI
);
6397 if (VectorizedTree
) {
6398 Builder
.SetCurrentDebugLocation(Loc
);
6399 OperationData
VectReductionData(ReductionData
.getOpcode(),
6400 VectorizedTree
, ReducedSubTree
,
6401 ReductionData
.getKind());
6403 VectReductionData
.createOp(Builder
, "op.rdx", ReductionOps
);
6405 VectorizedTree
= ReducedSubTree
;
6407 ReduxWidth
= PowerOf2Floor(NumReducedVals
- i
);
6410 if (VectorizedTree
) {
6411 // Finish the reduction.
6412 for (; i
< NumReducedVals
; ++i
) {
6413 auto *I
= cast
<Instruction
>(ReducedVals
[i
]);
6414 Builder
.SetCurrentDebugLocation(I
->getDebugLoc());
6415 OperationData
VectReductionData(ReductionData
.getOpcode(),
6417 ReductionData
.getKind());
6418 VectorizedTree
= VectReductionData
.createOp(Builder
, "", ReductionOps
);
6420 for (auto &Pair
: ExternallyUsedValues
) {
6421 // Add each externally used value to the final reduction.
6422 for (auto *I
: Pair
.second
) {
6423 Builder
.SetCurrentDebugLocation(I
->getDebugLoc());
6424 OperationData
VectReductionData(ReductionData
.getOpcode(),
6425 VectorizedTree
, Pair
.first
,
6426 ReductionData
.getKind());
6427 VectorizedTree
= VectReductionData
.createOp(Builder
, "op.extra", I
);
6431 ReductionRoot
->replaceAllUsesWith(VectorizedTree
);
6433 return VectorizedTree
!= nullptr;
6436 unsigned numReductionValues() const {
6437 return ReducedVals
.size();
6441 /// Calculate the cost of a reduction.
6442 int getReductionCost(TargetTransformInfo
*TTI
, Value
*FirstReducedVal
,
6443 unsigned ReduxWidth
) {
6444 Type
*ScalarTy
= FirstReducedVal
->getType();
6445 Type
*VecTy
= VectorType::get(ScalarTy
, ReduxWidth
);
6447 int PairwiseRdxCost
;
6448 int SplittingRdxCost
;
6449 switch (ReductionData
.getKind()) {
6452 TTI
->getArithmeticReductionCost(ReductionData
.getOpcode(), VecTy
,
6453 /*IsPairwiseForm=*/true);
6455 TTI
->getArithmeticReductionCost(ReductionData
.getOpcode(), VecTy
,
6456 /*IsPairwiseForm=*/false);
6462 Type
*VecCondTy
= CmpInst::makeCmpResultType(VecTy
);
6463 bool IsUnsigned
= ReductionData
.getKind() == RK_UMin
||
6464 ReductionData
.getKind() == RK_UMax
;
6466 TTI
->getMinMaxReductionCost(VecTy
, VecCondTy
,
6467 /*IsPairwiseForm=*/true, IsUnsigned
);
6469 TTI
->getMinMaxReductionCost(VecTy
, VecCondTy
,
6470 /*IsPairwiseForm=*/false, IsUnsigned
);
6474 llvm_unreachable("Expected arithmetic or min/max reduction operation");
6477 IsPairwiseReduction
= PairwiseRdxCost
< SplittingRdxCost
;
6478 int VecReduxCost
= IsPairwiseReduction
? PairwiseRdxCost
: SplittingRdxCost
;
6480 int ScalarReduxCost
= 0;
6481 switch (ReductionData
.getKind()) {
6484 TTI
->getArithmeticInstrCost(ReductionData
.getOpcode(), ScalarTy
);
6491 TTI
->getCmpSelInstrCost(ReductionData
.getOpcode(), ScalarTy
) +
6492 TTI
->getCmpSelInstrCost(Instruction::Select
, ScalarTy
,
6493 CmpInst::makeCmpResultType(ScalarTy
));
6496 llvm_unreachable("Expected arithmetic or min/max reduction operation");
6498 ScalarReduxCost
*= (ReduxWidth
- 1);
6500 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost
- ScalarReduxCost
6501 << " for reduction that starts with " << *FirstReducedVal
6503 << (IsPairwiseReduction
? "pairwise" : "splitting")
6504 << " reduction)\n");
6506 return VecReduxCost
- ScalarReduxCost
;
6509 /// Emit a horizontal reduction of the vectorized value.
6510 Value
*emitReduction(Value
*VectorizedValue
, IRBuilder
<> &Builder
,
6511 unsigned ReduxWidth
, const TargetTransformInfo
*TTI
) {
6512 assert(VectorizedValue
&& "Need to have a vectorized tree node");
6513 assert(isPowerOf2_32(ReduxWidth
) &&
6514 "We only handle power-of-two reductions for now");
6516 if (!IsPairwiseReduction
) {
6517 // FIXME: The builder should use an FMF guard. It should not be hard-coded
6519 assert(Builder
.getFastMathFlags().isFast() && "Expected 'fast' FMF");
6520 return createSimpleTargetReduction(
6521 Builder
, TTI
, ReductionData
.getOpcode(), VectorizedValue
,
6522 ReductionData
.getFlags(), ReductionOps
.back());
6525 Value
*TmpVec
= VectorizedValue
;
6526 for (unsigned i
= ReduxWidth
/ 2; i
!= 0; i
>>= 1) {
6528 createRdxShuffleMask(ReduxWidth
, i
, true, true, Builder
);
6530 createRdxShuffleMask(ReduxWidth
, i
, true, false, Builder
);
6532 Value
*LeftShuf
= Builder
.CreateShuffleVector(
6533 TmpVec
, UndefValue::get(TmpVec
->getType()), LeftMask
, "rdx.shuf.l");
6534 Value
*RightShuf
= Builder
.CreateShuffleVector(
6535 TmpVec
, UndefValue::get(TmpVec
->getType()), (RightMask
),
6537 OperationData
VectReductionData(ReductionData
.getOpcode(), LeftShuf
,
6538 RightShuf
, ReductionData
.getKind());
6539 TmpVec
= VectReductionData
.createOp(Builder
, "op.rdx", ReductionOps
);
6542 // The result is in the first element of the vector.
6543 return Builder
.CreateExtractElement(TmpVec
, Builder
.getInt32(0));
6547 } // end anonymous namespace
6549 /// Recognize construction of vectors like
6550 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
6551 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
6552 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
6553 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
6554 /// starting from the last insertelement instruction.
6556 /// Returns true if it matches
6557 static bool findBuildVector(InsertElementInst
*LastInsertElem
,
6558 TargetTransformInfo
*TTI
,
6559 SmallVectorImpl
<Value
*> &BuildVectorOpds
,
6564 if (auto *CI
= dyn_cast
<ConstantInt
>(LastInsertElem
->getOperand(2))) {
6565 UserCost
+= TTI
->getVectorInstrCost(Instruction::InsertElement
,
6566 LastInsertElem
->getType(),
6567 CI
->getZExtValue());
6569 BuildVectorOpds
.push_back(LastInsertElem
->getOperand(1));
6570 V
= LastInsertElem
->getOperand(0);
6571 if (isa
<UndefValue
>(V
))
6573 LastInsertElem
= dyn_cast
<InsertElementInst
>(V
);
6574 if (!LastInsertElem
|| !LastInsertElem
->hasOneUse())
6577 std::reverse(BuildVectorOpds
.begin(), BuildVectorOpds
.end());
6581 /// Like findBuildVector, but looks for construction of aggregate.
6583 /// \return true if it matches.
6584 static bool findBuildAggregate(InsertValueInst
*IV
,
6585 SmallVectorImpl
<Value
*> &BuildVectorOpds
) {
6587 BuildVectorOpds
.push_back(IV
->getInsertedValueOperand());
6588 Value
*V
= IV
->getAggregateOperand();
6589 if (isa
<UndefValue
>(V
))
6591 IV
= dyn_cast
<InsertValueInst
>(V
);
6592 if (!IV
|| !IV
->hasOneUse())
6595 std::reverse(BuildVectorOpds
.begin(), BuildVectorOpds
.end());
6599 static bool PhiTypeSorterFunc(Value
*V
, Value
*V2
) {
6600 return V
->getType() < V2
->getType();
6603 /// Try and get a reduction value from a phi node.
6605 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
6606 /// if they come from either \p ParentBB or a containing loop latch.
6608 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
6609 /// if not possible.
6610 static Value
*getReductionValue(const DominatorTree
*DT
, PHINode
*P
,
6611 BasicBlock
*ParentBB
, LoopInfo
*LI
) {
6612 // There are situations where the reduction value is not dominated by the
6613 // reduction phi. Vectorizing such cases has been reported to cause
6614 // miscompiles. See PR25787.
6615 auto DominatedReduxValue
= [&](Value
*R
) {
6616 return isa
<Instruction
>(R
) &&
6617 DT
->dominates(P
->getParent(), cast
<Instruction
>(R
)->getParent());
6620 Value
*Rdx
= nullptr;
6622 // Return the incoming value if it comes from the same BB as the phi node.
6623 if (P
->getIncomingBlock(0) == ParentBB
) {
6624 Rdx
= P
->getIncomingValue(0);
6625 } else if (P
->getIncomingBlock(1) == ParentBB
) {
6626 Rdx
= P
->getIncomingValue(1);
6629 if (Rdx
&& DominatedReduxValue(Rdx
))
6632 // Otherwise, check whether we have a loop latch to look at.
6633 Loop
*BBL
= LI
->getLoopFor(ParentBB
);
6636 BasicBlock
*BBLatch
= BBL
->getLoopLatch();
6640 // There is a loop latch, return the incoming value if it comes from
6641 // that. This reduction pattern occasionally turns up.
6642 if (P
->getIncomingBlock(0) == BBLatch
) {
6643 Rdx
= P
->getIncomingValue(0);
6644 } else if (P
->getIncomingBlock(1) == BBLatch
) {
6645 Rdx
= P
->getIncomingValue(1);
6648 if (Rdx
&& DominatedReduxValue(Rdx
))
6654 /// Attempt to reduce a horizontal reduction.
6655 /// If it is legal to match a horizontal reduction feeding the phi node \a P
6656 /// with reduction operators \a Root (or one of its operands) in a basic block
6657 /// \a BB, then check if it can be done. If horizontal reduction is not found
6658 /// and root instruction is a binary operation, vectorization of the operands is
6660 /// \returns true if a horizontal reduction was matched and reduced or operands
6661 /// of one of the binary instruction were vectorized.
6662 /// \returns false if a horizontal reduction was not matched (or not possible)
6663 /// or no vectorization of any binary operation feeding \a Root instruction was
6665 static bool tryToVectorizeHorReductionOrInstOperands(
6666 PHINode
*P
, Instruction
*Root
, BasicBlock
*BB
, BoUpSLP
&R
,
6667 TargetTransformInfo
*TTI
,
6668 const function_ref
<bool(Instruction
*, BoUpSLP
&)> Vectorize
) {
6669 if (!ShouldVectorizeHor
)
6675 if (Root
->getParent() != BB
|| isa
<PHINode
>(Root
))
6677 // Start analysis starting from Root instruction. If horizontal reduction is
6678 // found, try to vectorize it. If it is not a horizontal reduction or
6679 // vectorization is not possible or not effective, and currently analyzed
6680 // instruction is a binary operation, try to vectorize the operands, using
6681 // pre-order DFS traversal order. If the operands were not vectorized, repeat
6682 // the same procedure considering each operand as a possible root of the
6683 // horizontal reduction.
6684 // Interrupt the process if the Root instruction itself was vectorized or all
6685 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
6686 SmallVector
<std::pair
<WeakTrackingVH
, unsigned>, 8> Stack(1, {Root
, 0});
6687 SmallPtrSet
<Value
*, 8> VisitedInstrs
;
6689 while (!Stack
.empty()) {
6692 std::tie(V
, Level
) = Stack
.pop_back_val();
6695 auto *Inst
= dyn_cast
<Instruction
>(V
);
6698 auto *BI
= dyn_cast
<BinaryOperator
>(Inst
);
6699 auto *SI
= dyn_cast
<SelectInst
>(Inst
);
6701 HorizontalReduction HorRdx
;
6702 if (HorRdx
.matchAssociativeReduction(P
, Inst
)) {
6703 if (HorRdx
.tryToReduce(R
, TTI
)) {
6705 // Set P to nullptr to avoid re-analysis of phi node in
6706 // matchAssociativeReduction function unless this is the root node.
6712 Inst
= dyn_cast
<Instruction
>(BI
->getOperand(0));
6714 Inst
= dyn_cast
<Instruction
>(BI
->getOperand(1));
6716 // Set P to nullptr to avoid re-analysis of phi node in
6717 // matchAssociativeReduction function unless this is the root node.
6723 // Set P to nullptr to avoid re-analysis of phi node in
6724 // matchAssociativeReduction function unless this is the root node.
6726 if (Vectorize(Inst
, R
)) {
6731 // Try to vectorize operands.
6732 // Continue analysis for the instruction from the same basic block only to
6733 // save compile time.
6734 if (++Level
< RecursionMaxDepth
)
6735 for (auto *Op
: Inst
->operand_values())
6736 if (VisitedInstrs
.insert(Op
).second
)
6737 if (auto *I
= dyn_cast
<Instruction
>(Op
))
6738 if (!isa
<PHINode
>(I
) && I
->getParent() == BB
)
6739 Stack
.emplace_back(Op
, Level
);
6744 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode
*P
, Value
*V
,
6745 BasicBlock
*BB
, BoUpSLP
&R
,
6746 TargetTransformInfo
*TTI
) {
6749 auto *I
= dyn_cast
<Instruction
>(V
);
6753 if (!isa
<BinaryOperator
>(I
))
6755 // Try to match and vectorize a horizontal reduction.
6756 auto &&ExtraVectorization
= [this](Instruction
*I
, BoUpSLP
&R
) -> bool {
6757 return tryToVectorize(I
, R
);
6759 return tryToVectorizeHorReductionOrInstOperands(P
, I
, BB
, R
, TTI
,
6760 ExtraVectorization
);
6763 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst
*IVI
,
6764 BasicBlock
*BB
, BoUpSLP
&R
) {
6765 const DataLayout
&DL
= BB
->getModule()->getDataLayout();
6766 if (!R
.canMapToVector(IVI
->getType(), DL
))
6769 SmallVector
<Value
*, 16> BuildVectorOpds
;
6770 if (!findBuildAggregate(IVI
, BuildVectorOpds
))
6773 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI
<< "\n");
6774 // Aggregate value is unlikely to be processed in vector register, we need to
6775 // extract scalars into scalar registers, so NeedExtraction is set true.
6776 return tryToVectorizeList(BuildVectorOpds
, R
);
6779 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst
*IEI
,
6780 BasicBlock
*BB
, BoUpSLP
&R
) {
6782 SmallVector
<Value
*, 16> BuildVectorOpds
;
6783 if (!findBuildVector(IEI
, TTI
, BuildVectorOpds
, UserCost
) ||
6784 (llvm::all_of(BuildVectorOpds
,
6785 [](Value
*V
) { return isa
<ExtractElementInst
>(V
); }) &&
6786 isShuffle(BuildVectorOpds
)))
6789 // Vectorize starting with the build vector operands ignoring the BuildVector
6790 // instructions for the purpose of scheduling and user extraction.
6791 return tryToVectorizeList(BuildVectorOpds
, R
, UserCost
);
6794 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst
*CI
, BasicBlock
*BB
,
6796 if (tryToVectorizePair(CI
->getOperand(0), CI
->getOperand(1), R
))
6799 bool OpsChanged
= false;
6800 for (int Idx
= 0; Idx
< 2; ++Idx
) {
6802 vectorizeRootInstruction(nullptr, CI
->getOperand(Idx
), BB
, R
, TTI
);
6807 bool SLPVectorizerPass::vectorizeSimpleInstructions(
6808 SmallVectorImpl
<WeakVH
> &Instructions
, BasicBlock
*BB
, BoUpSLP
&R
) {
6809 bool OpsChanged
= false;
6810 for (auto &VH
: reverse(Instructions
)) {
6811 auto *I
= dyn_cast_or_null
<Instruction
>(VH
);
6814 if (auto *LastInsertValue
= dyn_cast
<InsertValueInst
>(I
))
6815 OpsChanged
|= vectorizeInsertValueInst(LastInsertValue
, BB
, R
);
6816 else if (auto *LastInsertElem
= dyn_cast
<InsertElementInst
>(I
))
6817 OpsChanged
|= vectorizeInsertElementInst(LastInsertElem
, BB
, R
);
6818 else if (auto *CI
= dyn_cast
<CmpInst
>(I
))
6819 OpsChanged
|= vectorizeCmpInst(CI
, BB
, R
);
6821 Instructions
.clear();
6825 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock
*BB
, BoUpSLP
&R
) {
6826 bool Changed
= false;
6827 SmallVector
<Value
*, 4> Incoming
;
6828 SmallPtrSet
<Value
*, 16> VisitedInstrs
;
6830 bool HaveVectorizedPhiNodes
= true;
6831 while (HaveVectorizedPhiNodes
) {
6832 HaveVectorizedPhiNodes
= false;
6834 // Collect the incoming values from the PHIs.
6836 for (Instruction
&I
: *BB
) {
6837 PHINode
*P
= dyn_cast
<PHINode
>(&I
);
6841 if (!VisitedInstrs
.count(P
))
6842 Incoming
.push_back(P
);
6846 llvm::stable_sort(Incoming
, PhiTypeSorterFunc
);
6848 // Try to vectorize elements base on their type.
6849 for (SmallVector
<Value
*, 4>::iterator IncIt
= Incoming
.begin(),
6853 // Look for the next elements with the same type.
6854 SmallVector
<Value
*, 4>::iterator SameTypeIt
= IncIt
;
6855 while (SameTypeIt
!= E
&&
6856 (*SameTypeIt
)->getType() == (*IncIt
)->getType()) {
6857 VisitedInstrs
.insert(*SameTypeIt
);
6861 // Try to vectorize them.
6862 unsigned NumElts
= (SameTypeIt
- IncIt
);
6863 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
6864 << NumElts
<< ")\n");
6865 // The order in which the phi nodes appear in the program does not matter.
6866 // So allow tryToVectorizeList to reorder them if it is beneficial. This
6867 // is done when there are exactly two elements since tryToVectorizeList
6868 // asserts that there are only two values when AllowReorder is true.
6869 bool AllowReorder
= NumElts
== 2;
6870 if (NumElts
> 1 && tryToVectorizeList(makeArrayRef(IncIt
, NumElts
), R
,
6871 /*UserCost=*/0, AllowReorder
)) {
6872 // Success start over because instructions might have been changed.
6873 HaveVectorizedPhiNodes
= true;
6878 // Start over at the next instruction of a different type (or the end).
6883 VisitedInstrs
.clear();
6885 SmallVector
<WeakVH
, 8> PostProcessInstructions
;
6886 SmallDenseSet
<Instruction
*, 4> KeyNodes
;
6887 for (BasicBlock::iterator it
= BB
->begin(), e
= BB
->end(); it
!= e
; ++it
) {
6888 // We may go through BB multiple times so skip the one we have checked.
6889 if (!VisitedInstrs
.insert(&*it
).second
) {
6890 if (it
->use_empty() && KeyNodes
.count(&*it
) > 0 &&
6891 vectorizeSimpleInstructions(PostProcessInstructions
, BB
, R
)) {
6892 // We would like to start over since some instructions are deleted
6893 // and the iterator may become invalid value.
6901 if (isa
<DbgInfoIntrinsic
>(it
))
6904 // Try to vectorize reductions that use PHINodes.
6905 if (PHINode
*P
= dyn_cast
<PHINode
>(it
)) {
6906 // Check that the PHI is a reduction PHI.
6907 if (P
->getNumIncomingValues() != 2)
6910 // Try to match and vectorize a horizontal reduction.
6911 if (vectorizeRootInstruction(P
, getReductionValue(DT
, P
, BB
, LI
), BB
, R
,
6921 // Ran into an instruction without users, like terminator, or function call
6922 // with ignored return value, store. Ignore unused instructions (basing on
6923 // instruction type, except for CallInst and InvokeInst).
6924 if (it
->use_empty() && (it
->getType()->isVoidTy() || isa
<CallInst
>(it
) ||
6925 isa
<InvokeInst
>(it
))) {
6926 KeyNodes
.insert(&*it
);
6927 bool OpsChanged
= false;
6928 if (ShouldStartVectorizeHorAtStore
|| !isa
<StoreInst
>(it
)) {
6929 for (auto *V
: it
->operand_values()) {
6930 // Try to match and vectorize a horizontal reduction.
6931 OpsChanged
|= vectorizeRootInstruction(nullptr, V
, BB
, R
, TTI
);
6934 // Start vectorization of post-process list of instructions from the
6935 // top-tree instructions to try to vectorize as many instructions as
6937 OpsChanged
|= vectorizeSimpleInstructions(PostProcessInstructions
, BB
, R
);
6939 // We would like to start over since some instructions are deleted
6940 // and the iterator may become invalid value.
6948 if (isa
<InsertElementInst
>(it
) || isa
<CmpInst
>(it
) ||
6949 isa
<InsertValueInst
>(it
))
6950 PostProcessInstructions
.push_back(&*it
);
6956 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock
*BB
, BoUpSLP
&R
) {
6957 auto Changed
= false;
6958 for (auto &Entry
: GEPs
) {
6959 // If the getelementptr list has fewer than two elements, there's nothing
6961 if (Entry
.second
.size() < 2)
6964 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
6965 << Entry
.second
.size() << ".\n");
6967 // We process the getelementptr list in chunks of 16 (like we do for
6968 // stores) to minimize compile-time.
6969 for (unsigned BI
= 0, BE
= Entry
.second
.size(); BI
< BE
; BI
+= 16) {
6970 auto Len
= std::min
<unsigned>(BE
- BI
, 16);
6971 auto GEPList
= makeArrayRef(&Entry
.second
[BI
], Len
);
6973 // Initialize a set a candidate getelementptrs. Note that we use a
6974 // SetVector here to preserve program order. If the index computations
6975 // are vectorizable and begin with loads, we want to minimize the chance
6976 // of having to reorder them later.
6977 SetVector
<Value
*> Candidates(GEPList
.begin(), GEPList
.end());
6979 // Some of the candidates may have already been vectorized after we
6980 // initially collected them. If so, the WeakTrackingVHs will have
6982 // values, so remove them from the set of candidates.
6983 Candidates
.remove(nullptr);
6985 // Remove from the set of candidates all pairs of getelementptrs with
6986 // constant differences. Such getelementptrs are likely not good
6987 // candidates for vectorization in a bottom-up phase since one can be
6988 // computed from the other. We also ensure all candidate getelementptr
6989 // indices are unique.
6990 for (int I
= 0, E
= GEPList
.size(); I
< E
&& Candidates
.size() > 1; ++I
) {
6991 auto *GEPI
= cast
<GetElementPtrInst
>(GEPList
[I
]);
6992 if (!Candidates
.count(GEPI
))
6994 auto *SCEVI
= SE
->getSCEV(GEPList
[I
]);
6995 for (int J
= I
+ 1; J
< E
&& Candidates
.size() > 1; ++J
) {
6996 auto *GEPJ
= cast
<GetElementPtrInst
>(GEPList
[J
]);
6997 auto *SCEVJ
= SE
->getSCEV(GEPList
[J
]);
6998 if (isa
<SCEVConstant
>(SE
->getMinusSCEV(SCEVI
, SCEVJ
))) {
6999 Candidates
.remove(GEPList
[I
]);
7000 Candidates
.remove(GEPList
[J
]);
7001 } else if (GEPI
->idx_begin()->get() == GEPJ
->idx_begin()->get()) {
7002 Candidates
.remove(GEPList
[J
]);
7007 // We break out of the above computation as soon as we know there are
7008 // fewer than two candidates remaining.
7009 if (Candidates
.size() < 2)
7012 // Add the single, non-constant index of each candidate to the bundle. We
7013 // ensured the indices met these constraints when we originally collected
7014 // the getelementptrs.
7015 SmallVector
<Value
*, 16> Bundle(Candidates
.size());
7016 auto BundleIndex
= 0u;
7017 for (auto *V
: Candidates
) {
7018 auto *GEP
= cast
<GetElementPtrInst
>(V
);
7019 auto *GEPIdx
= GEP
->idx_begin()->get();
7020 assert(GEP
->getNumIndices() == 1 || !isa
<Constant
>(GEPIdx
));
7021 Bundle
[BundleIndex
++] = GEPIdx
;
7024 // Try and vectorize the indices. We are currently only interested in
7025 // gather-like cases of the form:
7027 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7029 // where the loads of "a", the loads of "b", and the subtractions can be
7030 // performed in parallel. It's likely that detecting this pattern in a
7031 // bottom-up phase will be simpler and less costly than building a
7032 // full-blown top-down phase beginning at the consecutive loads.
7033 Changed
|= tryToVectorizeList(Bundle
, R
);
7039 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP
&R
) {
7040 bool Changed
= false;
7041 // Attempt to sort and vectorize each of the store-groups.
7042 for (StoreListMap::iterator it
= Stores
.begin(), e
= Stores
.end(); it
!= e
;
7044 if (it
->second
.size() < 2)
7047 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7048 << it
->second
.size() << ".\n");
7050 // Process the stores in chunks of 16.
7051 // TODO: The limit of 16 inhibits greater vectorization factors.
7052 // For example, AVX2 supports v32i8. Increasing this limit, however,
7053 // may cause a significant compile-time increase.
7054 for (unsigned CI
= 0, CE
= it
->second
.size(); CI
< CE
; CI
+= 16) {
7055 unsigned Len
= std::min
<unsigned>(CE
- CI
, 16);
7056 Changed
|= vectorizeStores(makeArrayRef(&it
->second
[CI
], Len
), R
);
7062 char SLPVectorizer::ID
= 0;
7064 static const char lv_name
[] = "SLP Vectorizer";
7066 INITIALIZE_PASS_BEGIN(SLPVectorizer
, SV_NAME
, lv_name
, false, false)
7067 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
7068 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
7069 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker
)
7070 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass
)
7071 INITIALIZE_PASS_DEPENDENCY(LoopSimplify
)
7072 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass
)
7073 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass
)
7074 INITIALIZE_PASS_END(SLPVectorizer
, SV_NAME
, lv_name
, false, false)
7076 Pass
*llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }