Improve Register Setup
[llvm-core.git] / lib / Transforms / Vectorize / SLPVectorizer.cpp
blob79b575b78cdd6525a7598dc9d94c92a1bb20c70d
1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
11 // stores that can be put together into vector-stores. Next, it attempts to
12 // construct vectorizable tree using the use-def chains. If a profitable tree
13 // was found, the SLP vectorizer performs vectorization on the tree.
15 // The pass is inspired by the work described in the paper:
16 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/DenseSet.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/ADT/None.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/PostOrderIterator.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/iterator.h"
35 #include "llvm/ADT/iterator_range.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/LoopAccessAnalysis.h"
41 #include "llvm/Analysis/LoopInfo.h"
42 #include "llvm/Analysis/MemoryLocation.h"
43 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
44 #include "llvm/Analysis/ScalarEvolution.h"
45 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
46 #include "llvm/Analysis/TargetLibraryInfo.h"
47 #include "llvm/Analysis/TargetTransformInfo.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/Analysis/VectorUtils.h"
50 #include "llvm/IR/Attributes.h"
51 #include "llvm/IR/BasicBlock.h"
52 #include "llvm/IR/Constant.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugLoc.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/NoFolder.h"
67 #include "llvm/IR/Operator.h"
68 #include "llvm/IR/PassManager.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/KnownBits.h"
85 #include "llvm/Support/MathExtras.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Transforms/Utils/LoopUtils.h"
88 #include "llvm/Transforms/Vectorize.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstdint>
92 #include <iterator>
93 #include <memory>
94 #include <set>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 #include <vector>
100 using namespace llvm;
101 using namespace llvm::PatternMatch;
102 using namespace slpvectorizer;
104 #define SV_NAME "slp-vectorizer"
105 #define DEBUG_TYPE "SLP"
107 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
109 static cl::opt<int>
110 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
111 cl::desc("Only vectorize if you gain more than this "
112 "number "));
114 static cl::opt<bool>
115 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
116 cl::desc("Attempt to vectorize horizontal reductions"));
118 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
119 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
120 cl::desc(
121 "Attempt to vectorize horizontal reductions feeding into a store"));
123 static cl::opt<int>
124 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
125 cl::desc("Attempt to vectorize for this register size in bits"));
127 /// Limits the size of scheduling regions in a block.
128 /// It avoid long compile times for _very_ large blocks where vector
129 /// instructions are spread over a wide range.
130 /// This limit is way higher than needed by real-world functions.
131 static cl::opt<int>
132 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
133 cl::desc("Limit the size of the SLP scheduling region per block"));
135 static cl::opt<int> MinVectorRegSizeOption(
136 "slp-min-reg-size", cl::init(128), cl::Hidden,
137 cl::desc("Attempt to vectorize for this register size in bits"));
139 static cl::opt<unsigned> RecursionMaxDepth(
140 "slp-recursion-max-depth", cl::init(12), cl::Hidden,
141 cl::desc("Limit the recursion depth when building a vectorizable tree"));
143 static cl::opt<unsigned> MinTreeSize(
144 "slp-min-tree-size", cl::init(3), cl::Hidden,
145 cl::desc("Only vectorize small trees if they are fully vectorizable"));
147 static cl::opt<bool>
148 ViewSLPTree("view-slp-tree", cl::Hidden,
149 cl::desc("Display the SLP trees with Graphviz"));
151 // Limit the number of alias checks. The limit is chosen so that
152 // it has no negative effect on the llvm benchmarks.
153 static const unsigned AliasedCheckLimit = 10;
155 // Another limit for the alias checks: The maximum distance between load/store
156 // instructions where alias checks are done.
157 // This limit is useful for very large basic blocks.
158 static const unsigned MaxMemDepDistance = 160;
160 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
161 /// regions to be handled.
162 static const int MinScheduleRegionSize = 16;
164 /// Predicate for the element types that the SLP vectorizer supports.
166 /// The most important thing to filter here are types which are invalid in LLVM
167 /// vectors. We also filter target specific types which have absolutely no
168 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
169 /// avoids spending time checking the cost model and realizing that they will
170 /// be inevitably scalarized.
171 static bool isValidElementType(Type *Ty) {
172 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
173 !Ty->isPPC_FP128Ty();
176 /// \returns true if all of the instructions in \p VL are in the same block or
177 /// false otherwise.
178 static bool allSameBlock(ArrayRef<Value *> VL) {
179 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
180 if (!I0)
181 return false;
182 BasicBlock *BB = I0->getParent();
183 for (int i = 1, e = VL.size(); i < e; i++) {
184 Instruction *I = dyn_cast<Instruction>(VL[i]);
185 if (!I)
186 return false;
188 if (BB != I->getParent())
189 return false;
191 return true;
194 /// \returns True if all of the values in \p VL are constants.
195 static bool allConstant(ArrayRef<Value *> VL) {
196 for (Value *i : VL)
197 if (!isa<Constant>(i))
198 return false;
199 return true;
202 /// \returns True if all of the values in \p VL are identical.
203 static bool isSplat(ArrayRef<Value *> VL) {
204 for (unsigned i = 1, e = VL.size(); i < e; ++i)
205 if (VL[i] != VL[0])
206 return false;
207 return true;
210 /// Checks if the vector of instructions can be represented as a shuffle, like:
211 /// %x0 = extractelement <4 x i8> %x, i32 0
212 /// %x3 = extractelement <4 x i8> %x, i32 3
213 /// %y1 = extractelement <4 x i8> %y, i32 1
214 /// %y2 = extractelement <4 x i8> %y, i32 2
215 /// %x0x0 = mul i8 %x0, %x0
216 /// %x3x3 = mul i8 %x3, %x3
217 /// %y1y1 = mul i8 %y1, %y1
218 /// %y2y2 = mul i8 %y2, %y2
219 /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
220 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
221 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
222 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
223 /// ret <4 x i8> %ins4
224 /// can be transformed into:
225 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
226 /// i32 6>
227 /// %2 = mul <4 x i8> %1, %1
228 /// ret <4 x i8> %2
229 /// We convert this initially to something like:
230 /// %x0 = extractelement <4 x i8> %x, i32 0
231 /// %x3 = extractelement <4 x i8> %x, i32 3
232 /// %y1 = extractelement <4 x i8> %y, i32 1
233 /// %y2 = extractelement <4 x i8> %y, i32 2
234 /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
235 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
236 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
237 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
238 /// %5 = mul <4 x i8> %4, %4
239 /// %6 = extractelement <4 x i8> %5, i32 0
240 /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
241 /// %7 = extractelement <4 x i8> %5, i32 1
242 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
243 /// %8 = extractelement <4 x i8> %5, i32 2
244 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
245 /// %9 = extractelement <4 x i8> %5, i32 3
246 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
247 /// ret <4 x i8> %ins4
248 /// InstCombiner transforms this into a shuffle and vector mul
249 /// TODO: Can we split off and reuse the shuffle mask detection from
250 /// TargetTransformInfo::getInstructionThroughput?
251 static Optional<TargetTransformInfo::ShuffleKind>
252 isShuffle(ArrayRef<Value *> VL) {
253 auto *EI0 = cast<ExtractElementInst>(VL[0]);
254 unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
255 Value *Vec1 = nullptr;
256 Value *Vec2 = nullptr;
257 enum ShuffleMode { Unknown, Select, Permute };
258 ShuffleMode CommonShuffleMode = Unknown;
259 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
260 auto *EI = cast<ExtractElementInst>(VL[I]);
261 auto *Vec = EI->getVectorOperand();
262 // All vector operands must have the same number of vector elements.
263 if (Vec->getType()->getVectorNumElements() != Size)
264 return None;
265 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
266 if (!Idx)
267 return None;
268 // Undefined behavior if Idx is negative or >= Size.
269 if (Idx->getValue().uge(Size))
270 continue;
271 unsigned IntIdx = Idx->getValue().getZExtValue();
272 // We can extractelement from undef vector.
273 if (isa<UndefValue>(Vec))
274 continue;
275 // For correct shuffling we have to have at most 2 different vector operands
276 // in all extractelement instructions.
277 if (!Vec1 || Vec1 == Vec)
278 Vec1 = Vec;
279 else if (!Vec2 || Vec2 == Vec)
280 Vec2 = Vec;
281 else
282 return None;
283 if (CommonShuffleMode == Permute)
284 continue;
285 // If the extract index is not the same as the operation number, it is a
286 // permutation.
287 if (IntIdx != I) {
288 CommonShuffleMode = Permute;
289 continue;
291 CommonShuffleMode = Select;
293 // If we're not crossing lanes in different vectors, consider it as blending.
294 if (CommonShuffleMode == Select && Vec2)
295 return TargetTransformInfo::SK_Select;
296 // If Vec2 was never used, we have a permutation of a single vector, otherwise
297 // we have permutation of 2 vectors.
298 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
299 : TargetTransformInfo::SK_PermuteSingleSrc;
302 namespace {
304 /// Main data required for vectorization of instructions.
305 struct InstructionsState {
306 /// The very first instruction in the list with the main opcode.
307 Value *OpValue = nullptr;
309 /// The main/alternate instruction.
310 Instruction *MainOp = nullptr;
311 Instruction *AltOp = nullptr;
313 /// The main/alternate opcodes for the list of instructions.
314 unsigned getOpcode() const {
315 return MainOp ? MainOp->getOpcode() : 0;
318 unsigned getAltOpcode() const {
319 return AltOp ? AltOp->getOpcode() : 0;
322 /// Some of the instructions in the list have alternate opcodes.
323 bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
325 bool isOpcodeOrAlt(Instruction *I) const {
326 unsigned CheckedOpcode = I->getOpcode();
327 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
330 InstructionsState() = delete;
331 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
332 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
335 } // end anonymous namespace
337 /// Chooses the correct key for scheduling data. If \p Op has the same (or
338 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
339 /// OpValue.
340 static Value *isOneOf(const InstructionsState &S, Value *Op) {
341 auto *I = dyn_cast<Instruction>(Op);
342 if (I && S.isOpcodeOrAlt(I))
343 return Op;
344 return S.OpValue;
347 /// \returns analysis of the Instructions in \p VL described in
348 /// InstructionsState, the Opcode that we suppose the whole list
349 /// could be vectorized even if its structure is diverse.
350 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
351 unsigned BaseIndex = 0) {
352 // Make sure these are all Instructions.
353 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
354 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
356 bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
357 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
358 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
359 unsigned AltOpcode = Opcode;
360 unsigned AltIndex = BaseIndex;
362 // Check for one alternate opcode from another BinaryOperator.
363 // TODO - generalize to support all operators (types, calls etc.).
364 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
365 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
366 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
367 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
368 continue;
369 if (Opcode == AltOpcode) {
370 AltOpcode = InstOpcode;
371 AltIndex = Cnt;
372 continue;
374 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
375 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
376 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
377 if (Ty0 == Ty1) {
378 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
379 continue;
380 if (Opcode == AltOpcode) {
381 AltOpcode = InstOpcode;
382 AltIndex = Cnt;
383 continue;
386 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
387 continue;
388 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
391 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
392 cast<Instruction>(VL[AltIndex]));
395 /// \returns true if all of the values in \p VL have the same type or false
396 /// otherwise.
397 static bool allSameType(ArrayRef<Value *> VL) {
398 Type *Ty = VL[0]->getType();
399 for (int i = 1, e = VL.size(); i < e; i++)
400 if (VL[i]->getType() != Ty)
401 return false;
403 return true;
406 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
407 static Optional<unsigned> getExtractIndex(Instruction *E) {
408 unsigned Opcode = E->getOpcode();
409 assert((Opcode == Instruction::ExtractElement ||
410 Opcode == Instruction::ExtractValue) &&
411 "Expected extractelement or extractvalue instruction.");
412 if (Opcode == Instruction::ExtractElement) {
413 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
414 if (!CI)
415 return None;
416 return CI->getZExtValue();
418 ExtractValueInst *EI = cast<ExtractValueInst>(E);
419 if (EI->getNumIndices() != 1)
420 return None;
421 return *EI->idx_begin();
424 /// \returns True if in-tree use also needs extract. This refers to
425 /// possible scalar operand in vectorized instruction.
426 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
427 TargetLibraryInfo *TLI) {
428 unsigned Opcode = UserInst->getOpcode();
429 switch (Opcode) {
430 case Instruction::Load: {
431 LoadInst *LI = cast<LoadInst>(UserInst);
432 return (LI->getPointerOperand() == Scalar);
434 case Instruction::Store: {
435 StoreInst *SI = cast<StoreInst>(UserInst);
436 return (SI->getPointerOperand() == Scalar);
438 case Instruction::Call: {
439 CallInst *CI = cast<CallInst>(UserInst);
440 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
441 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
442 return (CI->getArgOperand(1) == Scalar);
444 LLVM_FALLTHROUGH;
446 default:
447 return false;
451 /// \returns the AA location that is being access by the instruction.
452 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
453 if (StoreInst *SI = dyn_cast<StoreInst>(I))
454 return MemoryLocation::get(SI);
455 if (LoadInst *LI = dyn_cast<LoadInst>(I))
456 return MemoryLocation::get(LI);
457 return MemoryLocation();
460 /// \returns True if the instruction is not a volatile or atomic load/store.
461 static bool isSimple(Instruction *I) {
462 if (LoadInst *LI = dyn_cast<LoadInst>(I))
463 return LI->isSimple();
464 if (StoreInst *SI = dyn_cast<StoreInst>(I))
465 return SI->isSimple();
466 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
467 return !MI->isVolatile();
468 return true;
471 namespace llvm {
473 namespace slpvectorizer {
475 /// Bottom Up SLP Vectorizer.
476 class BoUpSLP {
477 public:
478 using ValueList = SmallVector<Value *, 8>;
479 using InstrList = SmallVector<Instruction *, 16>;
480 using ValueSet = SmallPtrSet<Value *, 16>;
481 using StoreList = SmallVector<StoreInst *, 8>;
482 using ExtraValueToDebugLocsMap =
483 MapVector<Value *, SmallVector<Instruction *, 2>>;
485 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
486 TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
487 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
488 const DataLayout *DL, OptimizationRemarkEmitter *ORE)
489 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
490 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
491 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
492 // Use the vector register size specified by the target unless overridden
493 // by a command-line option.
494 // TODO: It would be better to limit the vectorization factor based on
495 // data type rather than just register size. For example, x86 AVX has
496 // 256-bit registers, but it does not support integer operations
497 // at that width (that requires AVX2).
498 if (MaxVectorRegSizeOption.getNumOccurrences())
499 MaxVecRegSize = MaxVectorRegSizeOption;
500 else
501 MaxVecRegSize = TTI->getRegisterBitWidth(true);
503 if (MinVectorRegSizeOption.getNumOccurrences())
504 MinVecRegSize = MinVectorRegSizeOption;
505 else
506 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
509 /// Vectorize the tree that starts with the elements in \p VL.
510 /// Returns the vectorized root.
511 Value *vectorizeTree();
513 /// Vectorize the tree but with the list of externally used values \p
514 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
515 /// generated extractvalue instructions.
516 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
518 /// \returns the cost incurred by unwanted spills and fills, caused by
519 /// holding live values over call sites.
520 int getSpillCost();
522 /// \returns the vectorization cost of the subtree that starts at \p VL.
523 /// A negative number means that this is profitable.
524 int getTreeCost();
526 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
527 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
528 void buildTree(ArrayRef<Value *> Roots,
529 ArrayRef<Value *> UserIgnoreLst = None);
531 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
532 /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
533 /// into account (anf updating it, if required) list of externally used
534 /// values stored in \p ExternallyUsedValues.
535 void buildTree(ArrayRef<Value *> Roots,
536 ExtraValueToDebugLocsMap &ExternallyUsedValues,
537 ArrayRef<Value *> UserIgnoreLst = None);
539 /// Clear the internal data structures that are created by 'buildTree'.
540 void deleteTree() {
541 VectorizableTree.clear();
542 ScalarToTreeEntry.clear();
543 MustGather.clear();
544 ExternalUses.clear();
545 NumOpsWantToKeepOrder.clear();
546 NumOpsWantToKeepOriginalOrder = 0;
547 for (auto &Iter : BlocksSchedules) {
548 BlockScheduling *BS = Iter.second.get();
549 BS->clear();
551 MinBWs.clear();
554 unsigned getTreeSize() const { return VectorizableTree.size(); }
556 /// Perform LICM and CSE on the newly generated gather sequences.
557 void optimizeGatherSequence();
559 /// \returns The best order of instructions for vectorization.
560 Optional<ArrayRef<unsigned>> bestOrder() const {
561 auto I = std::max_element(
562 NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
563 [](const decltype(NumOpsWantToKeepOrder)::value_type &D1,
564 const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
565 return D1.second < D2.second;
567 if (I == NumOpsWantToKeepOrder.end() ||
568 I->getSecond() <= NumOpsWantToKeepOriginalOrder)
569 return None;
571 return makeArrayRef(I->getFirst());
574 /// \return The vector element size in bits to use when vectorizing the
575 /// expression tree ending at \p V. If V is a store, the size is the width of
576 /// the stored value. Otherwise, the size is the width of the largest loaded
577 /// value reaching V. This method is used by the vectorizer to calculate
578 /// vectorization factors.
579 unsigned getVectorElementSize(Value *V);
581 /// Compute the minimum type sizes required to represent the entries in a
582 /// vectorizable tree.
583 void computeMinimumValueSizes();
585 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
586 unsigned getMaxVecRegSize() const {
587 return MaxVecRegSize;
590 // \returns minimum vector register size as set by cl::opt.
591 unsigned getMinVecRegSize() const {
592 return MinVecRegSize;
595 /// Check if ArrayType or StructType is isomorphic to some VectorType.
597 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
598 unsigned canMapToVector(Type *T, const DataLayout &DL) const;
600 /// \returns True if the VectorizableTree is both tiny and not fully
601 /// vectorizable. We do not vectorize such trees.
602 bool isTreeTinyAndNotFullyVectorizable();
604 OptimizationRemarkEmitter *getORE() { return ORE; }
606 private:
607 struct TreeEntry;
609 /// Checks if all users of \p I are the part of the vectorization tree.
610 bool areAllUsersVectorized(Instruction *I) const;
612 /// \returns the cost of the vectorizable entry.
613 int getEntryCost(TreeEntry *E);
615 /// This is the recursive part of buildTree.
616 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, int);
618 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
619 /// be vectorized to use the original vector (or aggregate "bitcast" to a
620 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
621 /// returns false, setting \p CurrentOrder to either an empty vector or a
622 /// non-identity permutation that allows to reuse extract instructions.
623 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
624 SmallVectorImpl<unsigned> &CurrentOrder) const;
626 /// Vectorize a single entry in the tree.
627 Value *vectorizeTree(TreeEntry *E);
629 /// Vectorize a single entry in the tree, starting in \p VL.
630 Value *vectorizeTree(ArrayRef<Value *> VL);
632 /// \returns the scalarization cost for this type. Scalarization in this
633 /// context means the creation of vectors from a group of scalars.
634 int getGatherCost(Type *Ty, const DenseSet<unsigned> &ShuffledIndices);
636 /// \returns the scalarization cost for this list of values. Assuming that
637 /// this subtree gets vectorized, we may need to extract the values from the
638 /// roots. This method calculates the cost of extracting the values.
639 int getGatherCost(ArrayRef<Value *> VL);
641 /// Set the Builder insert point to one after the last instruction in
642 /// the bundle
643 void setInsertPointAfterBundle(ArrayRef<Value *> VL,
644 const InstructionsState &S);
646 /// \returns a vector from a collection of scalars in \p VL.
647 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
649 /// \returns whether the VectorizableTree is fully vectorizable and will
650 /// be beneficial even the tree height is tiny.
651 bool isFullyVectorizableTinyTree();
653 /// \reorder commutative operands in alt shuffle if they result in
654 /// vectorized code.
655 void reorderAltShuffleOperands(const InstructionsState &S,
656 ArrayRef<Value *> VL,
657 SmallVectorImpl<Value *> &Left,
658 SmallVectorImpl<Value *> &Right);
660 /// \reorder commutative operands to get better probability of
661 /// generating vectorized code.
662 void reorderInputsAccordingToOpcode(unsigned Opcode, ArrayRef<Value *> VL,
663 SmallVectorImpl<Value *> &Left,
664 SmallVectorImpl<Value *> &Right);
665 struct TreeEntry {
666 TreeEntry(std::vector<TreeEntry> &Container) : Container(Container) {}
668 /// \returns true if the scalars in VL are equal to this entry.
669 bool isSame(ArrayRef<Value *> VL) const {
670 if (VL.size() == Scalars.size())
671 return std::equal(VL.begin(), VL.end(), Scalars.begin());
672 return VL.size() == ReuseShuffleIndices.size() &&
673 std::equal(
674 VL.begin(), VL.end(), ReuseShuffleIndices.begin(),
675 [this](Value *V, unsigned Idx) { return V == Scalars[Idx]; });
678 /// A vector of scalars.
679 ValueList Scalars;
681 /// The Scalars are vectorized into this value. It is initialized to Null.
682 Value *VectorizedValue = nullptr;
684 /// Do we need to gather this sequence ?
685 bool NeedToGather = false;
687 /// Does this sequence require some shuffling?
688 SmallVector<unsigned, 4> ReuseShuffleIndices;
690 /// Does this entry require reordering?
691 ArrayRef<unsigned> ReorderIndices;
693 /// Points back to the VectorizableTree.
695 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
696 /// to be a pointer and needs to be able to initialize the child iterator.
697 /// Thus we need a reference back to the container to translate the indices
698 /// to entries.
699 std::vector<TreeEntry> &Container;
701 /// The TreeEntry index containing the user of this entry. We can actually
702 /// have multiple users so the data structure is not truly a tree.
703 SmallVector<int, 1> UserTreeIndices;
706 /// Create a new VectorizableTree entry.
707 void newTreeEntry(ArrayRef<Value *> VL, bool Vectorized, int &UserTreeIdx,
708 ArrayRef<unsigned> ReuseShuffleIndices = None,
709 ArrayRef<unsigned> ReorderIndices = None) {
710 VectorizableTree.emplace_back(VectorizableTree);
711 int idx = VectorizableTree.size() - 1;
712 TreeEntry *Last = &VectorizableTree[idx];
713 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
714 Last->NeedToGather = !Vectorized;
715 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
716 ReuseShuffleIndices.end());
717 Last->ReorderIndices = ReorderIndices;
718 if (Vectorized) {
719 for (int i = 0, e = VL.size(); i != e; ++i) {
720 assert(!getTreeEntry(VL[i]) && "Scalar already in tree!");
721 ScalarToTreeEntry[VL[i]] = idx;
723 } else {
724 MustGather.insert(VL.begin(), VL.end());
727 if (UserTreeIdx >= 0)
728 Last->UserTreeIndices.push_back(UserTreeIdx);
729 UserTreeIdx = idx;
732 /// -- Vectorization State --
733 /// Holds all of the tree entries.
734 std::vector<TreeEntry> VectorizableTree;
736 TreeEntry *getTreeEntry(Value *V) {
737 auto I = ScalarToTreeEntry.find(V);
738 if (I != ScalarToTreeEntry.end())
739 return &VectorizableTree[I->second];
740 return nullptr;
743 /// Maps a specific scalar to its tree entry.
744 SmallDenseMap<Value*, int> ScalarToTreeEntry;
746 /// A list of scalars that we found that we need to keep as scalars.
747 ValueSet MustGather;
749 /// This POD struct describes one external user in the vectorized tree.
750 struct ExternalUser {
751 ExternalUser(Value *S, llvm::User *U, int L)
752 : Scalar(S), User(U), Lane(L) {}
754 // Which scalar in our function.
755 Value *Scalar;
757 // Which user that uses the scalar.
758 llvm::User *User;
760 // Which lane does the scalar belong to.
761 int Lane;
763 using UserList = SmallVector<ExternalUser, 16>;
765 /// Checks if two instructions may access the same memory.
767 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
768 /// is invariant in the calling loop.
769 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
770 Instruction *Inst2) {
771 // First check if the result is already in the cache.
772 AliasCacheKey key = std::make_pair(Inst1, Inst2);
773 Optional<bool> &result = AliasCache[key];
774 if (result.hasValue()) {
775 return result.getValue();
777 MemoryLocation Loc2 = getLocation(Inst2, AA);
778 bool aliased = true;
779 if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
780 // Do the alias check.
781 aliased = AA->alias(Loc1, Loc2);
783 // Store the result in the cache.
784 result = aliased;
785 return aliased;
788 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
790 /// Cache for alias results.
791 /// TODO: consider moving this to the AliasAnalysis itself.
792 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
794 /// Removes an instruction from its block and eventually deletes it.
795 /// It's like Instruction::eraseFromParent() except that the actual deletion
796 /// is delayed until BoUpSLP is destructed.
797 /// This is required to ensure that there are no incorrect collisions in the
798 /// AliasCache, which can happen if a new instruction is allocated at the
799 /// same address as a previously deleted instruction.
800 void eraseInstruction(Instruction *I) {
801 I->removeFromParent();
802 I->dropAllReferences();
803 DeletedInstructions.emplace_back(I);
806 /// Temporary store for deleted instructions. Instructions will be deleted
807 /// eventually when the BoUpSLP is destructed.
808 SmallVector<unique_value, 8> DeletedInstructions;
810 /// A list of values that need to extracted out of the tree.
811 /// This list holds pairs of (Internal Scalar : External User). External User
812 /// can be nullptr, it means that this Internal Scalar will be used later,
813 /// after vectorization.
814 UserList ExternalUses;
816 /// Values used only by @llvm.assume calls.
817 SmallPtrSet<const Value *, 32> EphValues;
819 /// Holds all of the instructions that we gathered.
820 SetVector<Instruction *> GatherSeq;
822 /// A list of blocks that we are going to CSE.
823 SetVector<BasicBlock *> CSEBlocks;
825 /// Contains all scheduling relevant data for an instruction.
826 /// A ScheduleData either represents a single instruction or a member of an
827 /// instruction bundle (= a group of instructions which is combined into a
828 /// vector instruction).
829 struct ScheduleData {
830 // The initial value for the dependency counters. It means that the
831 // dependencies are not calculated yet.
832 enum { InvalidDeps = -1 };
834 ScheduleData() = default;
836 void init(int BlockSchedulingRegionID, Value *OpVal) {
837 FirstInBundle = this;
838 NextInBundle = nullptr;
839 NextLoadStore = nullptr;
840 IsScheduled = false;
841 SchedulingRegionID = BlockSchedulingRegionID;
842 UnscheduledDepsInBundle = UnscheduledDeps;
843 clearDependencies();
844 OpValue = OpVal;
847 /// Returns true if the dependency information has been calculated.
848 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
850 /// Returns true for single instructions and for bundle representatives
851 /// (= the head of a bundle).
852 bool isSchedulingEntity() const { return FirstInBundle == this; }
854 /// Returns true if it represents an instruction bundle and not only a
855 /// single instruction.
856 bool isPartOfBundle() const {
857 return NextInBundle != nullptr || FirstInBundle != this;
860 /// Returns true if it is ready for scheduling, i.e. it has no more
861 /// unscheduled depending instructions/bundles.
862 bool isReady() const {
863 assert(isSchedulingEntity() &&
864 "can't consider non-scheduling entity for ready list");
865 return UnscheduledDepsInBundle == 0 && !IsScheduled;
868 /// Modifies the number of unscheduled dependencies, also updating it for
869 /// the whole bundle.
870 int incrementUnscheduledDeps(int Incr) {
871 UnscheduledDeps += Incr;
872 return FirstInBundle->UnscheduledDepsInBundle += Incr;
875 /// Sets the number of unscheduled dependencies to the number of
876 /// dependencies.
877 void resetUnscheduledDeps() {
878 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
881 /// Clears all dependency information.
882 void clearDependencies() {
883 Dependencies = InvalidDeps;
884 resetUnscheduledDeps();
885 MemoryDependencies.clear();
888 void dump(raw_ostream &os) const {
889 if (!isSchedulingEntity()) {
890 os << "/ " << *Inst;
891 } else if (NextInBundle) {
892 os << '[' << *Inst;
893 ScheduleData *SD = NextInBundle;
894 while (SD) {
895 os << ';' << *SD->Inst;
896 SD = SD->NextInBundle;
898 os << ']';
899 } else {
900 os << *Inst;
904 Instruction *Inst = nullptr;
906 /// Points to the head in an instruction bundle (and always to this for
907 /// single instructions).
908 ScheduleData *FirstInBundle = nullptr;
910 /// Single linked list of all instructions in a bundle. Null if it is a
911 /// single instruction.
912 ScheduleData *NextInBundle = nullptr;
914 /// Single linked list of all memory instructions (e.g. load, store, call)
915 /// in the block - until the end of the scheduling region.
916 ScheduleData *NextLoadStore = nullptr;
918 /// The dependent memory instructions.
919 /// This list is derived on demand in calculateDependencies().
920 SmallVector<ScheduleData *, 4> MemoryDependencies;
922 /// This ScheduleData is in the current scheduling region if this matches
923 /// the current SchedulingRegionID of BlockScheduling.
924 int SchedulingRegionID = 0;
926 /// Used for getting a "good" final ordering of instructions.
927 int SchedulingPriority = 0;
929 /// The number of dependencies. Constitutes of the number of users of the
930 /// instruction plus the number of dependent memory instructions (if any).
931 /// This value is calculated on demand.
932 /// If InvalidDeps, the number of dependencies is not calculated yet.
933 int Dependencies = InvalidDeps;
935 /// The number of dependencies minus the number of dependencies of scheduled
936 /// instructions. As soon as this is zero, the instruction/bundle gets ready
937 /// for scheduling.
938 /// Note that this is negative as long as Dependencies is not calculated.
939 int UnscheduledDeps = InvalidDeps;
941 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
942 /// single instructions.
943 int UnscheduledDepsInBundle = InvalidDeps;
945 /// True if this instruction is scheduled (or considered as scheduled in the
946 /// dry-run).
947 bool IsScheduled = false;
949 /// Opcode of the current instruction in the schedule data.
950 Value *OpValue = nullptr;
953 #ifndef NDEBUG
954 friend inline raw_ostream &operator<<(raw_ostream &os,
955 const BoUpSLP::ScheduleData &SD) {
956 SD.dump(os);
957 return os;
959 #endif
961 friend struct GraphTraits<BoUpSLP *>;
962 friend struct DOTGraphTraits<BoUpSLP *>;
964 /// Contains all scheduling data for a basic block.
965 struct BlockScheduling {
966 BlockScheduling(BasicBlock *BB)
967 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
969 void clear() {
970 ReadyInsts.clear();
971 ScheduleStart = nullptr;
972 ScheduleEnd = nullptr;
973 FirstLoadStoreInRegion = nullptr;
974 LastLoadStoreInRegion = nullptr;
976 // Reduce the maximum schedule region size by the size of the
977 // previous scheduling run.
978 ScheduleRegionSizeLimit -= ScheduleRegionSize;
979 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
980 ScheduleRegionSizeLimit = MinScheduleRegionSize;
981 ScheduleRegionSize = 0;
983 // Make a new scheduling region, i.e. all existing ScheduleData is not
984 // in the new region yet.
985 ++SchedulingRegionID;
988 ScheduleData *getScheduleData(Value *V) {
989 ScheduleData *SD = ScheduleDataMap[V];
990 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
991 return SD;
992 return nullptr;
995 ScheduleData *getScheduleData(Value *V, Value *Key) {
996 if (V == Key)
997 return getScheduleData(V);
998 auto I = ExtraScheduleDataMap.find(V);
999 if (I != ExtraScheduleDataMap.end()) {
1000 ScheduleData *SD = I->second[Key];
1001 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1002 return SD;
1004 return nullptr;
1007 bool isInSchedulingRegion(ScheduleData *SD) {
1008 return SD->SchedulingRegionID == SchedulingRegionID;
1011 /// Marks an instruction as scheduled and puts all dependent ready
1012 /// instructions into the ready-list.
1013 template <typename ReadyListType>
1014 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
1015 SD->IsScheduled = true;
1016 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
1018 ScheduleData *BundleMember = SD;
1019 while (BundleMember) {
1020 if (BundleMember->Inst != BundleMember->OpValue) {
1021 BundleMember = BundleMember->NextInBundle;
1022 continue;
1024 // Handle the def-use chain dependencies.
1025 for (Use &U : BundleMember->Inst->operands()) {
1026 auto *I = dyn_cast<Instruction>(U.get());
1027 if (!I)
1028 continue;
1029 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
1030 if (OpDef && OpDef->hasValidDependencies() &&
1031 OpDef->incrementUnscheduledDeps(-1) == 0) {
1032 // There are no more unscheduled dependencies after
1033 // decrementing, so we can put the dependent instruction
1034 // into the ready list.
1035 ScheduleData *DepBundle = OpDef->FirstInBundle;
1036 assert(!DepBundle->IsScheduled &&
1037 "already scheduled bundle gets ready");
1038 ReadyList.insert(DepBundle);
1039 LLVM_DEBUG(dbgs()
1040 << "SLP: gets ready (def): " << *DepBundle << "\n");
1044 // Handle the memory dependencies.
1045 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
1046 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
1047 // There are no more unscheduled dependencies after decrementing,
1048 // so we can put the dependent instruction into the ready list.
1049 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
1050 assert(!DepBundle->IsScheduled &&
1051 "already scheduled bundle gets ready");
1052 ReadyList.insert(DepBundle);
1053 LLVM_DEBUG(dbgs()
1054 << "SLP: gets ready (mem): " << *DepBundle << "\n");
1057 BundleMember = BundleMember->NextInBundle;
1061 void doForAllOpcodes(Value *V,
1062 function_ref<void(ScheduleData *SD)> Action) {
1063 if (ScheduleData *SD = getScheduleData(V))
1064 Action(SD);
1065 auto I = ExtraScheduleDataMap.find(V);
1066 if (I != ExtraScheduleDataMap.end())
1067 for (auto &P : I->second)
1068 if (P.second->SchedulingRegionID == SchedulingRegionID)
1069 Action(P.second);
1072 /// Put all instructions into the ReadyList which are ready for scheduling.
1073 template <typename ReadyListType>
1074 void initialFillReadyList(ReadyListType &ReadyList) {
1075 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
1076 doForAllOpcodes(I, [&](ScheduleData *SD) {
1077 if (SD->isSchedulingEntity() && SD->isReady()) {
1078 ReadyList.insert(SD);
1079 LLVM_DEBUG(dbgs()
1080 << "SLP: initially in ready list: " << *I << "\n");
1086 /// Checks if a bundle of instructions can be scheduled, i.e. has no
1087 /// cyclic dependencies. This is only a dry-run, no instructions are
1088 /// actually moved at this stage.
1089 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
1090 const InstructionsState &S);
1092 /// Un-bundles a group of instructions.
1093 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
1095 /// Allocates schedule data chunk.
1096 ScheduleData *allocateScheduleDataChunks();
1098 /// Extends the scheduling region so that V is inside the region.
1099 /// \returns true if the region size is within the limit.
1100 bool extendSchedulingRegion(Value *V, const InstructionsState &S);
1102 /// Initialize the ScheduleData structures for new instructions in the
1103 /// scheduling region.
1104 void initScheduleData(Instruction *FromI, Instruction *ToI,
1105 ScheduleData *PrevLoadStore,
1106 ScheduleData *NextLoadStore);
1108 /// Updates the dependency information of a bundle and of all instructions/
1109 /// bundles which depend on the original bundle.
1110 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
1111 BoUpSLP *SLP);
1113 /// Sets all instruction in the scheduling region to un-scheduled.
1114 void resetSchedule();
1116 BasicBlock *BB;
1118 /// Simple memory allocation for ScheduleData.
1119 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
1121 /// The size of a ScheduleData array in ScheduleDataChunks.
1122 int ChunkSize;
1124 /// The allocator position in the current chunk, which is the last entry
1125 /// of ScheduleDataChunks.
1126 int ChunkPos;
1128 /// Attaches ScheduleData to Instruction.
1129 /// Note that the mapping survives during all vectorization iterations, i.e.
1130 /// ScheduleData structures are recycled.
1131 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
1133 /// Attaches ScheduleData to Instruction with the leading key.
1134 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
1135 ExtraScheduleDataMap;
1137 struct ReadyList : SmallVector<ScheduleData *, 8> {
1138 void insert(ScheduleData *SD) { push_back(SD); }
1141 /// The ready-list for scheduling (only used for the dry-run).
1142 ReadyList ReadyInsts;
1144 /// The first instruction of the scheduling region.
1145 Instruction *ScheduleStart = nullptr;
1147 /// The first instruction _after_ the scheduling region.
1148 Instruction *ScheduleEnd = nullptr;
1150 /// The first memory accessing instruction in the scheduling region
1151 /// (can be null).
1152 ScheduleData *FirstLoadStoreInRegion = nullptr;
1154 /// The last memory accessing instruction in the scheduling region
1155 /// (can be null).
1156 ScheduleData *LastLoadStoreInRegion = nullptr;
1158 /// The current size of the scheduling region.
1159 int ScheduleRegionSize = 0;
1161 /// The maximum size allowed for the scheduling region.
1162 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
1164 /// The ID of the scheduling region. For a new vectorization iteration this
1165 /// is incremented which "removes" all ScheduleData from the region.
1166 // Make sure that the initial SchedulingRegionID is greater than the
1167 // initial SchedulingRegionID in ScheduleData (which is 0).
1168 int SchedulingRegionID = 1;
1171 /// Attaches the BlockScheduling structures to basic blocks.
1172 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
1174 /// Performs the "real" scheduling. Done before vectorization is actually
1175 /// performed in a basic block.
1176 void scheduleBlock(BlockScheduling *BS);
1178 /// List of users to ignore during scheduling and that don't need extracting.
1179 ArrayRef<Value *> UserIgnoreList;
1181 using OrdersType = SmallVector<unsigned, 4>;
1182 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
1183 /// sorted SmallVectors of unsigned.
1184 struct OrdersTypeDenseMapInfo {
1185 static OrdersType getEmptyKey() {
1186 OrdersType V;
1187 V.push_back(~1U);
1188 return V;
1191 static OrdersType getTombstoneKey() {
1192 OrdersType V;
1193 V.push_back(~2U);
1194 return V;
1197 static unsigned getHashValue(const OrdersType &V) {
1198 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1201 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
1202 return LHS == RHS;
1206 /// Contains orders of operations along with the number of bundles that have
1207 /// operations in this order. It stores only those orders that require
1208 /// reordering, if reordering is not required it is counted using \a
1209 /// NumOpsWantToKeepOriginalOrder.
1210 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder;
1211 /// Number of bundles that do not require reordering.
1212 unsigned NumOpsWantToKeepOriginalOrder = 0;
1214 // Analysis and block reference.
1215 Function *F;
1216 ScalarEvolution *SE;
1217 TargetTransformInfo *TTI;
1218 TargetLibraryInfo *TLI;
1219 AliasAnalysis *AA;
1220 LoopInfo *LI;
1221 DominatorTree *DT;
1222 AssumptionCache *AC;
1223 DemandedBits *DB;
1224 const DataLayout *DL;
1225 OptimizationRemarkEmitter *ORE;
1227 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
1228 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
1230 /// Instruction builder to construct the vectorized tree.
1231 IRBuilder<> Builder;
1233 /// A map of scalar integer values to the smallest bit width with which they
1234 /// can legally be represented. The values map to (width, signed) pairs,
1235 /// where "width" indicates the minimum bit width and "signed" is True if the
1236 /// value must be signed-extended, rather than zero-extended, back to its
1237 /// original width.
1238 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
1241 } // end namespace slpvectorizer
1243 template <> struct GraphTraits<BoUpSLP *> {
1244 using TreeEntry = BoUpSLP::TreeEntry;
1246 /// NodeRef has to be a pointer per the GraphWriter.
1247 using NodeRef = TreeEntry *;
1249 /// Add the VectorizableTree to the index iterator to be able to return
1250 /// TreeEntry pointers.
1251 struct ChildIteratorType
1252 : public iterator_adaptor_base<ChildIteratorType,
1253 SmallVector<int, 1>::iterator> {
1254 std::vector<TreeEntry> &VectorizableTree;
1256 ChildIteratorType(SmallVector<int, 1>::iterator W,
1257 std::vector<TreeEntry> &VT)
1258 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
1260 NodeRef operator*() { return &VectorizableTree[*I]; }
1263 static NodeRef getEntryNode(BoUpSLP &R) { return &R.VectorizableTree[0]; }
1265 static ChildIteratorType child_begin(NodeRef N) {
1266 return {N->UserTreeIndices.begin(), N->Container};
1269 static ChildIteratorType child_end(NodeRef N) {
1270 return {N->UserTreeIndices.end(), N->Container};
1273 /// For the node iterator we just need to turn the TreeEntry iterator into a
1274 /// TreeEntry* iterator so that it dereferences to NodeRef.
1275 using nodes_iterator = pointer_iterator<std::vector<TreeEntry>::iterator>;
1277 static nodes_iterator nodes_begin(BoUpSLP *R) {
1278 return nodes_iterator(R->VectorizableTree.begin());
1281 static nodes_iterator nodes_end(BoUpSLP *R) {
1282 return nodes_iterator(R->VectorizableTree.end());
1285 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
1288 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
1289 using TreeEntry = BoUpSLP::TreeEntry;
1291 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
1293 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
1294 std::string Str;
1295 raw_string_ostream OS(Str);
1296 if (isSplat(Entry->Scalars)) {
1297 OS << "<splat> " << *Entry->Scalars[0];
1298 return Str;
1300 for (auto V : Entry->Scalars) {
1301 OS << *V;
1302 if (std::any_of(
1303 R->ExternalUses.begin(), R->ExternalUses.end(),
1304 [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
1305 OS << " <extract>";
1306 OS << "\n";
1308 return Str;
1311 static std::string getNodeAttributes(const TreeEntry *Entry,
1312 const BoUpSLP *) {
1313 if (Entry->NeedToGather)
1314 return "color=red";
1315 return "";
1319 } // end namespace llvm
1321 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1322 ArrayRef<Value *> UserIgnoreLst) {
1323 ExtraValueToDebugLocsMap ExternallyUsedValues;
1324 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
1327 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
1328 ExtraValueToDebugLocsMap &ExternallyUsedValues,
1329 ArrayRef<Value *> UserIgnoreLst) {
1330 deleteTree();
1331 UserIgnoreList = UserIgnoreLst;
1332 if (!allSameType(Roots))
1333 return;
1334 buildTree_rec(Roots, 0, -1);
1336 // Collect the values that we need to extract from the tree.
1337 for (TreeEntry &EIdx : VectorizableTree) {
1338 TreeEntry *Entry = &EIdx;
1340 // No need to handle users of gathered values.
1341 if (Entry->NeedToGather)
1342 continue;
1344 // For each lane:
1345 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1346 Value *Scalar = Entry->Scalars[Lane];
1347 int FoundLane = Lane;
1348 if (!Entry->ReuseShuffleIndices.empty()) {
1349 FoundLane =
1350 std::distance(Entry->ReuseShuffleIndices.begin(),
1351 llvm::find(Entry->ReuseShuffleIndices, FoundLane));
1354 // Check if the scalar is externally used as an extra arg.
1355 auto ExtI = ExternallyUsedValues.find(Scalar);
1356 if (ExtI != ExternallyUsedValues.end()) {
1357 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
1358 << Lane << " from " << *Scalar << ".\n");
1359 ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
1361 for (User *U : Scalar->users()) {
1362 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
1364 Instruction *UserInst = dyn_cast<Instruction>(U);
1365 if (!UserInst)
1366 continue;
1368 // Skip in-tree scalars that become vectors
1369 if (TreeEntry *UseEntry = getTreeEntry(U)) {
1370 Value *UseScalar = UseEntry->Scalars[0];
1371 // Some in-tree scalars will remain as scalar in vectorized
1372 // instructions. If that is the case, the one in Lane 0 will
1373 // be used.
1374 if (UseScalar != U ||
1375 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
1376 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
1377 << ".\n");
1378 assert(!UseEntry->NeedToGather && "Bad state");
1379 continue;
1383 // Ignore users in the user ignore list.
1384 if (is_contained(UserIgnoreList, UserInst))
1385 continue;
1387 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
1388 << Lane << " from " << *Scalar << ".\n");
1389 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
1395 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
1396 int UserTreeIdx) {
1397 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
1399 InstructionsState S = getSameOpcode(VL);
1400 if (Depth == RecursionMaxDepth) {
1401 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1402 newTreeEntry(VL, false, UserTreeIdx);
1403 return;
1406 // Don't handle vectors.
1407 if (S.OpValue->getType()->isVectorTy()) {
1408 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1409 newTreeEntry(VL, false, UserTreeIdx);
1410 return;
1413 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
1414 if (SI->getValueOperand()->getType()->isVectorTy()) {
1415 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1416 newTreeEntry(VL, false, UserTreeIdx);
1417 return;
1420 // If all of the operands are identical or constant we have a simple solution.
1421 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) {
1422 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1423 newTreeEntry(VL, false, UserTreeIdx);
1424 return;
1427 // We now know that this is a vector of instructions of the same type from
1428 // the same block.
1430 // Don't vectorize ephemeral values.
1431 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1432 if (EphValues.count(VL[i])) {
1433 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *VL[i]
1434 << ") is ephemeral.\n");
1435 newTreeEntry(VL, false, UserTreeIdx);
1436 return;
1440 // Check if this is a duplicate of another entry.
1441 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
1442 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
1443 if (!E->isSame(VL)) {
1444 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1445 newTreeEntry(VL, false, UserTreeIdx);
1446 return;
1448 // Record the reuse of the tree node. FIXME, currently this is only used to
1449 // properly draw the graph rather than for the actual vectorization.
1450 E->UserTreeIndices.push_back(UserTreeIdx);
1451 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
1452 << ".\n");
1453 return;
1456 // Check that none of the instructions in the bundle are already in the tree.
1457 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1458 auto *I = dyn_cast<Instruction>(VL[i]);
1459 if (!I)
1460 continue;
1461 if (getTreeEntry(I)) {
1462 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *VL[i]
1463 << ") is already in tree.\n");
1464 newTreeEntry(VL, false, UserTreeIdx);
1465 return;
1469 // If any of the scalars is marked as a value that needs to stay scalar, then
1470 // we need to gather the scalars.
1471 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1472 if (MustGather.count(VL[i])) {
1473 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1474 newTreeEntry(VL, false, UserTreeIdx);
1475 return;
1479 // Check that all of the users of the scalars that we want to vectorize are
1480 // schedulable.
1481 auto *VL0 = cast<Instruction>(S.OpValue);
1482 BasicBlock *BB = VL0->getParent();
1484 if (!DT->isReachableFromEntry(BB)) {
1485 // Don't go into unreachable blocks. They may contain instructions with
1486 // dependency cycles which confuse the final scheduling.
1487 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1488 newTreeEntry(VL, false, UserTreeIdx);
1489 return;
1492 // Check that every instruction appears once in this bundle.
1493 SmallVector<unsigned, 4> ReuseShuffleIndicies;
1494 SmallVector<Value *, 4> UniqueValues;
1495 DenseMap<Value *, unsigned> UniquePositions;
1496 for (Value *V : VL) {
1497 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
1498 ReuseShuffleIndicies.emplace_back(Res.first->second);
1499 if (Res.second)
1500 UniqueValues.emplace_back(V);
1502 if (UniqueValues.size() == VL.size()) {
1503 ReuseShuffleIndicies.clear();
1504 } else {
1505 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
1506 if (UniqueValues.size() <= 1 || !llvm::isPowerOf2_32(UniqueValues.size())) {
1507 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1508 newTreeEntry(VL, false, UserTreeIdx);
1509 return;
1511 VL = UniqueValues;
1514 auto &BSRef = BlocksSchedules[BB];
1515 if (!BSRef)
1516 BSRef = llvm::make_unique<BlockScheduling>(BB);
1518 BlockScheduling &BS = *BSRef.get();
1520 if (!BS.tryScheduleBundle(VL, this, S)) {
1521 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1522 assert((!BS.getScheduleData(VL0) ||
1523 !BS.getScheduleData(VL0)->isPartOfBundle()) &&
1524 "tryScheduleBundle should cancelScheduling on failure");
1525 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1526 return;
1528 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1530 unsigned ShuffleOrOp = S.isAltShuffle() ?
1531 (unsigned) Instruction::ShuffleVector : S.getOpcode();
1532 switch (ShuffleOrOp) {
1533 case Instruction::PHI: {
1534 PHINode *PH = dyn_cast<PHINode>(VL0);
1536 // Check for terminator values (e.g. invoke).
1537 for (unsigned j = 0; j < VL.size(); ++j)
1538 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1539 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1540 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1541 if (Term) {
1542 LLVM_DEBUG(
1543 dbgs()
1544 << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1545 BS.cancelScheduling(VL, VL0);
1546 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1547 return;
1551 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1552 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1554 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1555 ValueList Operands;
1556 // Prepare the operand vector.
1557 for (Value *j : VL)
1558 Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1559 PH->getIncomingBlock(i)));
1561 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1563 return;
1565 case Instruction::ExtractValue:
1566 case Instruction::ExtractElement: {
1567 OrdersType CurrentOrder;
1568 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
1569 if (Reuse) {
1570 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
1571 ++NumOpsWantToKeepOriginalOrder;
1572 newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx,
1573 ReuseShuffleIndicies);
1574 return;
1576 if (!CurrentOrder.empty()) {
1577 LLVM_DEBUG({
1578 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
1579 "with order";
1580 for (unsigned Idx : CurrentOrder)
1581 dbgs() << " " << Idx;
1582 dbgs() << "\n";
1584 // Insert new order with initial value 0, if it does not exist,
1585 // otherwise return the iterator to the existing one.
1586 auto StoredCurrentOrderAndNum =
1587 NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
1588 ++StoredCurrentOrderAndNum->getSecond();
1589 newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx, ReuseShuffleIndicies,
1590 StoredCurrentOrderAndNum->getFirst());
1591 return;
1593 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
1594 newTreeEntry(VL, /*Vectorized=*/false, UserTreeIdx, ReuseShuffleIndicies);
1595 BS.cancelScheduling(VL, VL0);
1596 return;
1598 case Instruction::Load: {
1599 // Check that a vectorized load would load the same memory as a scalar
1600 // load. For example, we don't want to vectorize loads that are smaller
1601 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
1602 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
1603 // from such a struct, we read/write packed bits disagreeing with the
1604 // unvectorized version.
1605 Type *ScalarTy = VL0->getType();
1607 if (DL->getTypeSizeInBits(ScalarTy) !=
1608 DL->getTypeAllocSizeInBits(ScalarTy)) {
1609 BS.cancelScheduling(VL, VL0);
1610 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1611 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
1612 return;
1615 // Make sure all loads in the bundle are simple - we can't vectorize
1616 // atomic or volatile loads.
1617 SmallVector<Value *, 4> PointerOps(VL.size());
1618 auto POIter = PointerOps.begin();
1619 for (Value *V : VL) {
1620 auto *L = cast<LoadInst>(V);
1621 if (!L->isSimple()) {
1622 BS.cancelScheduling(VL, VL0);
1623 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1624 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1625 return;
1627 *POIter = L->getPointerOperand();
1628 ++POIter;
1631 OrdersType CurrentOrder;
1632 // Check the order of pointer operands.
1633 if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
1634 Value *Ptr0;
1635 Value *PtrN;
1636 if (CurrentOrder.empty()) {
1637 Ptr0 = PointerOps.front();
1638 PtrN = PointerOps.back();
1639 } else {
1640 Ptr0 = PointerOps[CurrentOrder.front()];
1641 PtrN = PointerOps[CurrentOrder.back()];
1643 const SCEV *Scev0 = SE->getSCEV(Ptr0);
1644 const SCEV *ScevN = SE->getSCEV(PtrN);
1645 const auto *Diff =
1646 dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
1647 uint64_t Size = DL->getTypeAllocSize(ScalarTy);
1648 // Check that the sorted loads are consecutive.
1649 if (Diff && Diff->getAPInt().getZExtValue() == (VL.size() - 1) * Size) {
1650 if (CurrentOrder.empty()) {
1651 // Original loads are consecutive and does not require reordering.
1652 ++NumOpsWantToKeepOriginalOrder;
1653 newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx,
1654 ReuseShuffleIndicies);
1655 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1656 } else {
1657 // Need to reorder.
1658 auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
1659 ++I->getSecond();
1660 newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx,
1661 ReuseShuffleIndicies, I->getFirst());
1662 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
1664 return;
1668 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1669 BS.cancelScheduling(VL, VL0);
1670 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1671 return;
1673 case Instruction::ZExt:
1674 case Instruction::SExt:
1675 case Instruction::FPToUI:
1676 case Instruction::FPToSI:
1677 case Instruction::FPExt:
1678 case Instruction::PtrToInt:
1679 case Instruction::IntToPtr:
1680 case Instruction::SIToFP:
1681 case Instruction::UIToFP:
1682 case Instruction::Trunc:
1683 case Instruction::FPTrunc:
1684 case Instruction::BitCast: {
1685 Type *SrcTy = VL0->getOperand(0)->getType();
1686 for (unsigned i = 0; i < VL.size(); ++i) {
1687 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1688 if (Ty != SrcTy || !isValidElementType(Ty)) {
1689 BS.cancelScheduling(VL, VL0);
1690 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1691 LLVM_DEBUG(dbgs()
1692 << "SLP: Gathering casts with different src types.\n");
1693 return;
1696 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1697 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1699 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1700 ValueList Operands;
1701 // Prepare the operand vector.
1702 for (Value *j : VL)
1703 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1705 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1707 return;
1709 case Instruction::ICmp:
1710 case Instruction::FCmp: {
1711 // Check that all of the compares have the same predicate.
1712 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
1713 Type *ComparedTy = VL0->getOperand(0)->getType();
1714 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1715 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1716 if (Cmp->getPredicate() != P0 ||
1717 Cmp->getOperand(0)->getType() != ComparedTy) {
1718 BS.cancelScheduling(VL, VL0);
1719 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1720 LLVM_DEBUG(dbgs()
1721 << "SLP: Gathering cmp with different predicate.\n");
1722 return;
1726 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1727 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1729 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1730 ValueList Operands;
1731 // Prepare the operand vector.
1732 for (Value *j : VL)
1733 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1735 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1737 return;
1739 case Instruction::Select:
1740 case Instruction::Add:
1741 case Instruction::FAdd:
1742 case Instruction::Sub:
1743 case Instruction::FSub:
1744 case Instruction::Mul:
1745 case Instruction::FMul:
1746 case Instruction::UDiv:
1747 case Instruction::SDiv:
1748 case Instruction::FDiv:
1749 case Instruction::URem:
1750 case Instruction::SRem:
1751 case Instruction::FRem:
1752 case Instruction::Shl:
1753 case Instruction::LShr:
1754 case Instruction::AShr:
1755 case Instruction::And:
1756 case Instruction::Or:
1757 case Instruction::Xor:
1758 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1759 LLVM_DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1761 // Sort operands of the instructions so that each side is more likely to
1762 // have the same opcode.
1763 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1764 ValueList Left, Right;
1765 reorderInputsAccordingToOpcode(S.getOpcode(), VL, Left, Right);
1766 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1767 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1768 return;
1771 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1772 ValueList Operands;
1773 // Prepare the operand vector.
1774 for (Value *j : VL)
1775 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1777 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1779 return;
1781 case Instruction::GetElementPtr: {
1782 // We don't combine GEPs with complicated (nested) indexing.
1783 for (unsigned j = 0; j < VL.size(); ++j) {
1784 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1785 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1786 BS.cancelScheduling(VL, VL0);
1787 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1788 return;
1792 // We can't combine several GEPs into one vector if they operate on
1793 // different types.
1794 Type *Ty0 = VL0->getOperand(0)->getType();
1795 for (unsigned j = 0; j < VL.size(); ++j) {
1796 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1797 if (Ty0 != CurTy) {
1798 LLVM_DEBUG(dbgs()
1799 << "SLP: not-vectorizable GEP (different types).\n");
1800 BS.cancelScheduling(VL, VL0);
1801 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1802 return;
1806 // We don't combine GEPs with non-constant indexes.
1807 for (unsigned j = 0; j < VL.size(); ++j) {
1808 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1809 if (!isa<ConstantInt>(Op)) {
1810 LLVM_DEBUG(dbgs()
1811 << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1812 BS.cancelScheduling(VL, VL0);
1813 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1814 return;
1818 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1819 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1820 for (unsigned i = 0, e = 2; i < e; ++i) {
1821 ValueList Operands;
1822 // Prepare the operand vector.
1823 for (Value *j : VL)
1824 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1826 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1828 return;
1830 case Instruction::Store: {
1831 // Check if the stores are consecutive or of we need to swizzle them.
1832 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1833 if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1834 BS.cancelScheduling(VL, VL0);
1835 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1836 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1837 return;
1840 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1841 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1843 ValueList Operands;
1844 for (Value *j : VL)
1845 Operands.push_back(cast<Instruction>(j)->getOperand(0));
1847 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1848 return;
1850 case Instruction::Call: {
1851 // Check if the calls are all to the same vectorizable intrinsic.
1852 CallInst *CI = cast<CallInst>(VL0);
1853 // Check if this is an Intrinsic call or something that can be
1854 // represented by an intrinsic call
1855 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
1856 if (!isTriviallyVectorizable(ID)) {
1857 BS.cancelScheduling(VL, VL0);
1858 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1859 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1860 return;
1862 Function *Int = CI->getCalledFunction();
1863 Value *A1I = nullptr;
1864 if (hasVectorInstrinsicScalarOpd(ID, 1))
1865 A1I = CI->getArgOperand(1);
1866 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1867 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1868 if (!CI2 || CI2->getCalledFunction() != Int ||
1869 getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
1870 !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1871 BS.cancelScheduling(VL, VL0);
1872 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1873 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1874 << "\n");
1875 return;
1877 // ctlz,cttz and powi are special intrinsics whose second argument
1878 // should be same in order for them to be vectorized.
1879 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1880 Value *A1J = CI2->getArgOperand(1);
1881 if (A1I != A1J) {
1882 BS.cancelScheduling(VL, VL0);
1883 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1884 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1885 << " argument " << A1I << "!=" << A1J << "\n");
1886 return;
1889 // Verify that the bundle operands are identical between the two calls.
1890 if (CI->hasOperandBundles() &&
1891 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
1892 CI->op_begin() + CI->getBundleOperandsEndIndex(),
1893 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1894 BS.cancelScheduling(VL, VL0);
1895 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1896 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
1897 << *CI << "!=" << *VL[i] << '\n');
1898 return;
1902 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1903 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1904 ValueList Operands;
1905 // Prepare the operand vector.
1906 for (Value *j : VL) {
1907 CallInst *CI2 = dyn_cast<CallInst>(j);
1908 Operands.push_back(CI2->getArgOperand(i));
1910 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1912 return;
1914 case Instruction::ShuffleVector:
1915 // If this is not an alternate sequence of opcode like add-sub
1916 // then do not vectorize this instruction.
1917 if (!S.isAltShuffle()) {
1918 BS.cancelScheduling(VL, VL0);
1919 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1920 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1921 return;
1923 newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
1924 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1926 // Reorder operands if reordering would enable vectorization.
1927 if (isa<BinaryOperator>(VL0)) {
1928 ValueList Left, Right;
1929 reorderAltShuffleOperands(S, VL, Left, Right);
1930 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1931 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1932 return;
1935 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1936 ValueList Operands;
1937 // Prepare the operand vector.
1938 for (Value *j : VL)
1939 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1941 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1943 return;
1945 default:
1946 BS.cancelScheduling(VL, VL0);
1947 newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1948 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1949 return;
1953 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
1954 unsigned N;
1955 Type *EltTy;
1956 auto *ST = dyn_cast<StructType>(T);
1957 if (ST) {
1958 N = ST->getNumElements();
1959 EltTy = *ST->element_begin();
1960 } else {
1961 N = cast<ArrayType>(T)->getNumElements();
1962 EltTy = cast<ArrayType>(T)->getElementType();
1964 if (!isValidElementType(EltTy))
1965 return 0;
1966 uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
1967 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
1968 return 0;
1969 if (ST) {
1970 // Check that struct is homogeneous.
1971 for (const auto *Ty : ST->elements())
1972 if (Ty != EltTy)
1973 return 0;
1975 return N;
1978 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1979 SmallVectorImpl<unsigned> &CurrentOrder) const {
1980 Instruction *E0 = cast<Instruction>(OpValue);
1981 assert(E0->getOpcode() == Instruction::ExtractElement ||
1982 E0->getOpcode() == Instruction::ExtractValue);
1983 assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
1984 // Check if all of the extracts come from the same vector and from the
1985 // correct offset.
1986 Value *Vec = E0->getOperand(0);
1988 CurrentOrder.clear();
1990 // We have to extract from a vector/aggregate with the same number of elements.
1991 unsigned NElts;
1992 if (E0->getOpcode() == Instruction::ExtractValue) {
1993 const DataLayout &DL = E0->getModule()->getDataLayout();
1994 NElts = canMapToVector(Vec->getType(), DL);
1995 if (!NElts)
1996 return false;
1997 // Check if load can be rewritten as load of vector.
1998 LoadInst *LI = dyn_cast<LoadInst>(Vec);
1999 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
2000 return false;
2001 } else {
2002 NElts = Vec->getType()->getVectorNumElements();
2005 if (NElts != VL.size())
2006 return false;
2008 // Check that all of the indices extract from the correct offset.
2009 bool ShouldKeepOrder = true;
2010 unsigned E = VL.size();
2011 // Assign to all items the initial value E + 1 so we can check if the extract
2012 // instruction index was used already.
2013 // Also, later we can check that all the indices are used and we have a
2014 // consecutive access in the extract instructions, by checking that no
2015 // element of CurrentOrder still has value E + 1.
2016 CurrentOrder.assign(E, E + 1);
2017 unsigned I = 0;
2018 for (; I < E; ++I) {
2019 auto *Inst = cast<Instruction>(VL[I]);
2020 if (Inst->getOperand(0) != Vec)
2021 break;
2022 Optional<unsigned> Idx = getExtractIndex(Inst);
2023 if (!Idx)
2024 break;
2025 const unsigned ExtIdx = *Idx;
2026 if (ExtIdx != I) {
2027 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
2028 break;
2029 ShouldKeepOrder = false;
2030 CurrentOrder[ExtIdx] = I;
2031 } else {
2032 if (CurrentOrder[I] != E + 1)
2033 break;
2034 CurrentOrder[I] = I;
2037 if (I < E) {
2038 CurrentOrder.clear();
2039 return false;
2042 return ShouldKeepOrder;
2045 bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
2046 return I->hasOneUse() ||
2047 std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
2048 return ScalarToTreeEntry.count(U) > 0;
2052 int BoUpSLP::getEntryCost(TreeEntry *E) {
2053 ArrayRef<Value*> VL = E->Scalars;
2055 Type *ScalarTy = VL[0]->getType();
2056 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2057 ScalarTy = SI->getValueOperand()->getType();
2058 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
2059 ScalarTy = CI->getOperand(0)->getType();
2060 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2062 // If we have computed a smaller type for the expression, update VecTy so
2063 // that the costs will be accurate.
2064 if (MinBWs.count(VL[0]))
2065 VecTy = VectorType::get(
2066 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
2068 unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
2069 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
2070 int ReuseShuffleCost = 0;
2071 if (NeedToShuffleReuses) {
2072 ReuseShuffleCost =
2073 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
2075 if (E->NeedToGather) {
2076 if (allConstant(VL))
2077 return 0;
2078 if (isSplat(VL)) {
2079 return ReuseShuffleCost +
2080 TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
2082 if (getSameOpcode(VL).getOpcode() == Instruction::ExtractElement &&
2083 allSameType(VL) && allSameBlock(VL)) {
2084 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL);
2085 if (ShuffleKind.hasValue()) {
2086 int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy);
2087 for (auto *V : VL) {
2088 // If all users of instruction are going to be vectorized and this
2089 // instruction itself is not going to be vectorized, consider this
2090 // instruction as dead and remove its cost from the final cost of the
2091 // vectorized tree.
2092 if (areAllUsersVectorized(cast<Instruction>(V)) &&
2093 !ScalarToTreeEntry.count(V)) {
2094 auto *IO = cast<ConstantInt>(
2095 cast<ExtractElementInst>(V)->getIndexOperand());
2096 Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
2097 IO->getZExtValue());
2100 return ReuseShuffleCost + Cost;
2103 return ReuseShuffleCost + getGatherCost(VL);
2105 InstructionsState S = getSameOpcode(VL);
2106 assert(S.getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
2107 Instruction *VL0 = cast<Instruction>(S.OpValue);
2108 unsigned ShuffleOrOp = S.isAltShuffle() ?
2109 (unsigned) Instruction::ShuffleVector : S.getOpcode();
2110 switch (ShuffleOrOp) {
2111 case Instruction::PHI:
2112 return 0;
2114 case Instruction::ExtractValue:
2115 case Instruction::ExtractElement:
2116 if (NeedToShuffleReuses) {
2117 unsigned Idx = 0;
2118 for (unsigned I : E->ReuseShuffleIndices) {
2119 if (ShuffleOrOp == Instruction::ExtractElement) {
2120 auto *IO = cast<ConstantInt>(
2121 cast<ExtractElementInst>(VL[I])->getIndexOperand());
2122 Idx = IO->getZExtValue();
2123 ReuseShuffleCost -= TTI->getVectorInstrCost(
2124 Instruction::ExtractElement, VecTy, Idx);
2125 } else {
2126 ReuseShuffleCost -= TTI->getVectorInstrCost(
2127 Instruction::ExtractElement, VecTy, Idx);
2128 ++Idx;
2131 Idx = ReuseShuffleNumbers;
2132 for (Value *V : VL) {
2133 if (ShuffleOrOp == Instruction::ExtractElement) {
2134 auto *IO = cast<ConstantInt>(
2135 cast<ExtractElementInst>(V)->getIndexOperand());
2136 Idx = IO->getZExtValue();
2137 } else {
2138 --Idx;
2140 ReuseShuffleCost +=
2141 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
2144 if (!E->NeedToGather) {
2145 int DeadCost = ReuseShuffleCost;
2146 if (!E->ReorderIndices.empty()) {
2147 // TODO: Merge this shuffle with the ReuseShuffleCost.
2148 DeadCost += TTI->getShuffleCost(
2149 TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
2151 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2152 Instruction *E = cast<Instruction>(VL[i]);
2153 // If all users are going to be vectorized, instruction can be
2154 // considered as dead.
2155 // The same, if have only one user, it will be vectorized for sure.
2156 if (areAllUsersVectorized(E)) {
2157 // Take credit for instruction that will become dead.
2158 if (E->hasOneUse()) {
2159 Instruction *Ext = E->user_back();
2160 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2161 all_of(Ext->users(),
2162 [](User *U) { return isa<GetElementPtrInst>(U); })) {
2163 // Use getExtractWithExtendCost() to calculate the cost of
2164 // extractelement/ext pair.
2165 DeadCost -= TTI->getExtractWithExtendCost(
2166 Ext->getOpcode(), Ext->getType(), VecTy, i);
2167 // Add back the cost of s|zext which is subtracted seperately.
2168 DeadCost += TTI->getCastInstrCost(
2169 Ext->getOpcode(), Ext->getType(), E->getType(), Ext);
2170 continue;
2173 DeadCost -=
2174 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
2177 return DeadCost;
2179 return ReuseShuffleCost + getGatherCost(VL);
2181 case Instruction::ZExt:
2182 case Instruction::SExt:
2183 case Instruction::FPToUI:
2184 case Instruction::FPToSI:
2185 case Instruction::FPExt:
2186 case Instruction::PtrToInt:
2187 case Instruction::IntToPtr:
2188 case Instruction::SIToFP:
2189 case Instruction::UIToFP:
2190 case Instruction::Trunc:
2191 case Instruction::FPTrunc:
2192 case Instruction::BitCast: {
2193 Type *SrcTy = VL0->getOperand(0)->getType();
2194 int ScalarEltCost =
2195 TTI->getCastInstrCost(S.getOpcode(), ScalarTy, SrcTy, VL0);
2196 if (NeedToShuffleReuses) {
2197 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
2200 // Calculate the cost of this instruction.
2201 int ScalarCost = VL.size() * ScalarEltCost;
2203 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
2204 int VecCost = 0;
2205 // Check if the values are candidates to demote.
2206 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
2207 VecCost = ReuseShuffleCost +
2208 TTI->getCastInstrCost(S.getOpcode(), VecTy, SrcVecTy, VL0);
2210 return VecCost - ScalarCost;
2212 case Instruction::FCmp:
2213 case Instruction::ICmp:
2214 case Instruction::Select: {
2215 // Calculate the cost of this instruction.
2216 int ScalarEltCost = TTI->getCmpSelInstrCost(S.getOpcode(), ScalarTy,
2217 Builder.getInt1Ty(), VL0);
2218 if (NeedToShuffleReuses) {
2219 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
2221 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
2222 int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
2223 int VecCost = TTI->getCmpSelInstrCost(S.getOpcode(), VecTy, MaskTy, VL0);
2224 return ReuseShuffleCost + VecCost - ScalarCost;
2226 case Instruction::Add:
2227 case Instruction::FAdd:
2228 case Instruction::Sub:
2229 case Instruction::FSub:
2230 case Instruction::Mul:
2231 case Instruction::FMul:
2232 case Instruction::UDiv:
2233 case Instruction::SDiv:
2234 case Instruction::FDiv:
2235 case Instruction::URem:
2236 case Instruction::SRem:
2237 case Instruction::FRem:
2238 case Instruction::Shl:
2239 case Instruction::LShr:
2240 case Instruction::AShr:
2241 case Instruction::And:
2242 case Instruction::Or:
2243 case Instruction::Xor: {
2244 // Certain instructions can be cheaper to vectorize if they have a
2245 // constant second vector operand.
2246 TargetTransformInfo::OperandValueKind Op1VK =
2247 TargetTransformInfo::OK_AnyValue;
2248 TargetTransformInfo::OperandValueKind Op2VK =
2249 TargetTransformInfo::OK_UniformConstantValue;
2250 TargetTransformInfo::OperandValueProperties Op1VP =
2251 TargetTransformInfo::OP_None;
2252 TargetTransformInfo::OperandValueProperties Op2VP =
2253 TargetTransformInfo::OP_PowerOf2;
2255 // If all operands are exactly the same ConstantInt then set the
2256 // operand kind to OK_UniformConstantValue.
2257 // If instead not all operands are constants, then set the operand kind
2258 // to OK_AnyValue. If all operands are constants but not the same,
2259 // then set the operand kind to OK_NonUniformConstantValue.
2260 ConstantInt *CInt0 = nullptr;
2261 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2262 const Instruction *I = cast<Instruction>(VL[i]);
2263 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(1));
2264 if (!CInt) {
2265 Op2VK = TargetTransformInfo::OK_AnyValue;
2266 Op2VP = TargetTransformInfo::OP_None;
2267 break;
2269 if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
2270 !CInt->getValue().isPowerOf2())
2271 Op2VP = TargetTransformInfo::OP_None;
2272 if (i == 0) {
2273 CInt0 = CInt;
2274 continue;
2276 if (CInt0 != CInt)
2277 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
2280 SmallVector<const Value *, 4> Operands(VL0->operand_values());
2281 int ScalarEltCost = TTI->getArithmeticInstrCost(
2282 S.getOpcode(), ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands);
2283 if (NeedToShuffleReuses) {
2284 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
2286 int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
2287 int VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy, Op1VK,
2288 Op2VK, Op1VP, Op2VP, Operands);
2289 return ReuseShuffleCost + VecCost - ScalarCost;
2291 case Instruction::GetElementPtr: {
2292 TargetTransformInfo::OperandValueKind Op1VK =
2293 TargetTransformInfo::OK_AnyValue;
2294 TargetTransformInfo::OperandValueKind Op2VK =
2295 TargetTransformInfo::OK_UniformConstantValue;
2297 int ScalarEltCost =
2298 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
2299 if (NeedToShuffleReuses) {
2300 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
2302 int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
2303 int VecCost =
2304 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
2305 return ReuseShuffleCost + VecCost - ScalarCost;
2307 case Instruction::Load: {
2308 // Cost of wide load - cost of scalar loads.
2309 unsigned alignment = cast<LoadInst>(VL0)->getAlignment();
2310 int ScalarEltCost =
2311 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
2312 if (NeedToShuffleReuses) {
2313 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
2315 int ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
2316 int VecLdCost =
2317 TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0, VL0);
2318 if (!E->ReorderIndices.empty()) {
2319 // TODO: Merge this shuffle with the ReuseShuffleCost.
2320 VecLdCost += TTI->getShuffleCost(
2321 TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
2323 return ReuseShuffleCost + VecLdCost - ScalarLdCost;
2325 case Instruction::Store: {
2326 // We know that we can merge the stores. Calculate the cost.
2327 unsigned alignment = cast<StoreInst>(VL0)->getAlignment();
2328 int ScalarEltCost =
2329 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
2330 if (NeedToShuffleReuses) {
2331 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
2333 int ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
2334 int VecStCost =
2335 TTI->getMemoryOpCost(Instruction::Store, VecTy, alignment, 0, VL0);
2336 return ReuseShuffleCost + VecStCost - ScalarStCost;
2338 case Instruction::Call: {
2339 CallInst *CI = cast<CallInst>(VL0);
2340 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2342 // Calculate the cost of the scalar and vector calls.
2343 SmallVector<Type *, 4> ScalarTys;
2344 for (unsigned op = 0, opc = CI->getNumArgOperands(); op != opc; ++op)
2345 ScalarTys.push_back(CI->getArgOperand(op)->getType());
2347 FastMathFlags FMF;
2348 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2349 FMF = FPMO->getFastMathFlags();
2351 int ScalarEltCost =
2352 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
2353 if (NeedToShuffleReuses) {
2354 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
2356 int ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
2358 SmallVector<Value *, 4> Args(CI->arg_operands());
2359 int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
2360 VecTy->getNumElements());
2362 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
2363 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
2364 << " for " << *CI << "\n");
2366 return ReuseShuffleCost + VecCallCost - ScalarCallCost;
2368 case Instruction::ShuffleVector: {
2369 assert(S.isAltShuffle() &&
2370 ((Instruction::isBinaryOp(S.getOpcode()) &&
2371 Instruction::isBinaryOp(S.getAltOpcode())) ||
2372 (Instruction::isCast(S.getOpcode()) &&
2373 Instruction::isCast(S.getAltOpcode()))) &&
2374 "Invalid Shuffle Vector Operand");
2375 int ScalarCost = 0;
2376 if (NeedToShuffleReuses) {
2377 for (unsigned Idx : E->ReuseShuffleIndices) {
2378 Instruction *I = cast<Instruction>(VL[Idx]);
2379 ReuseShuffleCost -= TTI->getInstructionCost(
2380 I, TargetTransformInfo::TCK_RecipThroughput);
2382 for (Value *V : VL) {
2383 Instruction *I = cast<Instruction>(V);
2384 ReuseShuffleCost += TTI->getInstructionCost(
2385 I, TargetTransformInfo::TCK_RecipThroughput);
2388 for (Value *i : VL) {
2389 Instruction *I = cast<Instruction>(i);
2390 assert(S.isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
2391 ScalarCost += TTI->getInstructionCost(
2392 I, TargetTransformInfo::TCK_RecipThroughput);
2394 // VecCost is equal to sum of the cost of creating 2 vectors
2395 // and the cost of creating shuffle.
2396 int VecCost = 0;
2397 if (Instruction::isBinaryOp(S.getOpcode())) {
2398 VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy);
2399 VecCost += TTI->getArithmeticInstrCost(S.getAltOpcode(), VecTy);
2400 } else {
2401 Type *Src0SclTy = S.MainOp->getOperand(0)->getType();
2402 Type *Src1SclTy = S.AltOp->getOperand(0)->getType();
2403 VectorType *Src0Ty = VectorType::get(Src0SclTy, VL.size());
2404 VectorType *Src1Ty = VectorType::get(Src1SclTy, VL.size());
2405 VecCost = TTI->getCastInstrCost(S.getOpcode(), VecTy, Src0Ty);
2406 VecCost += TTI->getCastInstrCost(S.getAltOpcode(), VecTy, Src1Ty);
2408 VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
2409 return ReuseShuffleCost + VecCost - ScalarCost;
2411 default:
2412 llvm_unreachable("Unknown instruction");
2416 bool BoUpSLP::isFullyVectorizableTinyTree() {
2417 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
2418 << VectorizableTree.size() << " is fully vectorizable .\n");
2420 // We only handle trees of heights 1 and 2.
2421 if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
2422 return true;
2424 if (VectorizableTree.size() != 2)
2425 return false;
2427 // Handle splat and all-constants stores.
2428 if (!VectorizableTree[0].NeedToGather &&
2429 (allConstant(VectorizableTree[1].Scalars) ||
2430 isSplat(VectorizableTree[1].Scalars)))
2431 return true;
2433 // Gathering cost would be too much for tiny trees.
2434 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
2435 return false;
2437 return true;
2440 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
2441 // We can vectorize the tree if its size is greater than or equal to the
2442 // minimum size specified by the MinTreeSize command line option.
2443 if (VectorizableTree.size() >= MinTreeSize)
2444 return false;
2446 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
2447 // can vectorize it if we can prove it fully vectorizable.
2448 if (isFullyVectorizableTinyTree())
2449 return false;
2451 assert(VectorizableTree.empty()
2452 ? ExternalUses.empty()
2453 : true && "We shouldn't have any external users");
2455 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
2456 // vectorizable.
2457 return true;
2460 int BoUpSLP::getSpillCost() {
2461 // Walk from the bottom of the tree to the top, tracking which values are
2462 // live. When we see a call instruction that is not part of our tree,
2463 // query TTI to see if there is a cost to keeping values live over it
2464 // (for example, if spills and fills are required).
2465 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
2466 int Cost = 0;
2468 SmallPtrSet<Instruction*, 4> LiveValues;
2469 Instruction *PrevInst = nullptr;
2471 for (const auto &N : VectorizableTree) {
2472 Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
2473 if (!Inst)
2474 continue;
2476 if (!PrevInst) {
2477 PrevInst = Inst;
2478 continue;
2481 // Update LiveValues.
2482 LiveValues.erase(PrevInst);
2483 for (auto &J : PrevInst->operands()) {
2484 if (isa<Instruction>(&*J) && getTreeEntry(&*J))
2485 LiveValues.insert(cast<Instruction>(&*J));
2488 LLVM_DEBUG({
2489 dbgs() << "SLP: #LV: " << LiveValues.size();
2490 for (auto *X : LiveValues)
2491 dbgs() << " " << X->getName();
2492 dbgs() << ", Looking at ";
2493 Inst->dump();
2496 // Now find the sequence of instructions between PrevInst and Inst.
2497 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
2498 PrevInstIt =
2499 PrevInst->getIterator().getReverse();
2500 while (InstIt != PrevInstIt) {
2501 if (PrevInstIt == PrevInst->getParent()->rend()) {
2502 PrevInstIt = Inst->getParent()->rbegin();
2503 continue;
2506 // Debug informations don't impact spill cost.
2507 if ((isa<CallInst>(&*PrevInstIt) &&
2508 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
2509 &*PrevInstIt != PrevInst) {
2510 SmallVector<Type*, 4> V;
2511 for (auto *II : LiveValues)
2512 V.push_back(VectorType::get(II->getType(), BundleWidth));
2513 Cost += TTI->getCostOfKeepingLiveOverCall(V);
2516 ++PrevInstIt;
2519 PrevInst = Inst;
2522 return Cost;
2525 int BoUpSLP::getTreeCost() {
2526 int Cost = 0;
2527 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
2528 << VectorizableTree.size() << ".\n");
2530 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2532 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
2533 TreeEntry &TE = VectorizableTree[I];
2535 // We create duplicate tree entries for gather sequences that have multiple
2536 // uses. However, we should not compute the cost of duplicate sequences.
2537 // For example, if we have a build vector (i.e., insertelement sequence)
2538 // that is used by more than one vector instruction, we only need to
2539 // compute the cost of the insertelement instructions once. The redundent
2540 // instructions will be eliminated by CSE.
2542 // We should consider not creating duplicate tree entries for gather
2543 // sequences, and instead add additional edges to the tree representing
2544 // their uses. Since such an approach results in fewer total entries,
2545 // existing heuristics based on tree size may yeild different results.
2547 if (TE.NeedToGather &&
2548 std::any_of(std::next(VectorizableTree.begin(), I + 1),
2549 VectorizableTree.end(), [TE](TreeEntry &Entry) {
2550 return Entry.NeedToGather && Entry.isSame(TE.Scalars);
2552 continue;
2554 int C = getEntryCost(&TE);
2555 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
2556 << " for bundle that starts with " << *TE.Scalars[0]
2557 << ".\n");
2558 Cost += C;
2561 SmallPtrSet<Value *, 16> ExtractCostCalculated;
2562 int ExtractCost = 0;
2563 for (ExternalUser &EU : ExternalUses) {
2564 // We only add extract cost once for the same scalar.
2565 if (!ExtractCostCalculated.insert(EU.Scalar).second)
2566 continue;
2568 // Uses by ephemeral values are free (because the ephemeral value will be
2569 // removed prior to code generation, and so the extraction will be
2570 // removed as well).
2571 if (EphValues.count(EU.User))
2572 continue;
2574 // If we plan to rewrite the tree in a smaller type, we will need to sign
2575 // extend the extracted value back to the original type. Here, we account
2576 // for the extract and the added cost of the sign extend if needed.
2577 auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
2578 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2579 if (MinBWs.count(ScalarRoot)) {
2580 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2581 auto Extend =
2582 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2583 VecTy = VectorType::get(MinTy, BundleWidth);
2584 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2585 VecTy, EU.Lane);
2586 } else {
2587 ExtractCost +=
2588 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
2592 int SpillCost = getSpillCost();
2593 Cost += SpillCost + ExtractCost;
2595 std::string Str;
2597 raw_string_ostream OS(Str);
2598 OS << "SLP: Spill Cost = " << SpillCost << ".\n"
2599 << "SLP: Extract Cost = " << ExtractCost << ".\n"
2600 << "SLP: Total Cost = " << Cost << ".\n";
2602 LLVM_DEBUG(dbgs() << Str);
2604 if (ViewSLPTree)
2605 ViewGraph(this, "SLP" + F->getName(), false, Str);
2607 return Cost;
2610 int BoUpSLP::getGatherCost(Type *Ty,
2611 const DenseSet<unsigned> &ShuffledIndices) {
2612 int Cost = 0;
2613 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2614 if (!ShuffledIndices.count(i))
2615 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
2616 if (!ShuffledIndices.empty())
2617 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
2618 return Cost;
2621 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
2622 // Find the type of the operands in VL.
2623 Type *ScalarTy = VL[0]->getType();
2624 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2625 ScalarTy = SI->getValueOperand()->getType();
2626 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2627 // Find the cost of inserting/extracting values from the vector.
2628 // Check if the same elements are inserted several times and count them as
2629 // shuffle candidates.
2630 DenseSet<unsigned> ShuffledElements;
2631 DenseSet<Value *> UniqueElements;
2632 // Iterate in reverse order to consider insert elements with the high cost.
2633 for (unsigned I = VL.size(); I > 0; --I) {
2634 unsigned Idx = I - 1;
2635 if (!UniqueElements.insert(VL[Idx]).second)
2636 ShuffledElements.insert(Idx);
2638 return getGatherCost(VecTy, ShuffledElements);
2641 // Reorder commutative operations in alternate shuffle if the resulting vectors
2642 // are consecutive loads. This would allow us to vectorize the tree.
2643 // If we have something like-
2644 // load a[0] - load b[0]
2645 // load b[1] + load a[1]
2646 // load a[2] - load b[2]
2647 // load a[3] + load b[3]
2648 // Reordering the second load b[1] load a[1] would allow us to vectorize this
2649 // code.
2650 void BoUpSLP::reorderAltShuffleOperands(const InstructionsState &S,
2651 ArrayRef<Value *> VL,
2652 SmallVectorImpl<Value *> &Left,
2653 SmallVectorImpl<Value *> &Right) {
2654 // Push left and right operands of binary operation into Left and Right
2655 for (Value *V : VL) {
2656 auto *I = cast<Instruction>(V);
2657 assert(S.isOpcodeOrAlt(I) && "Incorrect instruction in vector");
2658 Left.push_back(I->getOperand(0));
2659 Right.push_back(I->getOperand(1));
2662 // Reorder if we have a commutative operation and consecutive access
2663 // are on either side of the alternate instructions.
2664 for (unsigned j = 0; j < VL.size() - 1; ++j) {
2665 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2666 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2667 Instruction *VL1 = cast<Instruction>(VL[j]);
2668 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2669 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2670 std::swap(Left[j], Right[j]);
2671 continue;
2672 } else if (VL2->isCommutative() &&
2673 isConsecutiveAccess(L, L1, *DL, *SE)) {
2674 std::swap(Left[j + 1], Right[j + 1]);
2675 continue;
2677 // else unchanged
2680 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2681 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2682 Instruction *VL1 = cast<Instruction>(VL[j]);
2683 Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2684 if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2685 std::swap(Left[j], Right[j]);
2686 continue;
2687 } else if (VL2->isCommutative() &&
2688 isConsecutiveAccess(L, L1, *DL, *SE)) {
2689 std::swap(Left[j + 1], Right[j + 1]);
2690 continue;
2692 // else unchanged
2698 // Return true if I should be commuted before adding it's left and right
2699 // operands to the arrays Left and Right.
2701 // The vectorizer is trying to either have all elements one side being
2702 // instruction with the same opcode to enable further vectorization, or having
2703 // a splat to lower the vectorizing cost.
2704 static bool shouldReorderOperands(
2705 int i, unsigned Opcode, Instruction &I, ArrayRef<Value *> Left,
2706 ArrayRef<Value *> Right, bool AllSameOpcodeLeft, bool AllSameOpcodeRight,
2707 bool SplatLeft, bool SplatRight, Value *&VLeft, Value *&VRight) {
2708 VLeft = I.getOperand(0);
2709 VRight = I.getOperand(1);
2710 // If we have "SplatRight", try to see if commuting is needed to preserve it.
2711 if (SplatRight) {
2712 if (VRight == Right[i - 1])
2713 // Preserve SplatRight
2714 return false;
2715 if (VLeft == Right[i - 1]) {
2716 // Commuting would preserve SplatRight, but we don't want to break
2717 // SplatLeft either, i.e. preserve the original order if possible.
2718 // (FIXME: why do we care?)
2719 if (SplatLeft && VLeft == Left[i - 1])
2720 return false;
2721 return true;
2724 // Symmetrically handle Right side.
2725 if (SplatLeft) {
2726 if (VLeft == Left[i - 1])
2727 // Preserve SplatLeft
2728 return false;
2729 if (VRight == Left[i - 1])
2730 return true;
2733 Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2734 Instruction *IRight = dyn_cast<Instruction>(VRight);
2736 // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2737 // it and not the right, in this case we want to commute.
2738 if (AllSameOpcodeRight) {
2739 unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2740 if (IRight && RightPrevOpcode == IRight->getOpcode())
2741 // Do not commute, a match on the right preserves AllSameOpcodeRight
2742 return false;
2743 if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2744 // We have a match and may want to commute, but first check if there is
2745 // not also a match on the existing operands on the Left to preserve
2746 // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2747 // (FIXME: why do we care?)
2748 if (AllSameOpcodeLeft && ILeft &&
2749 cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2750 return false;
2751 return true;
2754 // Symmetrically handle Left side.
2755 if (AllSameOpcodeLeft) {
2756 unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2757 if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2758 return false;
2759 if (IRight && LeftPrevOpcode == IRight->getOpcode())
2760 return true;
2762 return false;
2765 void BoUpSLP::reorderInputsAccordingToOpcode(unsigned Opcode,
2766 ArrayRef<Value *> VL,
2767 SmallVectorImpl<Value *> &Left,
2768 SmallVectorImpl<Value *> &Right) {
2769 if (!VL.empty()) {
2770 // Peel the first iteration out of the loop since there's nothing
2771 // interesting to do anyway and it simplifies the checks in the loop.
2772 auto *I = cast<Instruction>(VL[0]);
2773 Value *VLeft = I->getOperand(0);
2774 Value *VRight = I->getOperand(1);
2775 if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2776 // Favor having instruction to the right. FIXME: why?
2777 std::swap(VLeft, VRight);
2778 Left.push_back(VLeft);
2779 Right.push_back(VRight);
2782 // Keep track if we have instructions with all the same opcode on one side.
2783 bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2784 bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2785 // Keep track if we have one side with all the same value (broadcast).
2786 bool SplatLeft = true;
2787 bool SplatRight = true;
2789 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2790 Instruction *I = cast<Instruction>(VL[i]);
2791 assert(((I->getOpcode() == Opcode && I->isCommutative()) ||
2792 (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) &&
2793 "Can only process commutative instruction");
2794 // Commute to favor either a splat or maximizing having the same opcodes on
2795 // one side.
2796 Value *VLeft;
2797 Value *VRight;
2798 if (shouldReorderOperands(i, Opcode, *I, Left, Right, AllSameOpcodeLeft,
2799 AllSameOpcodeRight, SplatLeft, SplatRight, VLeft,
2800 VRight)) {
2801 Left.push_back(VRight);
2802 Right.push_back(VLeft);
2803 } else {
2804 Left.push_back(VLeft);
2805 Right.push_back(VRight);
2807 // Update Splat* and AllSameOpcode* after the insertion.
2808 SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2809 SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2810 AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2811 (cast<Instruction>(Left[i - 1])->getOpcode() ==
2812 cast<Instruction>(Left[i])->getOpcode());
2813 AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2814 (cast<Instruction>(Right[i - 1])->getOpcode() ==
2815 cast<Instruction>(Right[i])->getOpcode());
2818 // If one operand end up being broadcast, return this operand order.
2819 if (SplatRight || SplatLeft)
2820 return;
2822 // Finally check if we can get longer vectorizable chain by reordering
2823 // without breaking the good operand order detected above.
2824 // E.g. If we have something like-
2825 // load a[0] load b[0]
2826 // load b[1] load a[1]
2827 // load a[2] load b[2]
2828 // load a[3] load b[3]
2829 // Reordering the second load b[1] load a[1] would allow us to vectorize
2830 // this code and we still retain AllSameOpcode property.
2831 // FIXME: This load reordering might break AllSameOpcode in some rare cases
2832 // such as-
2833 // add a[0],c[0] load b[0]
2834 // add a[1],c[2] load b[1]
2835 // b[2] load b[2]
2836 // add a[3],c[3] load b[3]
2837 for (unsigned j = 0, e = VL.size() - 1; j < e; ++j) {
2838 if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2839 if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2840 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2841 std::swap(Left[j + 1], Right[j + 1]);
2842 continue;
2846 if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2847 if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2848 if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2849 std::swap(Left[j + 1], Right[j + 1]);
2850 continue;
2854 // else unchanged
2858 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL,
2859 const InstructionsState &S) {
2860 // Get the basic block this bundle is in. All instructions in the bundle
2861 // should be in this block.
2862 auto *Front = cast<Instruction>(S.OpValue);
2863 auto *BB = Front->getParent();
2864 assert(llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool {
2865 auto *I = cast<Instruction>(V);
2866 return !S.isOpcodeOrAlt(I) || I->getParent() == BB;
2867 }));
2869 // The last instruction in the bundle in program order.
2870 Instruction *LastInst = nullptr;
2872 // Find the last instruction. The common case should be that BB has been
2873 // scheduled, and the last instruction is VL.back(). So we start with
2874 // VL.back() and iterate over schedule data until we reach the end of the
2875 // bundle. The end of the bundle is marked by null ScheduleData.
2876 if (BlocksSchedules.count(BB)) {
2877 auto *Bundle =
2878 BlocksSchedules[BB]->getScheduleData(isOneOf(S, VL.back()));
2879 if (Bundle && Bundle->isPartOfBundle())
2880 for (; Bundle; Bundle = Bundle->NextInBundle)
2881 if (Bundle->OpValue == Bundle->Inst)
2882 LastInst = Bundle->Inst;
2885 // LastInst can still be null at this point if there's either not an entry
2886 // for BB in BlocksSchedules or there's no ScheduleData available for
2887 // VL.back(). This can be the case if buildTree_rec aborts for various
2888 // reasons (e.g., the maximum recursion depth is reached, the maximum region
2889 // size is reached, etc.). ScheduleData is initialized in the scheduling
2890 // "dry-run".
2892 // If this happens, we can still find the last instruction by brute force. We
2893 // iterate forwards from Front (inclusive) until we either see all
2894 // instructions in the bundle or reach the end of the block. If Front is the
2895 // last instruction in program order, LastInst will be set to Front, and we
2896 // will visit all the remaining instructions in the block.
2898 // One of the reasons we exit early from buildTree_rec is to place an upper
2899 // bound on compile-time. Thus, taking an additional compile-time hit here is
2900 // not ideal. However, this should be exceedingly rare since it requires that
2901 // we both exit early from buildTree_rec and that the bundle be out-of-order
2902 // (causing us to iterate all the way to the end of the block).
2903 if (!LastInst) {
2904 SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2905 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2906 if (Bundle.erase(&I) && S.isOpcodeOrAlt(&I))
2907 LastInst = &I;
2908 if (Bundle.empty())
2909 break;
2913 // Set the insertion point after the last instruction in the bundle. Set the
2914 // debug location to Front.
2915 Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2916 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2919 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2920 Value *Vec = UndefValue::get(Ty);
2921 // Generate the 'InsertElement' instruction.
2922 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2923 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2924 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2925 GatherSeq.insert(Insrt);
2926 CSEBlocks.insert(Insrt->getParent());
2928 // Add to our 'need-to-extract' list.
2929 if (TreeEntry *E = getTreeEntry(VL[i])) {
2930 // Find which lane we need to extract.
2931 int FoundLane = -1;
2932 for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
2933 // Is this the lane of the scalar that we are looking for ?
2934 if (E->Scalars[Lane] == VL[i]) {
2935 FoundLane = Lane;
2936 break;
2939 assert(FoundLane >= 0 && "Could not find the correct lane");
2940 if (!E->ReuseShuffleIndices.empty()) {
2941 FoundLane =
2942 std::distance(E->ReuseShuffleIndices.begin(),
2943 llvm::find(E->ReuseShuffleIndices, FoundLane));
2945 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2950 return Vec;
2953 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2954 InstructionsState S = getSameOpcode(VL);
2955 if (S.getOpcode()) {
2956 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2957 if (E->isSame(VL)) {
2958 Value *V = vectorizeTree(E);
2959 if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
2960 // We need to get the vectorized value but without shuffle.
2961 if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
2962 V = SV->getOperand(0);
2963 } else {
2964 // Reshuffle to get only unique values.
2965 SmallVector<unsigned, 4> UniqueIdxs;
2966 SmallSet<unsigned, 4> UsedIdxs;
2967 for(unsigned Idx : E->ReuseShuffleIndices)
2968 if (UsedIdxs.insert(Idx).second)
2969 UniqueIdxs.emplace_back(Idx);
2970 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
2971 UniqueIdxs);
2974 return V;
2979 Type *ScalarTy = S.OpValue->getType();
2980 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2981 ScalarTy = SI->getValueOperand()->getType();
2983 // Check that every instruction appears once in this bundle.
2984 SmallVector<unsigned, 4> ReuseShuffleIndicies;
2985 SmallVector<Value *, 4> UniqueValues;
2986 if (VL.size() > 2) {
2987 DenseMap<Value *, unsigned> UniquePositions;
2988 for (Value *V : VL) {
2989 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
2990 ReuseShuffleIndicies.emplace_back(Res.first->second);
2991 if (Res.second || isa<Constant>(V))
2992 UniqueValues.emplace_back(V);
2994 // Do not shuffle single element or if number of unique values is not power
2995 // of 2.
2996 if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
2997 !llvm::isPowerOf2_32(UniqueValues.size()))
2998 ReuseShuffleIndicies.clear();
2999 else
3000 VL = UniqueValues;
3002 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
3004 Value *V = Gather(VL, VecTy);
3005 if (!ReuseShuffleIndicies.empty()) {
3006 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3007 ReuseShuffleIndicies, "shuffle");
3008 if (auto *I = dyn_cast<Instruction>(V)) {
3009 GatherSeq.insert(I);
3010 CSEBlocks.insert(I->getParent());
3013 return V;
3016 static void inversePermutation(ArrayRef<unsigned> Indices,
3017 SmallVectorImpl<unsigned> &Mask) {
3018 Mask.clear();
3019 const unsigned E = Indices.size();
3020 Mask.resize(E);
3021 for (unsigned I = 0; I < E; ++I)
3022 Mask[Indices[I]] = I;
3025 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
3026 IRBuilder<>::InsertPointGuard Guard(Builder);
3028 if (E->VectorizedValue) {
3029 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
3030 return E->VectorizedValue;
3033 InstructionsState S = getSameOpcode(E->Scalars);
3034 Instruction *VL0 = cast<Instruction>(S.OpValue);
3035 Type *ScalarTy = VL0->getType();
3036 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
3037 ScalarTy = SI->getValueOperand()->getType();
3038 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
3040 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
3042 if (E->NeedToGather) {
3043 setInsertPointAfterBundle(E->Scalars, S);
3044 auto *V = Gather(E->Scalars, VecTy);
3045 if (NeedToShuffleReuses) {
3046 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3047 E->ReuseShuffleIndices, "shuffle");
3048 if (auto *I = dyn_cast<Instruction>(V)) {
3049 GatherSeq.insert(I);
3050 CSEBlocks.insert(I->getParent());
3053 E->VectorizedValue = V;
3054 return V;
3057 unsigned ShuffleOrOp = S.isAltShuffle() ?
3058 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3059 switch (ShuffleOrOp) {
3060 case Instruction::PHI: {
3061 PHINode *PH = dyn_cast<PHINode>(VL0);
3062 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
3063 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3064 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
3065 Value *V = NewPhi;
3066 if (NeedToShuffleReuses) {
3067 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3068 E->ReuseShuffleIndices, "shuffle");
3070 E->VectorizedValue = V;
3072 // PHINodes may have multiple entries from the same block. We want to
3073 // visit every block once.
3074 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
3076 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
3077 ValueList Operands;
3078 BasicBlock *IBB = PH->getIncomingBlock(i);
3080 if (!VisitedBBs.insert(IBB).second) {
3081 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
3082 continue;
3085 // Prepare the operand vector.
3086 for (Value *V : E->Scalars)
3087 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
3089 Builder.SetInsertPoint(IBB->getTerminator());
3090 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3091 Value *Vec = vectorizeTree(Operands);
3092 NewPhi->addIncoming(Vec, IBB);
3095 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
3096 "Invalid number of incoming values");
3097 return V;
3100 case Instruction::ExtractElement: {
3101 if (!E->NeedToGather) {
3102 Value *V = VL0->getOperand(0);
3103 if (!E->ReorderIndices.empty()) {
3104 OrdersType Mask;
3105 inversePermutation(E->ReorderIndices, Mask);
3106 Builder.SetInsertPoint(VL0);
3107 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask,
3108 "reorder_shuffle");
3110 if (NeedToShuffleReuses) {
3111 // TODO: Merge this shuffle with the ReorderShuffleMask.
3112 if (E->ReorderIndices.empty())
3113 Builder.SetInsertPoint(VL0);
3114 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3115 E->ReuseShuffleIndices, "shuffle");
3117 E->VectorizedValue = V;
3118 return V;
3120 setInsertPointAfterBundle(E->Scalars, S);
3121 auto *V = Gather(E->Scalars, VecTy);
3122 if (NeedToShuffleReuses) {
3123 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3124 E->ReuseShuffleIndices, "shuffle");
3125 if (auto *I = dyn_cast<Instruction>(V)) {
3126 GatherSeq.insert(I);
3127 CSEBlocks.insert(I->getParent());
3130 E->VectorizedValue = V;
3131 return V;
3133 case Instruction::ExtractValue: {
3134 if (!E->NeedToGather) {
3135 LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
3136 Builder.SetInsertPoint(LI);
3137 PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
3138 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
3139 LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
3140 Value *NewV = propagateMetadata(V, E->Scalars);
3141 if (!E->ReorderIndices.empty()) {
3142 OrdersType Mask;
3143 inversePermutation(E->ReorderIndices, Mask);
3144 NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask,
3145 "reorder_shuffle");
3147 if (NeedToShuffleReuses) {
3148 // TODO: Merge this shuffle with the ReorderShuffleMask.
3149 NewV = Builder.CreateShuffleVector(
3150 NewV, UndefValue::get(VecTy), E->ReuseShuffleIndices, "shuffle");
3152 E->VectorizedValue = NewV;
3153 return NewV;
3155 setInsertPointAfterBundle(E->Scalars, S);
3156 auto *V = Gather(E->Scalars, VecTy);
3157 if (NeedToShuffleReuses) {
3158 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3159 E->ReuseShuffleIndices, "shuffle");
3160 if (auto *I = dyn_cast<Instruction>(V)) {
3161 GatherSeq.insert(I);
3162 CSEBlocks.insert(I->getParent());
3165 E->VectorizedValue = V;
3166 return V;
3168 case Instruction::ZExt:
3169 case Instruction::SExt:
3170 case Instruction::FPToUI:
3171 case Instruction::FPToSI:
3172 case Instruction::FPExt:
3173 case Instruction::PtrToInt:
3174 case Instruction::IntToPtr:
3175 case Instruction::SIToFP:
3176 case Instruction::UIToFP:
3177 case Instruction::Trunc:
3178 case Instruction::FPTrunc:
3179 case Instruction::BitCast: {
3180 ValueList INVL;
3181 for (Value *V : E->Scalars)
3182 INVL.push_back(cast<Instruction>(V)->getOperand(0));
3184 setInsertPointAfterBundle(E->Scalars, S);
3186 Value *InVec = vectorizeTree(INVL);
3188 if (E->VectorizedValue) {
3189 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3190 return E->VectorizedValue;
3193 CastInst *CI = dyn_cast<CastInst>(VL0);
3194 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
3195 if (NeedToShuffleReuses) {
3196 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3197 E->ReuseShuffleIndices, "shuffle");
3199 E->VectorizedValue = V;
3200 ++NumVectorInstructions;
3201 return V;
3203 case Instruction::FCmp:
3204 case Instruction::ICmp: {
3205 ValueList LHSV, RHSV;
3206 for (Value *V : E->Scalars) {
3207 LHSV.push_back(cast<Instruction>(V)->getOperand(0));
3208 RHSV.push_back(cast<Instruction>(V)->getOperand(1));
3211 setInsertPointAfterBundle(E->Scalars, S);
3213 Value *L = vectorizeTree(LHSV);
3214 Value *R = vectorizeTree(RHSV);
3216 if (E->VectorizedValue) {
3217 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3218 return E->VectorizedValue;
3221 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3222 Value *V;
3223 if (S.getOpcode() == Instruction::FCmp)
3224 V = Builder.CreateFCmp(P0, L, R);
3225 else
3226 V = Builder.CreateICmp(P0, L, R);
3228 propagateIRFlags(V, E->Scalars, VL0);
3229 if (NeedToShuffleReuses) {
3230 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3231 E->ReuseShuffleIndices, "shuffle");
3233 E->VectorizedValue = V;
3234 ++NumVectorInstructions;
3235 return V;
3237 case Instruction::Select: {
3238 ValueList TrueVec, FalseVec, CondVec;
3239 for (Value *V : E->Scalars) {
3240 CondVec.push_back(cast<Instruction>(V)->getOperand(0));
3241 TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
3242 FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
3245 setInsertPointAfterBundle(E->Scalars, S);
3247 Value *Cond = vectorizeTree(CondVec);
3248 Value *True = vectorizeTree(TrueVec);
3249 Value *False = vectorizeTree(FalseVec);
3251 if (E->VectorizedValue) {
3252 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3253 return E->VectorizedValue;
3256 Value *V = Builder.CreateSelect(Cond, True, False);
3257 if (NeedToShuffleReuses) {
3258 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3259 E->ReuseShuffleIndices, "shuffle");
3261 E->VectorizedValue = V;
3262 ++NumVectorInstructions;
3263 return V;
3265 case Instruction::Add:
3266 case Instruction::FAdd:
3267 case Instruction::Sub:
3268 case Instruction::FSub:
3269 case Instruction::Mul:
3270 case Instruction::FMul:
3271 case Instruction::UDiv:
3272 case Instruction::SDiv:
3273 case Instruction::FDiv:
3274 case Instruction::URem:
3275 case Instruction::SRem:
3276 case Instruction::FRem:
3277 case Instruction::Shl:
3278 case Instruction::LShr:
3279 case Instruction::AShr:
3280 case Instruction::And:
3281 case Instruction::Or:
3282 case Instruction::Xor: {
3283 ValueList LHSVL, RHSVL;
3284 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
3285 reorderInputsAccordingToOpcode(S.getOpcode(), E->Scalars, LHSVL,
3286 RHSVL);
3287 else
3288 for (Value *V : E->Scalars) {
3289 auto *I = cast<Instruction>(V);
3290 LHSVL.push_back(I->getOperand(0));
3291 RHSVL.push_back(I->getOperand(1));
3294 setInsertPointAfterBundle(E->Scalars, S);
3296 Value *LHS = vectorizeTree(LHSVL);
3297 Value *RHS = vectorizeTree(RHSVL);
3299 if (E->VectorizedValue) {
3300 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3301 return E->VectorizedValue;
3304 Value *V = Builder.CreateBinOp(
3305 static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
3306 propagateIRFlags(V, E->Scalars, VL0);
3307 if (auto *I = dyn_cast<Instruction>(V))
3308 V = propagateMetadata(I, E->Scalars);
3310 if (NeedToShuffleReuses) {
3311 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3312 E->ReuseShuffleIndices, "shuffle");
3314 E->VectorizedValue = V;
3315 ++NumVectorInstructions;
3317 return V;
3319 case Instruction::Load: {
3320 // Loads are inserted at the head of the tree because we don't want to
3321 // sink them all the way down past store instructions.
3322 bool IsReorder = !E->ReorderIndices.empty();
3323 if (IsReorder) {
3324 S = getSameOpcode(E->Scalars, E->ReorderIndices.front());
3325 VL0 = cast<Instruction>(S.OpValue);
3327 setInsertPointAfterBundle(E->Scalars, S);
3329 LoadInst *LI = cast<LoadInst>(VL0);
3330 Type *ScalarLoadTy = LI->getType();
3331 unsigned AS = LI->getPointerAddressSpace();
3333 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
3334 VecTy->getPointerTo(AS));
3336 // The pointer operand uses an in-tree scalar so we add the new BitCast to
3337 // ExternalUses list to make sure that an extract will be generated in the
3338 // future.
3339 Value *PO = LI->getPointerOperand();
3340 if (getTreeEntry(PO))
3341 ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
3343 unsigned Alignment = LI->getAlignment();
3344 LI = Builder.CreateLoad(VecPtr);
3345 if (!Alignment) {
3346 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
3348 LI->setAlignment(Alignment);
3349 Value *V = propagateMetadata(LI, E->Scalars);
3350 if (IsReorder) {
3351 OrdersType Mask;
3352 inversePermutation(E->ReorderIndices, Mask);
3353 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
3354 Mask, "reorder_shuffle");
3356 if (NeedToShuffleReuses) {
3357 // TODO: Merge this shuffle with the ReorderShuffleMask.
3358 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3359 E->ReuseShuffleIndices, "shuffle");
3361 E->VectorizedValue = V;
3362 ++NumVectorInstructions;
3363 return V;
3365 case Instruction::Store: {
3366 StoreInst *SI = cast<StoreInst>(VL0);
3367 unsigned Alignment = SI->getAlignment();
3368 unsigned AS = SI->getPointerAddressSpace();
3370 ValueList ScalarStoreValues;
3371 for (Value *V : E->Scalars)
3372 ScalarStoreValues.push_back(cast<StoreInst>(V)->getValueOperand());
3374 setInsertPointAfterBundle(E->Scalars, S);
3376 Value *VecValue = vectorizeTree(ScalarStoreValues);
3377 Value *ScalarPtr = SI->getPointerOperand();
3378 Value *VecPtr = Builder.CreateBitCast(ScalarPtr, VecTy->getPointerTo(AS));
3379 StoreInst *ST = Builder.CreateStore(VecValue, VecPtr);
3381 // The pointer operand uses an in-tree scalar, so add the new BitCast to
3382 // ExternalUses to make sure that an extract will be generated in the
3383 // future.
3384 if (getTreeEntry(ScalarPtr))
3385 ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
3387 if (!Alignment)
3388 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
3390 ST->setAlignment(Alignment);
3391 Value *V = propagateMetadata(ST, E->Scalars);
3392 if (NeedToShuffleReuses) {
3393 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3394 E->ReuseShuffleIndices, "shuffle");
3396 E->VectorizedValue = V;
3397 ++NumVectorInstructions;
3398 return V;
3400 case Instruction::GetElementPtr: {
3401 setInsertPointAfterBundle(E->Scalars, S);
3403 ValueList Op0VL;
3404 for (Value *V : E->Scalars)
3405 Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
3407 Value *Op0 = vectorizeTree(Op0VL);
3409 std::vector<Value *> OpVecs;
3410 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
3411 ++j) {
3412 ValueList OpVL;
3413 for (Value *V : E->Scalars)
3414 OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
3416 Value *OpVec = vectorizeTree(OpVL);
3417 OpVecs.push_back(OpVec);
3420 Value *V = Builder.CreateGEP(
3421 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
3422 if (Instruction *I = dyn_cast<Instruction>(V))
3423 V = propagateMetadata(I, E->Scalars);
3425 if (NeedToShuffleReuses) {
3426 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3427 E->ReuseShuffleIndices, "shuffle");
3429 E->VectorizedValue = V;
3430 ++NumVectorInstructions;
3432 return V;
3434 case Instruction::Call: {
3435 CallInst *CI = cast<CallInst>(VL0);
3436 setInsertPointAfterBundle(E->Scalars, S);
3437 Function *FI;
3438 Intrinsic::ID IID = Intrinsic::not_intrinsic;
3439 Value *ScalarArg = nullptr;
3440 if (CI && (FI = CI->getCalledFunction())) {
3441 IID = FI->getIntrinsicID();
3443 std::vector<Value *> OpVecs;
3444 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
3445 ValueList OpVL;
3446 // ctlz,cttz and powi are special intrinsics whose second argument is
3447 // a scalar. This argument should not be vectorized.
3448 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
3449 CallInst *CEI = cast<CallInst>(VL0);
3450 ScalarArg = CEI->getArgOperand(j);
3451 OpVecs.push_back(CEI->getArgOperand(j));
3452 continue;
3454 for (Value *V : E->Scalars) {
3455 CallInst *CEI = cast<CallInst>(V);
3456 OpVL.push_back(CEI->getArgOperand(j));
3459 Value *OpVec = vectorizeTree(OpVL);
3460 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
3461 OpVecs.push_back(OpVec);
3464 Module *M = F->getParent();
3465 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3466 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
3467 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
3468 SmallVector<OperandBundleDef, 1> OpBundles;
3469 CI->getOperandBundlesAsDefs(OpBundles);
3470 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
3472 // The scalar argument uses an in-tree scalar so we add the new vectorized
3473 // call to ExternalUses list to make sure that an extract will be
3474 // generated in the future.
3475 if (ScalarArg && getTreeEntry(ScalarArg))
3476 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
3478 propagateIRFlags(V, E->Scalars, VL0);
3479 if (NeedToShuffleReuses) {
3480 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3481 E->ReuseShuffleIndices, "shuffle");
3483 E->VectorizedValue = V;
3484 ++NumVectorInstructions;
3485 return V;
3487 case Instruction::ShuffleVector: {
3488 ValueList LHSVL, RHSVL;
3489 assert(S.isAltShuffle() &&
3490 ((Instruction::isBinaryOp(S.getOpcode()) &&
3491 Instruction::isBinaryOp(S.getAltOpcode())) ||
3492 (Instruction::isCast(S.getOpcode()) &&
3493 Instruction::isCast(S.getAltOpcode()))) &&
3494 "Invalid Shuffle Vector Operand");
3496 Value *LHS, *RHS;
3497 if (Instruction::isBinaryOp(S.getOpcode())) {
3498 reorderAltShuffleOperands(S, E->Scalars, LHSVL, RHSVL);
3499 setInsertPointAfterBundle(E->Scalars, S);
3500 LHS = vectorizeTree(LHSVL);
3501 RHS = vectorizeTree(RHSVL);
3502 } else {
3503 ValueList INVL;
3504 for (Value *V : E->Scalars)
3505 INVL.push_back(cast<Instruction>(V)->getOperand(0));
3506 setInsertPointAfterBundle(E->Scalars, S);
3507 LHS = vectorizeTree(INVL);
3510 if (E->VectorizedValue) {
3511 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3512 return E->VectorizedValue;
3515 Value *V0, *V1;
3516 if (Instruction::isBinaryOp(S.getOpcode())) {
3517 V0 = Builder.CreateBinOp(
3518 static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
3519 V1 = Builder.CreateBinOp(
3520 static_cast<Instruction::BinaryOps>(S.getAltOpcode()), LHS, RHS);
3521 } else {
3522 V0 = Builder.CreateCast(
3523 static_cast<Instruction::CastOps>(S.getOpcode()), LHS, VecTy);
3524 V1 = Builder.CreateCast(
3525 static_cast<Instruction::CastOps>(S.getAltOpcode()), LHS, VecTy);
3528 // Create shuffle to take alternate operations from the vector.
3529 // Also, gather up main and alt scalar ops to propagate IR flags to
3530 // each vector operation.
3531 ValueList OpScalars, AltScalars;
3532 unsigned e = E->Scalars.size();
3533 SmallVector<Constant *, 8> Mask(e);
3534 for (unsigned i = 0; i < e; ++i) {
3535 auto *OpInst = cast<Instruction>(E->Scalars[i]);
3536 assert(S.isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
3537 if (OpInst->getOpcode() == S.getAltOpcode()) {
3538 Mask[i] = Builder.getInt32(e + i);
3539 AltScalars.push_back(E->Scalars[i]);
3540 } else {
3541 Mask[i] = Builder.getInt32(i);
3542 OpScalars.push_back(E->Scalars[i]);
3546 Value *ShuffleMask = ConstantVector::get(Mask);
3547 propagateIRFlags(V0, OpScalars);
3548 propagateIRFlags(V1, AltScalars);
3550 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
3551 if (Instruction *I = dyn_cast<Instruction>(V))
3552 V = propagateMetadata(I, E->Scalars);
3553 if (NeedToShuffleReuses) {
3554 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3555 E->ReuseShuffleIndices, "shuffle");
3557 E->VectorizedValue = V;
3558 ++NumVectorInstructions;
3560 return V;
3562 default:
3563 llvm_unreachable("unknown inst");
3565 return nullptr;
3568 Value *BoUpSLP::vectorizeTree() {
3569 ExtraValueToDebugLocsMap ExternallyUsedValues;
3570 return vectorizeTree(ExternallyUsedValues);
3573 Value *
3574 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3575 // All blocks must be scheduled before any instructions are inserted.
3576 for (auto &BSIter : BlocksSchedules) {
3577 scheduleBlock(BSIter.second.get());
3580 Builder.SetInsertPoint(&F->getEntryBlock().front());
3581 auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
3583 // If the vectorized tree can be rewritten in a smaller type, we truncate the
3584 // vectorized root. InstCombine will then rewrite the entire expression. We
3585 // sign extend the extracted values below.
3586 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
3587 if (MinBWs.count(ScalarRoot)) {
3588 if (auto *I = dyn_cast<Instruction>(VectorRoot))
3589 Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
3590 auto BundleWidth = VectorizableTree[0].Scalars.size();
3591 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3592 auto *VecTy = VectorType::get(MinTy, BundleWidth);
3593 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
3594 VectorizableTree[0].VectorizedValue = Trunc;
3597 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
3598 << " values .\n");
3600 // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
3601 // specified by ScalarType.
3602 auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
3603 if (!MinBWs.count(ScalarRoot))
3604 return Ex;
3605 if (MinBWs[ScalarRoot].second)
3606 return Builder.CreateSExt(Ex, ScalarType);
3607 return Builder.CreateZExt(Ex, ScalarType);
3610 // Extract all of the elements with the external uses.
3611 for (const auto &ExternalUse : ExternalUses) {
3612 Value *Scalar = ExternalUse.Scalar;
3613 llvm::User *User = ExternalUse.User;
3615 // Skip users that we already RAUW. This happens when one instruction
3616 // has multiple uses of the same value.
3617 if (User && !is_contained(Scalar->users(), User))
3618 continue;
3619 TreeEntry *E = getTreeEntry(Scalar);
3620 assert(E && "Invalid scalar");
3621 assert(!E->NeedToGather && "Extracting from a gather list");
3623 Value *Vec = E->VectorizedValue;
3624 assert(Vec && "Can't find vectorizable value");
3626 Value *Lane = Builder.getInt32(ExternalUse.Lane);
3627 // If User == nullptr, the Scalar is used as extra arg. Generate
3628 // ExtractElement instruction and update the record for this scalar in
3629 // ExternallyUsedValues.
3630 if (!User) {
3631 assert(ExternallyUsedValues.count(Scalar) &&
3632 "Scalar with nullptr as an external user must be registered in "
3633 "ExternallyUsedValues map");
3634 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3635 Builder.SetInsertPoint(VecI->getParent(),
3636 std::next(VecI->getIterator()));
3637 } else {
3638 Builder.SetInsertPoint(&F->getEntryBlock().front());
3640 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3641 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3642 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
3643 auto &Locs = ExternallyUsedValues[Scalar];
3644 ExternallyUsedValues.insert({Ex, Locs});
3645 ExternallyUsedValues.erase(Scalar);
3646 continue;
3649 // Generate extracts for out-of-tree users.
3650 // Find the insertion point for the extractelement lane.
3651 if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3652 if (PHINode *PH = dyn_cast<PHINode>(User)) {
3653 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
3654 if (PH->getIncomingValue(i) == Scalar) {
3655 TerminatorInst *IncomingTerminator =
3656 PH->getIncomingBlock(i)->getTerminator();
3657 if (isa<CatchSwitchInst>(IncomingTerminator)) {
3658 Builder.SetInsertPoint(VecI->getParent(),
3659 std::next(VecI->getIterator()));
3660 } else {
3661 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
3663 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3664 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3665 CSEBlocks.insert(PH->getIncomingBlock(i));
3666 PH->setOperand(i, Ex);
3669 } else {
3670 Builder.SetInsertPoint(cast<Instruction>(User));
3671 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3672 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3673 CSEBlocks.insert(cast<Instruction>(User)->getParent());
3674 User->replaceUsesOfWith(Scalar, Ex);
3676 } else {
3677 Builder.SetInsertPoint(&F->getEntryBlock().front());
3678 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3679 Ex = extend(ScalarRoot, Ex, Scalar->getType());
3680 CSEBlocks.insert(&F->getEntryBlock());
3681 User->replaceUsesOfWith(Scalar, Ex);
3684 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
3687 // For each vectorized value:
3688 for (TreeEntry &EIdx : VectorizableTree) {
3689 TreeEntry *Entry = &EIdx;
3691 // No need to handle users of gathered values.
3692 if (Entry->NeedToGather)
3693 continue;
3695 assert(Entry->VectorizedValue && "Can't find vectorizable value");
3697 // For each lane:
3698 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3699 Value *Scalar = Entry->Scalars[Lane];
3701 Type *Ty = Scalar->getType();
3702 if (!Ty->isVoidTy()) {
3703 #ifndef NDEBUG
3704 for (User *U : Scalar->users()) {
3705 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
3707 // It is legal to replace users in the ignorelist by undef.
3708 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
3709 "Replacing out-of-tree value with undef");
3711 #endif
3712 Value *Undef = UndefValue::get(Ty);
3713 Scalar->replaceAllUsesWith(Undef);
3715 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
3716 eraseInstruction(cast<Instruction>(Scalar));
3720 Builder.ClearInsertionPoint();
3722 return VectorizableTree[0].VectorizedValue;
3725 void BoUpSLP::optimizeGatherSequence() {
3726 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
3727 << " gather sequences instructions.\n");
3728 // LICM InsertElementInst sequences.
3729 for (Instruction *I : GatherSeq) {
3730 if (!isa<InsertElementInst>(I) && !isa<ShuffleVectorInst>(I))
3731 continue;
3733 // Check if this block is inside a loop.
3734 Loop *L = LI->getLoopFor(I->getParent());
3735 if (!L)
3736 continue;
3738 // Check if it has a preheader.
3739 BasicBlock *PreHeader = L->getLoopPreheader();
3740 if (!PreHeader)
3741 continue;
3743 // If the vector or the element that we insert into it are
3744 // instructions that are defined in this basic block then we can't
3745 // hoist this instruction.
3746 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
3747 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
3748 if (Op0 && L->contains(Op0))
3749 continue;
3750 if (Op1 && L->contains(Op1))
3751 continue;
3753 // We can hoist this instruction. Move it to the pre-header.
3754 I->moveBefore(PreHeader->getTerminator());
3757 // Make a list of all reachable blocks in our CSE queue.
3758 SmallVector<const DomTreeNode *, 8> CSEWorkList;
3759 CSEWorkList.reserve(CSEBlocks.size());
3760 for (BasicBlock *BB : CSEBlocks)
3761 if (DomTreeNode *N = DT->getNode(BB)) {
3762 assert(DT->isReachableFromEntry(N));
3763 CSEWorkList.push_back(N);
3766 // Sort blocks by domination. This ensures we visit a block after all blocks
3767 // dominating it are visited.
3768 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
3769 [this](const DomTreeNode *A, const DomTreeNode *B) {
3770 return DT->properlyDominates(A, B);
3773 // Perform O(N^2) search over the gather sequences and merge identical
3774 // instructions. TODO: We can further optimize this scan if we split the
3775 // instructions into different buckets based on the insert lane.
3776 SmallVector<Instruction *, 16> Visited;
3777 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
3778 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
3779 "Worklist not sorted properly!");
3780 BasicBlock *BB = (*I)->getBlock();
3781 // For all instructions in blocks containing gather sequences:
3782 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
3783 Instruction *In = &*it++;
3784 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3785 continue;
3787 // Check if we can replace this instruction with any of the
3788 // visited instructions.
3789 for (Instruction *v : Visited) {
3790 if (In->isIdenticalTo(v) &&
3791 DT->dominates(v->getParent(), In->getParent())) {
3792 In->replaceAllUsesWith(v);
3793 eraseInstruction(In);
3794 In = nullptr;
3795 break;
3798 if (In) {
3799 assert(!is_contained(Visited, In));
3800 Visited.push_back(In);
3804 CSEBlocks.clear();
3805 GatherSeq.clear();
3808 // Groups the instructions to a bundle (which is then a single scheduling entity)
3809 // and schedules instructions until the bundle gets ready.
3810 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
3811 BoUpSLP *SLP,
3812 const InstructionsState &S) {
3813 if (isa<PHINode>(S.OpValue))
3814 return true;
3816 // Initialize the instruction bundle.
3817 Instruction *OldScheduleEnd = ScheduleEnd;
3818 ScheduleData *PrevInBundle = nullptr;
3819 ScheduleData *Bundle = nullptr;
3820 bool ReSchedule = false;
3821 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n");
3823 // Make sure that the scheduling region contains all
3824 // instructions of the bundle.
3825 for (Value *V : VL) {
3826 if (!extendSchedulingRegion(V, S))
3827 return false;
3830 for (Value *V : VL) {
3831 ScheduleData *BundleMember = getScheduleData(V);
3832 assert(BundleMember &&
3833 "no ScheduleData for bundle member (maybe not in same basic block)");
3834 if (BundleMember->IsScheduled) {
3835 // A bundle member was scheduled as single instruction before and now
3836 // needs to be scheduled as part of the bundle. We just get rid of the
3837 // existing schedule.
3838 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
3839 << " was already scheduled\n");
3840 ReSchedule = true;
3842 assert(BundleMember->isSchedulingEntity() &&
3843 "bundle member already part of other bundle");
3844 if (PrevInBundle) {
3845 PrevInBundle->NextInBundle = BundleMember;
3846 } else {
3847 Bundle = BundleMember;
3849 BundleMember->UnscheduledDepsInBundle = 0;
3850 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3852 // Group the instructions to a bundle.
3853 BundleMember->FirstInBundle = Bundle;
3854 PrevInBundle = BundleMember;
3856 if (ScheduleEnd != OldScheduleEnd) {
3857 // The scheduling region got new instructions at the lower end (or it is a
3858 // new region for the first bundle). This makes it necessary to
3859 // recalculate all dependencies.
3860 // It is seldom that this needs to be done a second time after adding the
3861 // initial bundle to the region.
3862 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3863 doForAllOpcodes(I, [](ScheduleData *SD) {
3864 SD->clearDependencies();
3867 ReSchedule = true;
3869 if (ReSchedule) {
3870 resetSchedule();
3871 initialFillReadyList(ReadyInsts);
3874 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
3875 << BB->getName() << "\n");
3877 calculateDependencies(Bundle, true, SLP);
3879 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
3880 // means that there are no cyclic dependencies and we can schedule it.
3881 // Note that's important that we don't "schedule" the bundle yet (see
3882 // cancelScheduling).
3883 while (!Bundle->isReady() && !ReadyInsts.empty()) {
3885 ScheduleData *pickedSD = ReadyInsts.back();
3886 ReadyInsts.pop_back();
3888 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3889 schedule(pickedSD, ReadyInsts);
3892 if (!Bundle->isReady()) {
3893 cancelScheduling(VL, S.OpValue);
3894 return false;
3896 return true;
3899 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
3900 Value *OpValue) {
3901 if (isa<PHINode>(OpValue))
3902 return;
3904 ScheduleData *Bundle = getScheduleData(OpValue);
3905 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
3906 assert(!Bundle->IsScheduled &&
3907 "Can't cancel bundle which is already scheduled");
3908 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3909 "tried to unbundle something which is not a bundle");
3911 // Un-bundle: make single instructions out of the bundle.
3912 ScheduleData *BundleMember = Bundle;
3913 while (BundleMember) {
3914 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3915 BundleMember->FirstInBundle = BundleMember;
3916 ScheduleData *Next = BundleMember->NextInBundle;
3917 BundleMember->NextInBundle = nullptr;
3918 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3919 if (BundleMember->UnscheduledDepsInBundle == 0) {
3920 ReadyInsts.insert(BundleMember);
3922 BundleMember = Next;
3926 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
3927 // Allocate a new ScheduleData for the instruction.
3928 if (ChunkPos >= ChunkSize) {
3929 ScheduleDataChunks.push_back(llvm::make_unique<ScheduleData[]>(ChunkSize));
3930 ChunkPos = 0;
3932 return &(ScheduleDataChunks.back()[ChunkPos++]);
3935 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
3936 const InstructionsState &S) {
3937 if (getScheduleData(V, isOneOf(S, V)))
3938 return true;
3939 Instruction *I = dyn_cast<Instruction>(V);
3940 assert(I && "bundle member must be an instruction");
3941 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3942 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
3943 ScheduleData *ISD = getScheduleData(I);
3944 if (!ISD)
3945 return false;
3946 assert(isInSchedulingRegion(ISD) &&
3947 "ScheduleData not in scheduling region");
3948 ScheduleData *SD = allocateScheduleDataChunks();
3949 SD->Inst = I;
3950 SD->init(SchedulingRegionID, S.OpValue);
3951 ExtraScheduleDataMap[I][S.OpValue] = SD;
3952 return true;
3954 if (CheckSheduleForI(I))
3955 return true;
3956 if (!ScheduleStart) {
3957 // It's the first instruction in the new region.
3958 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3959 ScheduleStart = I;
3960 ScheduleEnd = I->getNextNode();
3961 if (isOneOf(S, I) != I)
3962 CheckSheduleForI(I);
3963 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3964 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
3965 return true;
3967 // Search up and down at the same time, because we don't know if the new
3968 // instruction is above or below the existing scheduling region.
3969 BasicBlock::reverse_iterator UpIter =
3970 ++ScheduleStart->getIterator().getReverse();
3971 BasicBlock::reverse_iterator UpperEnd = BB->rend();
3972 BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3973 BasicBlock::iterator LowerEnd = BB->end();
3974 while (true) {
3975 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3976 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
3977 return false;
3980 if (UpIter != UpperEnd) {
3981 if (&*UpIter == I) {
3982 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3983 ScheduleStart = I;
3984 if (isOneOf(S, I) != I)
3985 CheckSheduleForI(I);
3986 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I
3987 << "\n");
3988 return true;
3990 UpIter++;
3992 if (DownIter != LowerEnd) {
3993 if (&*DownIter == I) {
3994 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3995 nullptr);
3996 ScheduleEnd = I->getNextNode();
3997 if (isOneOf(S, I) != I)
3998 CheckSheduleForI(I);
3999 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
4000 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I
4001 << "\n");
4002 return true;
4004 DownIter++;
4006 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
4007 "instruction not found in block");
4009 return true;
4012 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
4013 Instruction *ToI,
4014 ScheduleData *PrevLoadStore,
4015 ScheduleData *NextLoadStore) {
4016 ScheduleData *CurrentLoadStore = PrevLoadStore;
4017 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
4018 ScheduleData *SD = ScheduleDataMap[I];
4019 if (!SD) {
4020 SD = allocateScheduleDataChunks();
4021 ScheduleDataMap[I] = SD;
4022 SD->Inst = I;
4024 assert(!isInSchedulingRegion(SD) &&
4025 "new ScheduleData already in scheduling region");
4026 SD->init(SchedulingRegionID, I);
4028 if (I->mayReadOrWriteMemory() &&
4029 (!isa<IntrinsicInst>(I) ||
4030 cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
4031 // Update the linked list of memory accessing instructions.
4032 if (CurrentLoadStore) {
4033 CurrentLoadStore->NextLoadStore = SD;
4034 } else {
4035 FirstLoadStoreInRegion = SD;
4037 CurrentLoadStore = SD;
4040 if (NextLoadStore) {
4041 if (CurrentLoadStore)
4042 CurrentLoadStore->NextLoadStore = NextLoadStore;
4043 } else {
4044 LastLoadStoreInRegion = CurrentLoadStore;
4048 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
4049 bool InsertInReadyList,
4050 BoUpSLP *SLP) {
4051 assert(SD->isSchedulingEntity());
4053 SmallVector<ScheduleData *, 10> WorkList;
4054 WorkList.push_back(SD);
4056 while (!WorkList.empty()) {
4057 ScheduleData *SD = WorkList.back();
4058 WorkList.pop_back();
4060 ScheduleData *BundleMember = SD;
4061 while (BundleMember) {
4062 assert(isInSchedulingRegion(BundleMember));
4063 if (!BundleMember->hasValidDependencies()) {
4065 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember
4066 << "\n");
4067 BundleMember->Dependencies = 0;
4068 BundleMember->resetUnscheduledDeps();
4070 // Handle def-use chain dependencies.
4071 if (BundleMember->OpValue != BundleMember->Inst) {
4072 ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
4073 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4074 BundleMember->Dependencies++;
4075 ScheduleData *DestBundle = UseSD->FirstInBundle;
4076 if (!DestBundle->IsScheduled)
4077 BundleMember->incrementUnscheduledDeps(1);
4078 if (!DestBundle->hasValidDependencies())
4079 WorkList.push_back(DestBundle);
4081 } else {
4082 for (User *U : BundleMember->Inst->users()) {
4083 if (isa<Instruction>(U)) {
4084 ScheduleData *UseSD = getScheduleData(U);
4085 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4086 BundleMember->Dependencies++;
4087 ScheduleData *DestBundle = UseSD->FirstInBundle;
4088 if (!DestBundle->IsScheduled)
4089 BundleMember->incrementUnscheduledDeps(1);
4090 if (!DestBundle->hasValidDependencies())
4091 WorkList.push_back(DestBundle);
4093 } else {
4094 // I'm not sure if this can ever happen. But we need to be safe.
4095 // This lets the instruction/bundle never be scheduled and
4096 // eventually disable vectorization.
4097 BundleMember->Dependencies++;
4098 BundleMember->incrementUnscheduledDeps(1);
4103 // Handle the memory dependencies.
4104 ScheduleData *DepDest = BundleMember->NextLoadStore;
4105 if (DepDest) {
4106 Instruction *SrcInst = BundleMember->Inst;
4107 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
4108 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
4109 unsigned numAliased = 0;
4110 unsigned DistToSrc = 1;
4112 while (DepDest) {
4113 assert(isInSchedulingRegion(DepDest));
4115 // We have two limits to reduce the complexity:
4116 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
4117 // SLP->isAliased (which is the expensive part in this loop).
4118 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
4119 // the whole loop (even if the loop is fast, it's quadratic).
4120 // It's important for the loop break condition (see below) to
4121 // check this limit even between two read-only instructions.
4122 if (DistToSrc >= MaxMemDepDistance ||
4123 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
4124 (numAliased >= AliasedCheckLimit ||
4125 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
4127 // We increment the counter only if the locations are aliased
4128 // (instead of counting all alias checks). This gives a better
4129 // balance between reduced runtime and accurate dependencies.
4130 numAliased++;
4132 DepDest->MemoryDependencies.push_back(BundleMember);
4133 BundleMember->Dependencies++;
4134 ScheduleData *DestBundle = DepDest->FirstInBundle;
4135 if (!DestBundle->IsScheduled) {
4136 BundleMember->incrementUnscheduledDeps(1);
4138 if (!DestBundle->hasValidDependencies()) {
4139 WorkList.push_back(DestBundle);
4142 DepDest = DepDest->NextLoadStore;
4144 // Example, explaining the loop break condition: Let's assume our
4145 // starting instruction is i0 and MaxMemDepDistance = 3.
4147 // +--------v--v--v
4148 // i0,i1,i2,i3,i4,i5,i6,i7,i8
4149 // +--------^--^--^
4151 // MaxMemDepDistance let us stop alias-checking at i3 and we add
4152 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
4153 // Previously we already added dependencies from i3 to i6,i7,i8
4154 // (because of MaxMemDepDistance). As we added a dependency from
4155 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
4156 // and we can abort this loop at i6.
4157 if (DistToSrc >= 2 * MaxMemDepDistance)
4158 break;
4159 DistToSrc++;
4163 BundleMember = BundleMember->NextInBundle;
4165 if (InsertInReadyList && SD->isReady()) {
4166 ReadyInsts.push_back(SD);
4167 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst
4168 << "\n");
4173 void BoUpSLP::BlockScheduling::resetSchedule() {
4174 assert(ScheduleStart &&
4175 "tried to reset schedule on block which has not been scheduled");
4176 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
4177 doForAllOpcodes(I, [&](ScheduleData *SD) {
4178 assert(isInSchedulingRegion(SD) &&
4179 "ScheduleData not in scheduling region");
4180 SD->IsScheduled = false;
4181 SD->resetUnscheduledDeps();
4184 ReadyInsts.clear();
4187 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
4188 if (!BS->ScheduleStart)
4189 return;
4191 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
4193 BS->resetSchedule();
4195 // For the real scheduling we use a more sophisticated ready-list: it is
4196 // sorted by the original instruction location. This lets the final schedule
4197 // be as close as possible to the original instruction order.
4198 struct ScheduleDataCompare {
4199 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
4200 return SD2->SchedulingPriority < SD1->SchedulingPriority;
4203 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
4205 // Ensure that all dependency data is updated and fill the ready-list with
4206 // initial instructions.
4207 int Idx = 0;
4208 int NumToSchedule = 0;
4209 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
4210 I = I->getNextNode()) {
4211 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
4212 assert(SD->isPartOfBundle() ==
4213 (getTreeEntry(SD->Inst) != nullptr) &&
4214 "scheduler and vectorizer bundle mismatch");
4215 SD->FirstInBundle->SchedulingPriority = Idx++;
4216 if (SD->isSchedulingEntity()) {
4217 BS->calculateDependencies(SD, false, this);
4218 NumToSchedule++;
4222 BS->initialFillReadyList(ReadyInsts);
4224 Instruction *LastScheduledInst = BS->ScheduleEnd;
4226 // Do the "real" scheduling.
4227 while (!ReadyInsts.empty()) {
4228 ScheduleData *picked = *ReadyInsts.begin();
4229 ReadyInsts.erase(ReadyInsts.begin());
4231 // Move the scheduled instruction(s) to their dedicated places, if not
4232 // there yet.
4233 ScheduleData *BundleMember = picked;
4234 while (BundleMember) {
4235 Instruction *pickedInst = BundleMember->Inst;
4236 if (LastScheduledInst->getNextNode() != pickedInst) {
4237 BS->BB->getInstList().remove(pickedInst);
4238 BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
4239 pickedInst);
4241 LastScheduledInst = pickedInst;
4242 BundleMember = BundleMember->NextInBundle;
4245 BS->schedule(picked, ReadyInsts);
4246 NumToSchedule--;
4248 assert(NumToSchedule == 0 && "could not schedule all instructions");
4250 // Avoid duplicate scheduling of the block.
4251 BS->ScheduleStart = nullptr;
4254 unsigned BoUpSLP::getVectorElementSize(Value *V) {
4255 // If V is a store, just return the width of the stored value without
4256 // traversing the expression tree. This is the common case.
4257 if (auto *Store = dyn_cast<StoreInst>(V))
4258 return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
4260 // If V is not a store, we can traverse the expression tree to find loads
4261 // that feed it. The type of the loaded value may indicate a more suitable
4262 // width than V's type. We want to base the vector element size on the width
4263 // of memory operations where possible.
4264 SmallVector<Instruction *, 16> Worklist;
4265 SmallPtrSet<Instruction *, 16> Visited;
4266 if (auto *I = dyn_cast<Instruction>(V))
4267 Worklist.push_back(I);
4269 // Traverse the expression tree in bottom-up order looking for loads. If we
4270 // encounter an instruciton we don't yet handle, we give up.
4271 auto MaxWidth = 0u;
4272 auto FoundUnknownInst = false;
4273 while (!Worklist.empty() && !FoundUnknownInst) {
4274 auto *I = Worklist.pop_back_val();
4275 Visited.insert(I);
4277 // We should only be looking at scalar instructions here. If the current
4278 // instruction has a vector type, give up.
4279 auto *Ty = I->getType();
4280 if (isa<VectorType>(Ty))
4281 FoundUnknownInst = true;
4283 // If the current instruction is a load, update MaxWidth to reflect the
4284 // width of the loaded value.
4285 else if (isa<LoadInst>(I))
4286 MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
4288 // Otherwise, we need to visit the operands of the instruction. We only
4289 // handle the interesting cases from buildTree here. If an operand is an
4290 // instruction we haven't yet visited, we add it to the worklist.
4291 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
4292 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
4293 for (Use &U : I->operands())
4294 if (auto *J = dyn_cast<Instruction>(U.get()))
4295 if (!Visited.count(J))
4296 Worklist.push_back(J);
4299 // If we don't yet handle the instruction, give up.
4300 else
4301 FoundUnknownInst = true;
4304 // If we didn't encounter a memory access in the expression tree, or if we
4305 // gave up for some reason, just return the width of V.
4306 if (!MaxWidth || FoundUnknownInst)
4307 return DL->getTypeSizeInBits(V->getType());
4309 // Otherwise, return the maximum width we found.
4310 return MaxWidth;
4313 // Determine if a value V in a vectorizable expression Expr can be demoted to a
4314 // smaller type with a truncation. We collect the values that will be demoted
4315 // in ToDemote and additional roots that require investigating in Roots.
4316 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
4317 SmallVectorImpl<Value *> &ToDemote,
4318 SmallVectorImpl<Value *> &Roots) {
4319 // We can always demote constants.
4320 if (isa<Constant>(V)) {
4321 ToDemote.push_back(V);
4322 return true;
4325 // If the value is not an instruction in the expression with only one use, it
4326 // cannot be demoted.
4327 auto *I = dyn_cast<Instruction>(V);
4328 if (!I || !I->hasOneUse() || !Expr.count(I))
4329 return false;
4331 switch (I->getOpcode()) {
4333 // We can always demote truncations and extensions. Since truncations can
4334 // seed additional demotion, we save the truncated value.
4335 case Instruction::Trunc:
4336 Roots.push_back(I->getOperand(0));
4337 break;
4338 case Instruction::ZExt:
4339 case Instruction::SExt:
4340 break;
4342 // We can demote certain binary operations if we can demote both of their
4343 // operands.
4344 case Instruction::Add:
4345 case Instruction::Sub:
4346 case Instruction::Mul:
4347 case Instruction::And:
4348 case Instruction::Or:
4349 case Instruction::Xor:
4350 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
4351 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
4352 return false;
4353 break;
4355 // We can demote selects if we can demote their true and false values.
4356 case Instruction::Select: {
4357 SelectInst *SI = cast<SelectInst>(I);
4358 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
4359 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
4360 return false;
4361 break;
4364 // We can demote phis if we can demote all their incoming operands. Note that
4365 // we don't need to worry about cycles since we ensure single use above.
4366 case Instruction::PHI: {
4367 PHINode *PN = cast<PHINode>(I);
4368 for (Value *IncValue : PN->incoming_values())
4369 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
4370 return false;
4371 break;
4374 // Otherwise, conservatively give up.
4375 default:
4376 return false;
4379 // Record the value that we can demote.
4380 ToDemote.push_back(V);
4381 return true;
4384 void BoUpSLP::computeMinimumValueSizes() {
4385 // If there are no external uses, the expression tree must be rooted by a
4386 // store. We can't demote in-memory values, so there is nothing to do here.
4387 if (ExternalUses.empty())
4388 return;
4390 // We only attempt to truncate integer expressions.
4391 auto &TreeRoot = VectorizableTree[0].Scalars;
4392 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
4393 if (!TreeRootIT)
4394 return;
4396 // If the expression is not rooted by a store, these roots should have
4397 // external uses. We will rely on InstCombine to rewrite the expression in
4398 // the narrower type. However, InstCombine only rewrites single-use values.
4399 // This means that if a tree entry other than a root is used externally, it
4400 // must have multiple uses and InstCombine will not rewrite it. The code
4401 // below ensures that only the roots are used externally.
4402 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
4403 for (auto &EU : ExternalUses)
4404 if (!Expr.erase(EU.Scalar))
4405 return;
4406 if (!Expr.empty())
4407 return;
4409 // Collect the scalar values of the vectorizable expression. We will use this
4410 // context to determine which values can be demoted. If we see a truncation,
4411 // we mark it as seeding another demotion.
4412 for (auto &Entry : VectorizableTree)
4413 Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
4415 // Ensure the roots of the vectorizable tree don't form a cycle. They must
4416 // have a single external user that is not in the vectorizable tree.
4417 for (auto *Root : TreeRoot)
4418 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
4419 return;
4421 // Conservatively determine if we can actually truncate the roots of the
4422 // expression. Collect the values that can be demoted in ToDemote and
4423 // additional roots that require investigating in Roots.
4424 SmallVector<Value *, 32> ToDemote;
4425 SmallVector<Value *, 4> Roots;
4426 for (auto *Root : TreeRoot)
4427 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
4428 return;
4430 // The maximum bit width required to represent all the values that can be
4431 // demoted without loss of precision. It would be safe to truncate the roots
4432 // of the expression to this width.
4433 auto MaxBitWidth = 8u;
4435 // We first check if all the bits of the roots are demanded. If they're not,
4436 // we can truncate the roots to this narrower type.
4437 for (auto *Root : TreeRoot) {
4438 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
4439 MaxBitWidth = std::max<unsigned>(
4440 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
4443 // True if the roots can be zero-extended back to their original type, rather
4444 // than sign-extended. We know that if the leading bits are not demanded, we
4445 // can safely zero-extend. So we initialize IsKnownPositive to True.
4446 bool IsKnownPositive = true;
4448 // If all the bits of the roots are demanded, we can try a little harder to
4449 // compute a narrower type. This can happen, for example, if the roots are
4450 // getelementptr indices. InstCombine promotes these indices to the pointer
4451 // width. Thus, all their bits are technically demanded even though the
4452 // address computation might be vectorized in a smaller type.
4454 // We start by looking at each entry that can be demoted. We compute the
4455 // maximum bit width required to store the scalar by using ValueTracking to
4456 // compute the number of high-order bits we can truncate.
4457 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
4458 llvm::all_of(TreeRoot, [](Value *R) {
4459 assert(R->hasOneUse() && "Root should have only one use!");
4460 return isa<GetElementPtrInst>(R->user_back());
4461 })) {
4462 MaxBitWidth = 8u;
4464 // Determine if the sign bit of all the roots is known to be zero. If not,
4465 // IsKnownPositive is set to False.
4466 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
4467 KnownBits Known = computeKnownBits(R, *DL);
4468 return Known.isNonNegative();
4471 // Determine the maximum number of bits required to store the scalar
4472 // values.
4473 for (auto *Scalar : ToDemote) {
4474 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
4475 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
4476 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
4479 // If we can't prove that the sign bit is zero, we must add one to the
4480 // maximum bit width to account for the unknown sign bit. This preserves
4481 // the existing sign bit so we can safely sign-extend the root back to the
4482 // original type. Otherwise, if we know the sign bit is zero, we will
4483 // zero-extend the root instead.
4485 // FIXME: This is somewhat suboptimal, as there will be cases where adding
4486 // one to the maximum bit width will yield a larger-than-necessary
4487 // type. In general, we need to add an extra bit only if we can't
4488 // prove that the upper bit of the original type is equal to the
4489 // upper bit of the proposed smaller type. If these two bits are the
4490 // same (either zero or one) we know that sign-extending from the
4491 // smaller type will result in the same value. Here, since we can't
4492 // yet prove this, we are just making the proposed smaller type
4493 // larger to ensure correctness.
4494 if (!IsKnownPositive)
4495 ++MaxBitWidth;
4498 // Round MaxBitWidth up to the next power-of-two.
4499 if (!isPowerOf2_64(MaxBitWidth))
4500 MaxBitWidth = NextPowerOf2(MaxBitWidth);
4502 // If the maximum bit width we compute is less than the with of the roots'
4503 // type, we can proceed with the narrowing. Otherwise, do nothing.
4504 if (MaxBitWidth >= TreeRootIT->getBitWidth())
4505 return;
4507 // If we can truncate the root, we must collect additional values that might
4508 // be demoted as a result. That is, those seeded by truncations we will
4509 // modify.
4510 while (!Roots.empty())
4511 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
4513 // Finally, map the values we can demote to the maximum bit with we computed.
4514 for (auto *Scalar : ToDemote)
4515 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
4518 namespace {
4520 /// The SLPVectorizer Pass.
4521 struct SLPVectorizer : public FunctionPass {
4522 SLPVectorizerPass Impl;
4524 /// Pass identification, replacement for typeid
4525 static char ID;
4527 explicit SLPVectorizer() : FunctionPass(ID) {
4528 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
4531 bool doInitialization(Module &M) override {
4532 return false;
4535 bool runOnFunction(Function &F) override {
4536 if (skipFunction(F))
4537 return false;
4539 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4540 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4541 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
4542 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
4543 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4544 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4545 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4546 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4547 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
4548 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4550 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4553 void getAnalysisUsage(AnalysisUsage &AU) const override {
4554 FunctionPass::getAnalysisUsage(AU);
4555 AU.addRequired<AssumptionCacheTracker>();
4556 AU.addRequired<ScalarEvolutionWrapperPass>();
4557 AU.addRequired<AAResultsWrapperPass>();
4558 AU.addRequired<TargetTransformInfoWrapperPass>();
4559 AU.addRequired<LoopInfoWrapperPass>();
4560 AU.addRequired<DominatorTreeWrapperPass>();
4561 AU.addRequired<DemandedBitsWrapperPass>();
4562 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4563 AU.addPreserved<LoopInfoWrapperPass>();
4564 AU.addPreserved<DominatorTreeWrapperPass>();
4565 AU.addPreserved<AAResultsWrapperPass>();
4566 AU.addPreserved<GlobalsAAWrapperPass>();
4567 AU.setPreservesCFG();
4571 } // end anonymous namespace
4573 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
4574 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
4575 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
4576 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
4577 auto *AA = &AM.getResult<AAManager>(F);
4578 auto *LI = &AM.getResult<LoopAnalysis>(F);
4579 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
4580 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
4581 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
4582 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4584 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4585 if (!Changed)
4586 return PreservedAnalyses::all();
4588 PreservedAnalyses PA;
4589 PA.preserveSet<CFGAnalyses>();
4590 PA.preserve<AAManager>();
4591 PA.preserve<GlobalsAA>();
4592 return PA;
4595 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
4596 TargetTransformInfo *TTI_,
4597 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
4598 LoopInfo *LI_, DominatorTree *DT_,
4599 AssumptionCache *AC_, DemandedBits *DB_,
4600 OptimizationRemarkEmitter *ORE_) {
4601 SE = SE_;
4602 TTI = TTI_;
4603 TLI = TLI_;
4604 AA = AA_;
4605 LI = LI_;
4606 DT = DT_;
4607 AC = AC_;
4608 DB = DB_;
4609 DL = &F.getParent()->getDataLayout();
4611 Stores.clear();
4612 GEPs.clear();
4613 bool Changed = false;
4615 // If the target claims to have no vector registers don't attempt
4616 // vectorization.
4617 if (!TTI->getNumberOfRegisters(true))
4618 return false;
4620 // Don't vectorize when the attribute NoImplicitFloat is used.
4621 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
4622 return false;
4624 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
4626 // Use the bottom up slp vectorizer to construct chains that start with
4627 // store instructions.
4628 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
4630 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
4631 // delete instructions.
4633 // Scan the blocks in the function in post order.
4634 for (auto BB : post_order(&F.getEntryBlock())) {
4635 collectSeedInstructions(BB);
4637 // Vectorize trees that end at stores.
4638 if (!Stores.empty()) {
4639 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
4640 << " underlying objects.\n");
4641 Changed |= vectorizeStoreChains(R);
4644 // Vectorize trees that end at reductions.
4645 Changed |= vectorizeChainsInBlock(BB, R);
4647 // Vectorize the index computations of getelementptr instructions. This
4648 // is primarily intended to catch gather-like idioms ending at
4649 // non-consecutive loads.
4650 if (!GEPs.empty()) {
4651 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
4652 << " underlying objects.\n");
4653 Changed |= vectorizeGEPIndices(BB, R);
4657 if (Changed) {
4658 R.optimizeGatherSequence();
4659 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
4660 LLVM_DEBUG(verifyFunction(F));
4662 return Changed;
4665 /// Check that the Values in the slice in VL array are still existent in
4666 /// the WeakTrackingVH array.
4667 /// Vectorization of part of the VL array may cause later values in the VL array
4668 /// to become invalid. We track when this has happened in the WeakTrackingVH
4669 /// array.
4670 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
4671 ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
4672 unsigned SliceSize) {
4673 VL = VL.slice(SliceBegin, SliceSize);
4674 VH = VH.slice(SliceBegin, SliceSize);
4675 return !std::equal(VL.begin(), VL.end(), VH.begin());
4678 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
4679 unsigned VecRegSize) {
4680 const unsigned ChainLen = Chain.size();
4681 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
4682 << "\n");
4683 const unsigned Sz = R.getVectorElementSize(Chain[0]);
4684 const unsigned VF = VecRegSize / Sz;
4686 if (!isPowerOf2_32(Sz) || VF < 2)
4687 return false;
4689 // Keep track of values that were deleted by vectorizing in the loop below.
4690 const SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
4692 bool Changed = false;
4693 // Look for profitable vectorizable trees at all offsets, starting at zero.
4694 for (unsigned i = 0, e = ChainLen; i + VF <= e; ++i) {
4696 // Check that a previous iteration of this loop did not delete the Value.
4697 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
4698 continue;
4700 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
4701 << "\n");
4702 ArrayRef<Value *> Operands = Chain.slice(i, VF);
4704 R.buildTree(Operands);
4705 if (R.isTreeTinyAndNotFullyVectorizable())
4706 continue;
4708 R.computeMinimumValueSizes();
4710 int Cost = R.getTreeCost();
4712 LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF
4713 << "\n");
4714 if (Cost < -SLPCostThreshold) {
4715 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
4717 using namespace ore;
4719 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
4720 cast<StoreInst>(Chain[i]))
4721 << "Stores SLP vectorized with cost " << NV("Cost", Cost)
4722 << " and with tree size "
4723 << NV("TreeSize", R.getTreeSize()));
4725 R.vectorizeTree();
4727 // Move to the next bundle.
4728 i += VF - 1;
4729 Changed = true;
4733 return Changed;
4736 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
4737 BoUpSLP &R) {
4738 SetVector<StoreInst *> Heads;
4739 SmallDenseSet<StoreInst *> Tails;
4740 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
4742 // We may run into multiple chains that merge into a single chain. We mark the
4743 // stores that we vectorized so that we don't visit the same store twice.
4744 BoUpSLP::ValueSet VectorizedStores;
4745 bool Changed = false;
4747 // Do a quadratic search on all of the given stores in reverse order and find
4748 // all of the pairs of stores that follow each other.
4749 SmallVector<unsigned, 16> IndexQueue;
4750 unsigned E = Stores.size();
4751 IndexQueue.resize(E - 1);
4752 for (unsigned I = E; I > 0; --I) {
4753 unsigned Idx = I - 1;
4754 // If a store has multiple consecutive store candidates, search Stores
4755 // array according to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
4756 // This is because usually pairing with immediate succeeding or preceding
4757 // candidate create the best chance to find slp vectorization opportunity.
4758 unsigned Offset = 1;
4759 unsigned Cnt = 0;
4760 for (unsigned J = 0; J < E - 1; ++J, ++Offset) {
4761 if (Idx >= Offset) {
4762 IndexQueue[Cnt] = Idx - Offset;
4763 ++Cnt;
4765 if (Idx + Offset < E) {
4766 IndexQueue[Cnt] = Idx + Offset;
4767 ++Cnt;
4771 for (auto K : IndexQueue) {
4772 if (isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE)) {
4773 Tails.insert(Stores[Idx]);
4774 Heads.insert(Stores[K]);
4775 ConsecutiveChain[Stores[K]] = Stores[Idx];
4776 break;
4781 // For stores that start but don't end a link in the chain:
4782 for (auto *SI : llvm::reverse(Heads)) {
4783 if (Tails.count(SI))
4784 continue;
4786 // We found a store instr that starts a chain. Now follow the chain and try
4787 // to vectorize it.
4788 BoUpSLP::ValueList Operands;
4789 StoreInst *I = SI;
4790 // Collect the chain into a list.
4791 while ((Tails.count(I) || Heads.count(I)) && !VectorizedStores.count(I)) {
4792 Operands.push_back(I);
4793 // Move to the next value in the chain.
4794 I = ConsecutiveChain[I];
4797 // FIXME: Is division-by-2 the correct step? Should we assert that the
4798 // register size is a power-of-2?
4799 for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4800 Size /= 2) {
4801 if (vectorizeStoreChain(Operands, R, Size)) {
4802 // Mark the vectorized stores so that we don't vectorize them again.
4803 VectorizedStores.insert(Operands.begin(), Operands.end());
4804 Changed = true;
4805 break;
4810 return Changed;
4813 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4814 // Initialize the collections. We will make a single pass over the block.
4815 Stores.clear();
4816 GEPs.clear();
4818 // Visit the store and getelementptr instructions in BB and organize them in
4819 // Stores and GEPs according to the underlying objects of their pointer
4820 // operands.
4821 for (Instruction &I : *BB) {
4822 // Ignore store instructions that are volatile or have a pointer operand
4823 // that doesn't point to a scalar type.
4824 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4825 if (!SI->isSimple())
4826 continue;
4827 if (!isValidElementType(SI->getValueOperand()->getType()))
4828 continue;
4829 Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4832 // Ignore getelementptr instructions that have more than one index, a
4833 // constant index, or a pointer operand that doesn't point to a scalar
4834 // type.
4835 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4836 auto Idx = GEP->idx_begin()->get();
4837 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4838 continue;
4839 if (!isValidElementType(Idx->getType()))
4840 continue;
4841 if (GEP->getType()->isVectorTy())
4842 continue;
4843 GEPs[GEP->getPointerOperand()].push_back(GEP);
4848 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4849 if (!A || !B)
4850 return false;
4851 Value *VL[] = { A, B };
4852 return tryToVectorizeList(VL, R, /*UserCost=*/0, true);
4855 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4856 int UserCost, bool AllowReorder) {
4857 if (VL.size() < 2)
4858 return false;
4860 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
4861 << VL.size() << ".\n");
4863 // Check that all of the parts are scalar instructions of the same type,
4864 // we permit an alternate opcode via InstructionsState.
4865 InstructionsState S = getSameOpcode(VL);
4866 if (!S.getOpcode())
4867 return false;
4869 Instruction *I0 = cast<Instruction>(S.OpValue);
4870 unsigned Sz = R.getVectorElementSize(I0);
4871 unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4872 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4873 if (MaxVF < 2) {
4874 R.getORE()->emit([&]() {
4875 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
4876 << "Cannot SLP vectorize list: vectorization factor "
4877 << "less than 2 is not supported";
4879 return false;
4882 for (Value *V : VL) {
4883 Type *Ty = V->getType();
4884 if (!isValidElementType(Ty)) {
4885 // NOTE: the following will give user internal llvm type name, which may
4886 // not be useful.
4887 R.getORE()->emit([&]() {
4888 std::string type_str;
4889 llvm::raw_string_ostream rso(type_str);
4890 Ty->print(rso);
4891 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
4892 << "Cannot SLP vectorize list: type "
4893 << rso.str() + " is unsupported by vectorizer";
4895 return false;
4899 bool Changed = false;
4900 bool CandidateFound = false;
4901 int MinCost = SLPCostThreshold;
4903 // Keep track of values that were deleted by vectorizing in the loop below.
4904 SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4906 unsigned NextInst = 0, MaxInst = VL.size();
4907 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4908 VF /= 2) {
4909 // No actual vectorization should happen, if number of parts is the same as
4910 // provided vectorization factor (i.e. the scalar type is used for vector
4911 // code during codegen).
4912 auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4913 if (TTI->getNumberOfParts(VecTy) == VF)
4914 continue;
4915 for (unsigned I = NextInst; I < MaxInst; ++I) {
4916 unsigned OpsWidth = 0;
4918 if (I + VF > MaxInst)
4919 OpsWidth = MaxInst - I;
4920 else
4921 OpsWidth = VF;
4923 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4924 break;
4926 // Check that a previous iteration of this loop did not delete the Value.
4927 if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4928 continue;
4930 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4931 << "\n");
4932 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4934 R.buildTree(Ops);
4935 Optional<ArrayRef<unsigned>> Order = R.bestOrder();
4936 // TODO: check if we can allow reordering for more cases.
4937 if (AllowReorder && Order) {
4938 // TODO: reorder tree nodes without tree rebuilding.
4939 // Conceptually, there is nothing actually preventing us from trying to
4940 // reorder a larger list. In fact, we do exactly this when vectorizing
4941 // reductions. However, at this point, we only expect to get here when
4942 // there are exactly two operations.
4943 assert(Ops.size() == 2);
4944 Value *ReorderedOps[] = {Ops[1], Ops[0]};
4945 R.buildTree(ReorderedOps, None);
4947 if (R.isTreeTinyAndNotFullyVectorizable())
4948 continue;
4950 R.computeMinimumValueSizes();
4951 int Cost = R.getTreeCost() - UserCost;
4952 CandidateFound = true;
4953 MinCost = std::min(MinCost, Cost);
4955 if (Cost < -SLPCostThreshold) {
4956 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
4957 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
4958 cast<Instruction>(Ops[0]))
4959 << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4960 << " and with tree size "
4961 << ore::NV("TreeSize", R.getTreeSize()));
4963 R.vectorizeTree();
4964 // Move to the next bundle.
4965 I += VF - 1;
4966 NextInst = I + 1;
4967 Changed = true;
4972 if (!Changed && CandidateFound) {
4973 R.getORE()->emit([&]() {
4974 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
4975 << "List vectorization was possible but not beneficial with cost "
4976 << ore::NV("Cost", MinCost) << " >= "
4977 << ore::NV("Treshold", -SLPCostThreshold);
4979 } else if (!Changed) {
4980 R.getORE()->emit([&]() {
4981 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
4982 << "Cannot SLP vectorize list: vectorization was impossible"
4983 << " with available vectorization factors";
4986 return Changed;
4989 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
4990 if (!I)
4991 return false;
4993 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
4994 return false;
4996 Value *P = I->getParent();
4998 // Vectorize in current basic block only.
4999 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
5000 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
5001 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
5002 return false;
5004 // Try to vectorize V.
5005 if (tryToVectorizePair(Op0, Op1, R))
5006 return true;
5008 auto *A = dyn_cast<BinaryOperator>(Op0);
5009 auto *B = dyn_cast<BinaryOperator>(Op1);
5010 // Try to skip B.
5011 if (B && B->hasOneUse()) {
5012 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
5013 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
5014 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
5015 return true;
5016 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
5017 return true;
5020 // Try to skip A.
5021 if (A && A->hasOneUse()) {
5022 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
5023 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
5024 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
5025 return true;
5026 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
5027 return true;
5029 return false;
5032 /// Generate a shuffle mask to be used in a reduction tree.
5034 /// \param VecLen The length of the vector to be reduced.
5035 /// \param NumEltsToRdx The number of elements that should be reduced in the
5036 /// vector.
5037 /// \param IsPairwise Whether the reduction is a pairwise or splitting
5038 /// reduction. A pairwise reduction will generate a mask of
5039 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
5040 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
5041 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
5042 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
5043 bool IsPairwise, bool IsLeft,
5044 IRBuilder<> &Builder) {
5045 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
5047 SmallVector<Constant *, 32> ShuffleMask(
5048 VecLen, UndefValue::get(Builder.getInt32Ty()));
5050 if (IsPairwise)
5051 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
5052 for (unsigned i = 0; i != NumEltsToRdx; ++i)
5053 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
5054 else
5055 // Move the upper half of the vector to the lower half.
5056 for (unsigned i = 0; i != NumEltsToRdx; ++i)
5057 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
5059 return ConstantVector::get(ShuffleMask);
5062 namespace {
5064 /// Model horizontal reductions.
5066 /// A horizontal reduction is a tree of reduction operations (currently add and
5067 /// fadd) that has operations that can be put into a vector as its leaf.
5068 /// For example, this tree:
5070 /// mul mul mul mul
5071 /// \ / \ /
5072 /// + +
5073 /// \ /
5074 /// +
5075 /// This tree has "mul" as its reduced values and "+" as its reduction
5076 /// operations. A reduction might be feeding into a store or a binary operation
5077 /// feeding a phi.
5078 /// ...
5079 /// \ /
5080 /// +
5081 /// |
5082 /// phi +=
5084 /// Or:
5085 /// ...
5086 /// \ /
5087 /// +
5088 /// |
5089 /// *p =
5091 class HorizontalReduction {
5092 using ReductionOpsType = SmallVector<Value *, 16>;
5093 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
5094 ReductionOpsListType ReductionOps;
5095 SmallVector<Value *, 32> ReducedVals;
5096 // Use map vector to make stable output.
5097 MapVector<Instruction *, Value *> ExtraArgs;
5099 /// Kind of the reduction data.
5100 enum ReductionKind {
5101 RK_None, /// Not a reduction.
5102 RK_Arithmetic, /// Binary reduction data.
5103 RK_Min, /// Minimum reduction data.
5104 RK_UMin, /// Unsigned minimum reduction data.
5105 RK_Max, /// Maximum reduction data.
5106 RK_UMax, /// Unsigned maximum reduction data.
5109 /// Contains info about operation, like its opcode, left and right operands.
5110 class OperationData {
5111 /// Opcode of the instruction.
5112 unsigned Opcode = 0;
5114 /// Left operand of the reduction operation.
5115 Value *LHS = nullptr;
5117 /// Right operand of the reduction operation.
5118 Value *RHS = nullptr;
5120 /// Kind of the reduction operation.
5121 ReductionKind Kind = RK_None;
5123 /// True if float point min/max reduction has no NaNs.
5124 bool NoNaN = false;
5126 /// Checks if the reduction operation can be vectorized.
5127 bool isVectorizable() const {
5128 return LHS && RHS &&
5129 // We currently only support adds && min/max reductions.
5130 ((Kind == RK_Arithmetic &&
5131 (Opcode == Instruction::Add || Opcode == Instruction::FAdd)) ||
5132 ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
5133 (Kind == RK_Min || Kind == RK_Max)) ||
5134 (Opcode == Instruction::ICmp &&
5135 (Kind == RK_UMin || Kind == RK_UMax)));
5138 /// Creates reduction operation with the current opcode.
5139 Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
5140 assert(isVectorizable() &&
5141 "Expected add|fadd or min/max reduction operation.");
5142 Value *Cmp;
5143 switch (Kind) {
5144 case RK_Arithmetic:
5145 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
5146 Name);
5147 case RK_Min:
5148 Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
5149 : Builder.CreateFCmpOLT(LHS, RHS);
5150 break;
5151 case RK_Max:
5152 Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
5153 : Builder.CreateFCmpOGT(LHS, RHS);
5154 break;
5155 case RK_UMin:
5156 assert(Opcode == Instruction::ICmp && "Expected integer types.");
5157 Cmp = Builder.CreateICmpULT(LHS, RHS);
5158 break;
5159 case RK_UMax:
5160 assert(Opcode == Instruction::ICmp && "Expected integer types.");
5161 Cmp = Builder.CreateICmpUGT(LHS, RHS);
5162 break;
5163 case RK_None:
5164 llvm_unreachable("Unknown reduction operation.");
5166 return Builder.CreateSelect(Cmp, LHS, RHS, Name);
5169 public:
5170 explicit OperationData() = default;
5172 /// Construction for reduced values. They are identified by opcode only and
5173 /// don't have associated LHS/RHS values.
5174 explicit OperationData(Value *V) {
5175 if (auto *I = dyn_cast<Instruction>(V))
5176 Opcode = I->getOpcode();
5179 /// Constructor for reduction operations with opcode and its left and
5180 /// right operands.
5181 OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
5182 bool NoNaN = false)
5183 : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
5184 assert(Kind != RK_None && "One of the reduction operations is expected.");
5187 explicit operator bool() const { return Opcode; }
5189 /// Get the index of the first operand.
5190 unsigned getFirstOperandIndex() const {
5191 assert(!!*this && "The opcode is not set.");
5192 switch (Kind) {
5193 case RK_Min:
5194 case RK_UMin:
5195 case RK_Max:
5196 case RK_UMax:
5197 return 1;
5198 case RK_Arithmetic:
5199 case RK_None:
5200 break;
5202 return 0;
5205 /// Total number of operands in the reduction operation.
5206 unsigned getNumberOfOperands() const {
5207 assert(Kind != RK_None && !!*this && LHS && RHS &&
5208 "Expected reduction operation.");
5209 switch (Kind) {
5210 case RK_Arithmetic:
5211 return 2;
5212 case RK_Min:
5213 case RK_UMin:
5214 case RK_Max:
5215 case RK_UMax:
5216 return 3;
5217 case RK_None:
5218 break;
5220 llvm_unreachable("Reduction kind is not set");
5223 /// Checks if the operation has the same parent as \p P.
5224 bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
5225 assert(Kind != RK_None && !!*this && LHS && RHS &&
5226 "Expected reduction operation.");
5227 if (!IsRedOp)
5228 return I->getParent() == P;
5229 switch (Kind) {
5230 case RK_Arithmetic:
5231 // Arithmetic reduction operation must be used once only.
5232 return I->getParent() == P;
5233 case RK_Min:
5234 case RK_UMin:
5235 case RK_Max:
5236 case RK_UMax: {
5237 // SelectInst must be used twice while the condition op must have single
5238 // use only.
5239 auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
5240 return I->getParent() == P && Cmp && Cmp->getParent() == P;
5242 case RK_None:
5243 break;
5245 llvm_unreachable("Reduction kind is not set");
5247 /// Expected number of uses for reduction operations/reduced values.
5248 bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
5249 assert(Kind != RK_None && !!*this && LHS && RHS &&
5250 "Expected reduction operation.");
5251 switch (Kind) {
5252 case RK_Arithmetic:
5253 return I->hasOneUse();
5254 case RK_Min:
5255 case RK_UMin:
5256 case RK_Max:
5257 case RK_UMax:
5258 return I->hasNUses(2) &&
5259 (!IsReductionOp ||
5260 cast<SelectInst>(I)->getCondition()->hasOneUse());
5261 case RK_None:
5262 break;
5264 llvm_unreachable("Reduction kind is not set");
5267 /// Initializes the list of reduction operations.
5268 void initReductionOps(ReductionOpsListType &ReductionOps) {
5269 assert(Kind != RK_None && !!*this && LHS && RHS &&
5270 "Expected reduction operation.");
5271 switch (Kind) {
5272 case RK_Arithmetic:
5273 ReductionOps.assign(1, ReductionOpsType());
5274 break;
5275 case RK_Min:
5276 case RK_UMin:
5277 case RK_Max:
5278 case RK_UMax:
5279 ReductionOps.assign(2, ReductionOpsType());
5280 break;
5281 case RK_None:
5282 llvm_unreachable("Reduction kind is not set");
5285 /// Add all reduction operations for the reduction instruction \p I.
5286 void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
5287 assert(Kind != RK_None && !!*this && LHS && RHS &&
5288 "Expected reduction operation.");
5289 switch (Kind) {
5290 case RK_Arithmetic:
5291 ReductionOps[0].emplace_back(I);
5292 break;
5293 case RK_Min:
5294 case RK_UMin:
5295 case RK_Max:
5296 case RK_UMax:
5297 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
5298 ReductionOps[1].emplace_back(I);
5299 break;
5300 case RK_None:
5301 llvm_unreachable("Reduction kind is not set");
5305 /// Checks if instruction is associative and can be vectorized.
5306 bool isAssociative(Instruction *I) const {
5307 assert(Kind != RK_None && *this && LHS && RHS &&
5308 "Expected reduction operation.");
5309 switch (Kind) {
5310 case RK_Arithmetic:
5311 return I->isAssociative();
5312 case RK_Min:
5313 case RK_Max:
5314 return Opcode == Instruction::ICmp ||
5315 cast<Instruction>(I->getOperand(0))->isFast();
5316 case RK_UMin:
5317 case RK_UMax:
5318 assert(Opcode == Instruction::ICmp &&
5319 "Only integer compare operation is expected.");
5320 return true;
5321 case RK_None:
5322 break;
5324 llvm_unreachable("Reduction kind is not set");
5327 /// Checks if the reduction operation can be vectorized.
5328 bool isVectorizable(Instruction *I) const {
5329 return isVectorizable() && isAssociative(I);
5332 /// Checks if two operation data are both a reduction op or both a reduced
5333 /// value.
5334 bool operator==(const OperationData &OD) {
5335 assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
5336 "One of the comparing operations is incorrect.");
5337 return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
5339 bool operator!=(const OperationData &OD) { return !(*this == OD); }
5340 void clear() {
5341 Opcode = 0;
5342 LHS = nullptr;
5343 RHS = nullptr;
5344 Kind = RK_None;
5345 NoNaN = false;
5348 /// Get the opcode of the reduction operation.
5349 unsigned getOpcode() const {
5350 assert(isVectorizable() && "Expected vectorizable operation.");
5351 return Opcode;
5354 /// Get kind of reduction data.
5355 ReductionKind getKind() const { return Kind; }
5356 Value *getLHS() const { return LHS; }
5357 Value *getRHS() const { return RHS; }
5358 Type *getConditionType() const {
5359 switch (Kind) {
5360 case RK_Arithmetic:
5361 return nullptr;
5362 case RK_Min:
5363 case RK_Max:
5364 case RK_UMin:
5365 case RK_UMax:
5366 return CmpInst::makeCmpResultType(LHS->getType());
5367 case RK_None:
5368 break;
5370 llvm_unreachable("Reduction kind is not set");
5373 /// Creates reduction operation with the current opcode with the IR flags
5374 /// from \p ReductionOps.
5375 Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5376 const ReductionOpsListType &ReductionOps) const {
5377 assert(isVectorizable() &&
5378 "Expected add|fadd or min/max reduction operation.");
5379 auto *Op = createOp(Builder, Name);
5380 switch (Kind) {
5381 case RK_Arithmetic:
5382 propagateIRFlags(Op, ReductionOps[0]);
5383 return Op;
5384 case RK_Min:
5385 case RK_Max:
5386 case RK_UMin:
5387 case RK_UMax:
5388 if (auto *SI = dyn_cast<SelectInst>(Op))
5389 propagateIRFlags(SI->getCondition(), ReductionOps[0]);
5390 propagateIRFlags(Op, ReductionOps[1]);
5391 return Op;
5392 case RK_None:
5393 break;
5395 llvm_unreachable("Unknown reduction operation.");
5397 /// Creates reduction operation with the current opcode with the IR flags
5398 /// from \p I.
5399 Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5400 Instruction *I) const {
5401 assert(isVectorizable() &&
5402 "Expected add|fadd or min/max reduction operation.");
5403 auto *Op = createOp(Builder, Name);
5404 switch (Kind) {
5405 case RK_Arithmetic:
5406 propagateIRFlags(Op, I);
5407 return Op;
5408 case RK_Min:
5409 case RK_Max:
5410 case RK_UMin:
5411 case RK_UMax:
5412 if (auto *SI = dyn_cast<SelectInst>(Op)) {
5413 propagateIRFlags(SI->getCondition(),
5414 cast<SelectInst>(I)->getCondition());
5416 propagateIRFlags(Op, I);
5417 return Op;
5418 case RK_None:
5419 break;
5421 llvm_unreachable("Unknown reduction operation.");
5424 TargetTransformInfo::ReductionFlags getFlags() const {
5425 TargetTransformInfo::ReductionFlags Flags;
5426 Flags.NoNaN = NoNaN;
5427 switch (Kind) {
5428 case RK_Arithmetic:
5429 break;
5430 case RK_Min:
5431 Flags.IsSigned = Opcode == Instruction::ICmp;
5432 Flags.IsMaxOp = false;
5433 break;
5434 case RK_Max:
5435 Flags.IsSigned = Opcode == Instruction::ICmp;
5436 Flags.IsMaxOp = true;
5437 break;
5438 case RK_UMin:
5439 Flags.IsSigned = false;
5440 Flags.IsMaxOp = false;
5441 break;
5442 case RK_UMax:
5443 Flags.IsSigned = false;
5444 Flags.IsMaxOp = true;
5445 break;
5446 case RK_None:
5447 llvm_unreachable("Reduction kind is not set");
5449 return Flags;
5453 Instruction *ReductionRoot = nullptr;
5455 /// The operation data of the reduction operation.
5456 OperationData ReductionData;
5458 /// The operation data of the values we perform a reduction on.
5459 OperationData ReducedValueData;
5461 /// Should we model this reduction as a pairwise reduction tree or a tree that
5462 /// splits the vector in halves and adds those halves.
5463 bool IsPairwiseReduction = false;
5465 /// Checks if the ParentStackElem.first should be marked as a reduction
5466 /// operation with an extra argument or as extra argument itself.
5467 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
5468 Value *ExtraArg) {
5469 if (ExtraArgs.count(ParentStackElem.first)) {
5470 ExtraArgs[ParentStackElem.first] = nullptr;
5471 // We ran into something like:
5472 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
5473 // The whole ParentStackElem.first should be considered as an extra value
5474 // in this case.
5475 // Do not perform analysis of remaining operands of ParentStackElem.first
5476 // instruction, this whole instruction is an extra argument.
5477 ParentStackElem.second = ParentStackElem.first->getNumOperands();
5478 } else {
5479 // We ran into something like:
5480 // ParentStackElem.first += ... + ExtraArg + ...
5481 ExtraArgs[ParentStackElem.first] = ExtraArg;
5485 static OperationData getOperationData(Value *V) {
5486 if (!V)
5487 return OperationData();
5489 Value *LHS;
5490 Value *RHS;
5491 if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
5492 return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
5493 RK_Arithmetic);
5495 if (auto *Select = dyn_cast<SelectInst>(V)) {
5496 // Look for a min/max pattern.
5497 if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5498 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
5499 } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5500 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
5501 } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
5502 m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5503 return OperationData(
5504 Instruction::FCmp, LHS, RHS, RK_Min,
5505 cast<Instruction>(Select->getCondition())->hasNoNaNs());
5506 } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5507 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
5508 } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5509 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
5510 } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
5511 m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5512 return OperationData(
5513 Instruction::FCmp, LHS, RHS, RK_Max,
5514 cast<Instruction>(Select->getCondition())->hasNoNaNs());
5515 } else {
5516 // Try harder: look for min/max pattern based on instructions producing
5517 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
5518 // During the intermediate stages of SLP, it's very common to have
5519 // pattern like this (since optimizeGatherSequence is run only once
5520 // at the end):
5521 // %1 = extractelement <2 x i32> %a, i32 0
5522 // %2 = extractelement <2 x i32> %a, i32 1
5523 // %cond = icmp sgt i32 %1, %2
5524 // %3 = extractelement <2 x i32> %a, i32 0
5525 // %4 = extractelement <2 x i32> %a, i32 1
5526 // %select = select i1 %cond, i32 %3, i32 %4
5527 CmpInst::Predicate Pred;
5528 Instruction *L1;
5529 Instruction *L2;
5531 LHS = Select->getTrueValue();
5532 RHS = Select->getFalseValue();
5533 Value *Cond = Select->getCondition();
5535 // TODO: Support inverse predicates.
5536 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
5537 if (!isa<ExtractElementInst>(RHS) ||
5538 !L2->isIdenticalTo(cast<Instruction>(RHS)))
5539 return OperationData(V);
5540 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
5541 if (!isa<ExtractElementInst>(LHS) ||
5542 !L1->isIdenticalTo(cast<Instruction>(LHS)))
5543 return OperationData(V);
5544 } else {
5545 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
5546 return OperationData(V);
5547 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
5548 !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
5549 !L2->isIdenticalTo(cast<Instruction>(RHS)))
5550 return OperationData(V);
5552 switch (Pred) {
5553 default:
5554 return OperationData(V);
5556 case CmpInst::ICMP_ULT:
5557 case CmpInst::ICMP_ULE:
5558 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
5560 case CmpInst::ICMP_SLT:
5561 case CmpInst::ICMP_SLE:
5562 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
5564 case CmpInst::FCMP_OLT:
5565 case CmpInst::FCMP_OLE:
5566 case CmpInst::FCMP_ULT:
5567 case CmpInst::FCMP_ULE:
5568 return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
5569 cast<Instruction>(Cond)->hasNoNaNs());
5571 case CmpInst::ICMP_UGT:
5572 case CmpInst::ICMP_UGE:
5573 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
5575 case CmpInst::ICMP_SGT:
5576 case CmpInst::ICMP_SGE:
5577 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
5579 case CmpInst::FCMP_OGT:
5580 case CmpInst::FCMP_OGE:
5581 case CmpInst::FCMP_UGT:
5582 case CmpInst::FCMP_UGE:
5583 return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
5584 cast<Instruction>(Cond)->hasNoNaNs());
5588 return OperationData(V);
5591 public:
5592 HorizontalReduction() = default;
5594 /// Try to find a reduction tree.
5595 bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
5596 assert((!Phi || is_contained(Phi->operands(), B)) &&
5597 "Thi phi needs to use the binary operator");
5599 ReductionData = getOperationData(B);
5601 // We could have a initial reductions that is not an add.
5602 // r *= v1 + v2 + v3 + v4
5603 // In such a case start looking for a tree rooted in the first '+'.
5604 if (Phi) {
5605 if (ReductionData.getLHS() == Phi) {
5606 Phi = nullptr;
5607 B = dyn_cast<Instruction>(ReductionData.getRHS());
5608 ReductionData = getOperationData(B);
5609 } else if (ReductionData.getRHS() == Phi) {
5610 Phi = nullptr;
5611 B = dyn_cast<Instruction>(ReductionData.getLHS());
5612 ReductionData = getOperationData(B);
5616 if (!ReductionData.isVectorizable(B))
5617 return false;
5619 Type *Ty = B->getType();
5620 if (!isValidElementType(Ty))
5621 return false;
5622 if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
5623 return false;
5625 ReducedValueData.clear();
5626 ReductionRoot = B;
5628 // Post order traverse the reduction tree starting at B. We only handle true
5629 // trees containing only binary operators.
5630 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
5631 Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
5632 ReductionData.initReductionOps(ReductionOps);
5633 while (!Stack.empty()) {
5634 Instruction *TreeN = Stack.back().first;
5635 unsigned EdgeToVist = Stack.back().second++;
5636 OperationData OpData = getOperationData(TreeN);
5637 bool IsReducedValue = OpData != ReductionData;
5639 // Postorder vist.
5640 if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
5641 if (IsReducedValue)
5642 ReducedVals.push_back(TreeN);
5643 else {
5644 auto I = ExtraArgs.find(TreeN);
5645 if (I != ExtraArgs.end() && !I->second) {
5646 // Check if TreeN is an extra argument of its parent operation.
5647 if (Stack.size() <= 1) {
5648 // TreeN can't be an extra argument as it is a root reduction
5649 // operation.
5650 return false;
5652 // Yes, TreeN is an extra argument, do not add it to a list of
5653 // reduction operations.
5654 // Stack[Stack.size() - 2] always points to the parent operation.
5655 markExtraArg(Stack[Stack.size() - 2], TreeN);
5656 ExtraArgs.erase(TreeN);
5657 } else
5658 ReductionData.addReductionOps(TreeN, ReductionOps);
5660 // Retract.
5661 Stack.pop_back();
5662 continue;
5665 // Visit left or right.
5666 Value *NextV = TreeN->getOperand(EdgeToVist);
5667 if (NextV != Phi) {
5668 auto *I = dyn_cast<Instruction>(NextV);
5669 OpData = getOperationData(I);
5670 // Continue analysis if the next operand is a reduction operation or
5671 // (possibly) a reduced value. If the reduced value opcode is not set,
5672 // the first met operation != reduction operation is considered as the
5673 // reduced value class.
5674 if (I && (!ReducedValueData || OpData == ReducedValueData ||
5675 OpData == ReductionData)) {
5676 const bool IsReductionOperation = OpData == ReductionData;
5677 // Only handle trees in the current basic block.
5678 if (!ReductionData.hasSameParent(I, B->getParent(),
5679 IsReductionOperation)) {
5680 // I is an extra argument for TreeN (its parent operation).
5681 markExtraArg(Stack.back(), I);
5682 continue;
5685 // Each tree node needs to have minimal number of users except for the
5686 // ultimate reduction.
5687 if (!ReductionData.hasRequiredNumberOfUses(I,
5688 OpData == ReductionData) &&
5689 I != B) {
5690 // I is an extra argument for TreeN (its parent operation).
5691 markExtraArg(Stack.back(), I);
5692 continue;
5695 if (IsReductionOperation) {
5696 // We need to be able to reassociate the reduction operations.
5697 if (!OpData.isAssociative(I)) {
5698 // I is an extra argument for TreeN (its parent operation).
5699 markExtraArg(Stack.back(), I);
5700 continue;
5702 } else if (ReducedValueData &&
5703 ReducedValueData != OpData) {
5704 // Make sure that the opcodes of the operations that we are going to
5705 // reduce match.
5706 // I is an extra argument for TreeN (its parent operation).
5707 markExtraArg(Stack.back(), I);
5708 continue;
5709 } else if (!ReducedValueData)
5710 ReducedValueData = OpData;
5712 Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5713 continue;
5716 // NextV is an extra argument for TreeN (its parent operation).
5717 markExtraArg(Stack.back(), NextV);
5719 return true;
5722 /// Attempt to vectorize the tree found by
5723 /// matchAssociativeReduction.
5724 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
5725 if (ReducedVals.empty())
5726 return false;
5728 // If there is a sufficient number of reduction values, reduce
5729 // to a nearby power-of-2. Can safely generate oversized
5730 // vectors and rely on the backend to split them to legal sizes.
5731 unsigned NumReducedVals = ReducedVals.size();
5732 if (NumReducedVals < 4)
5733 return false;
5735 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
5737 Value *VectorizedTree = nullptr;
5738 IRBuilder<> Builder(ReductionRoot);
5739 FastMathFlags Unsafe;
5740 Unsafe.setFast();
5741 Builder.setFastMathFlags(Unsafe);
5742 unsigned i = 0;
5744 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
5745 // The same extra argument may be used several time, so log each attempt
5746 // to use it.
5747 for (auto &Pair : ExtraArgs)
5748 ExternallyUsedValues[Pair.second].push_back(Pair.first);
5749 SmallVector<Value *, 16> IgnoreList;
5750 for (auto &V : ReductionOps)
5751 IgnoreList.append(V.begin(), V.end());
5752 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5753 auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
5754 V.buildTree(VL, ExternallyUsedValues, IgnoreList);
5755 Optional<ArrayRef<unsigned>> Order = V.bestOrder();
5756 // TODO: Handle orders of size less than number of elements in the vector.
5757 if (Order && Order->size() == VL.size()) {
5758 // TODO: reorder tree nodes without tree rebuilding.
5759 SmallVector<Value *, 4> ReorderedOps(VL.size());
5760 llvm::transform(*Order, ReorderedOps.begin(),
5761 [VL](const unsigned Idx) { return VL[Idx]; });
5762 V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
5764 if (V.isTreeTinyAndNotFullyVectorizable())
5765 break;
5767 V.computeMinimumValueSizes();
5769 // Estimate cost.
5770 int TreeCost = V.getTreeCost();
5771 int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
5772 int Cost = TreeCost + ReductionCost;
5773 if (Cost >= -SLPCostThreshold) {
5774 V.getORE()->emit([&]() {
5775 return OptimizationRemarkMissed(
5776 SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
5777 << "Vectorizing horizontal reduction is possible"
5778 << "but not beneficial with cost "
5779 << ore::NV("Cost", Cost) << " and threshold "
5780 << ore::NV("Threshold", -SLPCostThreshold);
5782 break;
5785 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
5786 << Cost << ". (HorRdx)\n");
5787 V.getORE()->emit([&]() {
5788 return OptimizationRemark(
5789 SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
5790 << "Vectorized horizontal reduction with cost "
5791 << ore::NV("Cost", Cost) << " and with tree size "
5792 << ore::NV("TreeSize", V.getTreeSize());
5795 // Vectorize a tree.
5796 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
5797 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5799 // Emit a reduction.
5800 Value *ReducedSubTree =
5801 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
5802 if (VectorizedTree) {
5803 Builder.SetCurrentDebugLocation(Loc);
5804 OperationData VectReductionData(ReductionData.getOpcode(),
5805 VectorizedTree, ReducedSubTree,
5806 ReductionData.getKind());
5807 VectorizedTree =
5808 VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5809 } else
5810 VectorizedTree = ReducedSubTree;
5811 i += ReduxWidth;
5812 ReduxWidth = PowerOf2Floor(NumReducedVals - i);
5815 if (VectorizedTree) {
5816 // Finish the reduction.
5817 for (; i < NumReducedVals; ++i) {
5818 auto *I = cast<Instruction>(ReducedVals[i]);
5819 Builder.SetCurrentDebugLocation(I->getDebugLoc());
5820 OperationData VectReductionData(ReductionData.getOpcode(),
5821 VectorizedTree, I,
5822 ReductionData.getKind());
5823 VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
5825 for (auto &Pair : ExternallyUsedValues) {
5826 assert(!Pair.second.empty() &&
5827 "At least one DebugLoc must be inserted");
5828 // Add each externally used value to the final reduction.
5829 for (auto *I : Pair.second) {
5830 Builder.SetCurrentDebugLocation(I->getDebugLoc());
5831 OperationData VectReductionData(ReductionData.getOpcode(),
5832 VectorizedTree, Pair.first,
5833 ReductionData.getKind());
5834 VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
5837 // Update users.
5838 ReductionRoot->replaceAllUsesWith(VectorizedTree);
5840 return VectorizedTree != nullptr;
5843 unsigned numReductionValues() const {
5844 return ReducedVals.size();
5847 private:
5848 /// Calculate the cost of a reduction.
5849 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
5850 unsigned ReduxWidth) {
5851 Type *ScalarTy = FirstReducedVal->getType();
5852 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
5854 int PairwiseRdxCost;
5855 int SplittingRdxCost;
5856 switch (ReductionData.getKind()) {
5857 case RK_Arithmetic:
5858 PairwiseRdxCost =
5859 TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5860 /*IsPairwiseForm=*/true);
5861 SplittingRdxCost =
5862 TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5863 /*IsPairwiseForm=*/false);
5864 break;
5865 case RK_Min:
5866 case RK_Max:
5867 case RK_UMin:
5868 case RK_UMax: {
5869 Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
5870 bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
5871 ReductionData.getKind() == RK_UMax;
5872 PairwiseRdxCost =
5873 TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5874 /*IsPairwiseForm=*/true, IsUnsigned);
5875 SplittingRdxCost =
5876 TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5877 /*IsPairwiseForm=*/false, IsUnsigned);
5878 break;
5880 case RK_None:
5881 llvm_unreachable("Expected arithmetic or min/max reduction operation");
5884 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5885 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5887 int ScalarReduxCost;
5888 switch (ReductionData.getKind()) {
5889 case RK_Arithmetic:
5890 ScalarReduxCost =
5891 TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
5892 break;
5893 case RK_Min:
5894 case RK_Max:
5895 case RK_UMin:
5896 case RK_UMax:
5897 ScalarReduxCost =
5898 TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
5899 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
5900 CmpInst::makeCmpResultType(ScalarTy));
5901 break;
5902 case RK_None:
5903 llvm_unreachable("Expected arithmetic or min/max reduction operation");
5905 ScalarReduxCost *= (ReduxWidth - 1);
5907 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
5908 << " for reduction that starts with " << *FirstReducedVal
5909 << " (It is a "
5910 << (IsPairwiseReduction ? "pairwise" : "splitting")
5911 << " reduction)\n");
5913 return VecReduxCost - ScalarReduxCost;
5916 /// Emit a horizontal reduction of the vectorized value.
5917 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
5918 unsigned ReduxWidth, const TargetTransformInfo *TTI) {
5919 assert(VectorizedValue && "Need to have a vectorized tree node");
5920 assert(isPowerOf2_32(ReduxWidth) &&
5921 "We only handle power-of-two reductions for now");
5923 if (!IsPairwiseReduction)
5924 return createSimpleTargetReduction(
5925 Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
5926 ReductionData.getFlags(), ReductionOps.back());
5928 Value *TmpVec = VectorizedValue;
5929 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5930 Value *LeftMask =
5931 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
5932 Value *RightMask =
5933 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
5935 Value *LeftShuf = Builder.CreateShuffleVector(
5936 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
5937 Value *RightShuf = Builder.CreateShuffleVector(
5938 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
5939 "rdx.shuf.r");
5940 OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
5941 RightShuf, ReductionData.getKind());
5942 TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5945 // The result is in the first element of the vector.
5946 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
5950 } // end anonymous namespace
5952 /// Recognize construction of vectors like
5953 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
5954 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
5955 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
5956 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
5957 /// starting from the last insertelement instruction.
5959 /// Returns true if it matches
5960 static bool findBuildVector(InsertElementInst *LastInsertElem,
5961 TargetTransformInfo *TTI,
5962 SmallVectorImpl<Value *> &BuildVectorOpds,
5963 int &UserCost) {
5964 UserCost = 0;
5965 Value *V = nullptr;
5966 do {
5967 if (auto *CI = dyn_cast<ConstantInt>(LastInsertElem->getOperand(2))) {
5968 UserCost += TTI->getVectorInstrCost(Instruction::InsertElement,
5969 LastInsertElem->getType(),
5970 CI->getZExtValue());
5972 BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
5973 V = LastInsertElem->getOperand(0);
5974 if (isa<UndefValue>(V))
5975 break;
5976 LastInsertElem = dyn_cast<InsertElementInst>(V);
5977 if (!LastInsertElem || !LastInsertElem->hasOneUse())
5978 return false;
5979 } while (true);
5980 std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5981 return true;
5984 /// Like findBuildVector, but looks for construction of aggregate.
5986 /// \return true if it matches.
5987 static bool findBuildAggregate(InsertValueInst *IV,
5988 SmallVectorImpl<Value *> &BuildVectorOpds) {
5989 Value *V;
5990 do {
5991 BuildVectorOpds.push_back(IV->getInsertedValueOperand());
5992 V = IV->getAggregateOperand();
5993 if (isa<UndefValue>(V))
5994 break;
5995 IV = dyn_cast<InsertValueInst>(V);
5996 if (!IV || !IV->hasOneUse())
5997 return false;
5998 } while (true);
5999 std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
6000 return true;
6003 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
6004 return V->getType() < V2->getType();
6007 /// Try and get a reduction value from a phi node.
6009 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
6010 /// if they come from either \p ParentBB or a containing loop latch.
6012 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
6013 /// if not possible.
6014 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
6015 BasicBlock *ParentBB, LoopInfo *LI) {
6016 // There are situations where the reduction value is not dominated by the
6017 // reduction phi. Vectorizing such cases has been reported to cause
6018 // miscompiles. See PR25787.
6019 auto DominatedReduxValue = [&](Value *R) {
6020 return isa<Instruction>(R) &&
6021 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
6024 Value *Rdx = nullptr;
6026 // Return the incoming value if it comes from the same BB as the phi node.
6027 if (P->getIncomingBlock(0) == ParentBB) {
6028 Rdx = P->getIncomingValue(0);
6029 } else if (P->getIncomingBlock(1) == ParentBB) {
6030 Rdx = P->getIncomingValue(1);
6033 if (Rdx && DominatedReduxValue(Rdx))
6034 return Rdx;
6036 // Otherwise, check whether we have a loop latch to look at.
6037 Loop *BBL = LI->getLoopFor(ParentBB);
6038 if (!BBL)
6039 return nullptr;
6040 BasicBlock *BBLatch = BBL->getLoopLatch();
6041 if (!BBLatch)
6042 return nullptr;
6044 // There is a loop latch, return the incoming value if it comes from
6045 // that. This reduction pattern occasionally turns up.
6046 if (P->getIncomingBlock(0) == BBLatch) {
6047 Rdx = P->getIncomingValue(0);
6048 } else if (P->getIncomingBlock(1) == BBLatch) {
6049 Rdx = P->getIncomingValue(1);
6052 if (Rdx && DominatedReduxValue(Rdx))
6053 return Rdx;
6055 return nullptr;
6058 /// Attempt to reduce a horizontal reduction.
6059 /// If it is legal to match a horizontal reduction feeding the phi node \a P
6060 /// with reduction operators \a Root (or one of its operands) in a basic block
6061 /// \a BB, then check if it can be done. If horizontal reduction is not found
6062 /// and root instruction is a binary operation, vectorization of the operands is
6063 /// attempted.
6064 /// \returns true if a horizontal reduction was matched and reduced or operands
6065 /// of one of the binary instruction were vectorized.
6066 /// \returns false if a horizontal reduction was not matched (or not possible)
6067 /// or no vectorization of any binary operation feeding \a Root instruction was
6068 /// performed.
6069 static bool tryToVectorizeHorReductionOrInstOperands(
6070 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
6071 TargetTransformInfo *TTI,
6072 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
6073 if (!ShouldVectorizeHor)
6074 return false;
6076 if (!Root)
6077 return false;
6079 if (Root->getParent() != BB || isa<PHINode>(Root))
6080 return false;
6081 // Start analysis starting from Root instruction. If horizontal reduction is
6082 // found, try to vectorize it. If it is not a horizontal reduction or
6083 // vectorization is not possible or not effective, and currently analyzed
6084 // instruction is a binary operation, try to vectorize the operands, using
6085 // pre-order DFS traversal order. If the operands were not vectorized, repeat
6086 // the same procedure considering each operand as a possible root of the
6087 // horizontal reduction.
6088 // Interrupt the process if the Root instruction itself was vectorized or all
6089 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
6090 SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
6091 SmallPtrSet<Value *, 8> VisitedInstrs;
6092 bool Res = false;
6093 while (!Stack.empty()) {
6094 Value *V;
6095 unsigned Level;
6096 std::tie(V, Level) = Stack.pop_back_val();
6097 if (!V)
6098 continue;
6099 auto *Inst = dyn_cast<Instruction>(V);
6100 if (!Inst)
6101 continue;
6102 auto *BI = dyn_cast<BinaryOperator>(Inst);
6103 auto *SI = dyn_cast<SelectInst>(Inst);
6104 if (BI || SI) {
6105 HorizontalReduction HorRdx;
6106 if (HorRdx.matchAssociativeReduction(P, Inst)) {
6107 if (HorRdx.tryToReduce(R, TTI)) {
6108 Res = true;
6109 // Set P to nullptr to avoid re-analysis of phi node in
6110 // matchAssociativeReduction function unless this is the root node.
6111 P = nullptr;
6112 continue;
6115 if (P && BI) {
6116 Inst = dyn_cast<Instruction>(BI->getOperand(0));
6117 if (Inst == P)
6118 Inst = dyn_cast<Instruction>(BI->getOperand(1));
6119 if (!Inst) {
6120 // Set P to nullptr to avoid re-analysis of phi node in
6121 // matchAssociativeReduction function unless this is the root node.
6122 P = nullptr;
6123 continue;
6127 // Set P to nullptr to avoid re-analysis of phi node in
6128 // matchAssociativeReduction function unless this is the root node.
6129 P = nullptr;
6130 if (Vectorize(Inst, R)) {
6131 Res = true;
6132 continue;
6135 // Try to vectorize operands.
6136 // Continue analysis for the instruction from the same basic block only to
6137 // save compile time.
6138 if (++Level < RecursionMaxDepth)
6139 for (auto *Op : Inst->operand_values())
6140 if (VisitedInstrs.insert(Op).second)
6141 if (auto *I = dyn_cast<Instruction>(Op))
6142 if (!isa<PHINode>(I) && I->getParent() == BB)
6143 Stack.emplace_back(Op, Level);
6145 return Res;
6148 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
6149 BasicBlock *BB, BoUpSLP &R,
6150 TargetTransformInfo *TTI) {
6151 if (!V)
6152 return false;
6153 auto *I = dyn_cast<Instruction>(V);
6154 if (!I)
6155 return false;
6157 if (!isa<BinaryOperator>(I))
6158 P = nullptr;
6159 // Try to match and vectorize a horizontal reduction.
6160 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
6161 return tryToVectorize(I, R);
6163 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
6164 ExtraVectorization);
6167 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
6168 BasicBlock *BB, BoUpSLP &R) {
6169 const DataLayout &DL = BB->getModule()->getDataLayout();
6170 if (!R.canMapToVector(IVI->getType(), DL))
6171 return false;
6173 SmallVector<Value *, 16> BuildVectorOpds;
6174 if (!findBuildAggregate(IVI, BuildVectorOpds))
6175 return false;
6177 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
6178 // Aggregate value is unlikely to be processed in vector register, we need to
6179 // extract scalars into scalar registers, so NeedExtraction is set true.
6180 return tryToVectorizeList(BuildVectorOpds, R);
6183 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
6184 BasicBlock *BB, BoUpSLP &R) {
6185 int UserCost;
6186 SmallVector<Value *, 16> BuildVectorOpds;
6187 if (!findBuildVector(IEI, TTI, BuildVectorOpds, UserCost) ||
6188 (llvm::all_of(BuildVectorOpds,
6189 [](Value *V) { return isa<ExtractElementInst>(V); }) &&
6190 isShuffle(BuildVectorOpds)))
6191 return false;
6193 // Vectorize starting with the build vector operands ignoring the BuildVector
6194 // instructions for the purpose of scheduling and user extraction.
6195 return tryToVectorizeList(BuildVectorOpds, R, UserCost);
6198 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
6199 BoUpSLP &R) {
6200 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
6201 return true;
6203 bool OpsChanged = false;
6204 for (int Idx = 0; Idx < 2; ++Idx) {
6205 OpsChanged |=
6206 vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
6208 return OpsChanged;
6211 bool SLPVectorizerPass::vectorizeSimpleInstructions(
6212 SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
6213 bool OpsChanged = false;
6214 for (auto &VH : reverse(Instructions)) {
6215 auto *I = dyn_cast_or_null<Instruction>(VH);
6216 if (!I)
6217 continue;
6218 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
6219 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
6220 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
6221 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
6222 else if (auto *CI = dyn_cast<CmpInst>(I))
6223 OpsChanged |= vectorizeCmpInst(CI, BB, R);
6225 Instructions.clear();
6226 return OpsChanged;
6229 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
6230 bool Changed = false;
6231 SmallVector<Value *, 4> Incoming;
6232 SmallPtrSet<Value *, 16> VisitedInstrs;
6234 bool HaveVectorizedPhiNodes = true;
6235 while (HaveVectorizedPhiNodes) {
6236 HaveVectorizedPhiNodes = false;
6238 // Collect the incoming values from the PHIs.
6239 Incoming.clear();
6240 for (Instruction &I : *BB) {
6241 PHINode *P = dyn_cast<PHINode>(&I);
6242 if (!P)
6243 break;
6245 if (!VisitedInstrs.count(P))
6246 Incoming.push_back(P);
6249 // Sort by type.
6250 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
6252 // Try to vectorize elements base on their type.
6253 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
6254 E = Incoming.end();
6255 IncIt != E;) {
6257 // Look for the next elements with the same type.
6258 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
6259 while (SameTypeIt != E &&
6260 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
6261 VisitedInstrs.insert(*SameTypeIt);
6262 ++SameTypeIt;
6265 // Try to vectorize them.
6266 unsigned NumElts = (SameTypeIt - IncIt);
6267 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
6268 << NumElts << ")\n");
6269 // The order in which the phi nodes appear in the program does not matter.
6270 // So allow tryToVectorizeList to reorder them if it is beneficial. This
6271 // is done when there are exactly two elements since tryToVectorizeList
6272 // asserts that there are only two values when AllowReorder is true.
6273 bool AllowReorder = NumElts == 2;
6274 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
6275 /*UserCost=*/0, AllowReorder)) {
6276 // Success start over because instructions might have been changed.
6277 HaveVectorizedPhiNodes = true;
6278 Changed = true;
6279 break;
6282 // Start over at the next instruction of a different type (or the end).
6283 IncIt = SameTypeIt;
6287 VisitedInstrs.clear();
6289 SmallVector<WeakVH, 8> PostProcessInstructions;
6290 SmallDenseSet<Instruction *, 4> KeyNodes;
6291 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
6292 // We may go through BB multiple times so skip the one we have checked.
6293 if (!VisitedInstrs.insert(&*it).second) {
6294 if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
6295 vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
6296 // We would like to start over since some instructions are deleted
6297 // and the iterator may become invalid value.
6298 Changed = true;
6299 it = BB->begin();
6300 e = BB->end();
6302 continue;
6305 if (isa<DbgInfoIntrinsic>(it))
6306 continue;
6308 // Try to vectorize reductions that use PHINodes.
6309 if (PHINode *P = dyn_cast<PHINode>(it)) {
6310 // Check that the PHI is a reduction PHI.
6311 if (P->getNumIncomingValues() != 2)
6312 return Changed;
6314 // Try to match and vectorize a horizontal reduction.
6315 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
6316 TTI)) {
6317 Changed = true;
6318 it = BB->begin();
6319 e = BB->end();
6320 continue;
6322 continue;
6325 // Ran into an instruction without users, like terminator, or function call
6326 // with ignored return value, store. Ignore unused instructions (basing on
6327 // instruction type, except for CallInst and InvokeInst).
6328 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
6329 isa<InvokeInst>(it))) {
6330 KeyNodes.insert(&*it);
6331 bool OpsChanged = false;
6332 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
6333 for (auto *V : it->operand_values()) {
6334 // Try to match and vectorize a horizontal reduction.
6335 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
6338 // Start vectorization of post-process list of instructions from the
6339 // top-tree instructions to try to vectorize as many instructions as
6340 // possible.
6341 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
6342 if (OpsChanged) {
6343 // We would like to start over since some instructions are deleted
6344 // and the iterator may become invalid value.
6345 Changed = true;
6346 it = BB->begin();
6347 e = BB->end();
6348 continue;
6352 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
6353 isa<InsertValueInst>(it))
6354 PostProcessInstructions.push_back(&*it);
6357 return Changed;
6360 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
6361 auto Changed = false;
6362 for (auto &Entry : GEPs) {
6363 // If the getelementptr list has fewer than two elements, there's nothing
6364 // to do.
6365 if (Entry.second.size() < 2)
6366 continue;
6368 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
6369 << Entry.second.size() << ".\n");
6371 // We process the getelementptr list in chunks of 16 (like we do for
6372 // stores) to minimize compile-time.
6373 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
6374 auto Len = std::min<unsigned>(BE - BI, 16);
6375 auto GEPList = makeArrayRef(&Entry.second[BI], Len);
6377 // Initialize a set a candidate getelementptrs. Note that we use a
6378 // SetVector here to preserve program order. If the index computations
6379 // are vectorizable and begin with loads, we want to minimize the chance
6380 // of having to reorder them later.
6381 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
6383 // Some of the candidates may have already been vectorized after we
6384 // initially collected them. If so, the WeakTrackingVHs will have
6385 // nullified the
6386 // values, so remove them from the set of candidates.
6387 Candidates.remove(nullptr);
6389 // Remove from the set of candidates all pairs of getelementptrs with
6390 // constant differences. Such getelementptrs are likely not good
6391 // candidates for vectorization in a bottom-up phase since one can be
6392 // computed from the other. We also ensure all candidate getelementptr
6393 // indices are unique.
6394 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
6395 auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
6396 if (!Candidates.count(GEPI))
6397 continue;
6398 auto *SCEVI = SE->getSCEV(GEPList[I]);
6399 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
6400 auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
6401 auto *SCEVJ = SE->getSCEV(GEPList[J]);
6402 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
6403 Candidates.remove(GEPList[I]);
6404 Candidates.remove(GEPList[J]);
6405 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
6406 Candidates.remove(GEPList[J]);
6411 // We break out of the above computation as soon as we know there are
6412 // fewer than two candidates remaining.
6413 if (Candidates.size() < 2)
6414 continue;
6416 // Add the single, non-constant index of each candidate to the bundle. We
6417 // ensured the indices met these constraints when we originally collected
6418 // the getelementptrs.
6419 SmallVector<Value *, 16> Bundle(Candidates.size());
6420 auto BundleIndex = 0u;
6421 for (auto *V : Candidates) {
6422 auto *GEP = cast<GetElementPtrInst>(V);
6423 auto *GEPIdx = GEP->idx_begin()->get();
6424 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
6425 Bundle[BundleIndex++] = GEPIdx;
6428 // Try and vectorize the indices. We are currently only interested in
6429 // gather-like cases of the form:
6431 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
6433 // where the loads of "a", the loads of "b", and the subtractions can be
6434 // performed in parallel. It's likely that detecting this pattern in a
6435 // bottom-up phase will be simpler and less costly than building a
6436 // full-blown top-down phase beginning at the consecutive loads.
6437 Changed |= tryToVectorizeList(Bundle, R);
6440 return Changed;
6443 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
6444 bool Changed = false;
6445 // Attempt to sort and vectorize each of the store-groups.
6446 for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
6447 ++it) {
6448 if (it->second.size() < 2)
6449 continue;
6451 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
6452 << it->second.size() << ".\n");
6454 // Process the stores in chunks of 16.
6455 // TODO: The limit of 16 inhibits greater vectorization factors.
6456 // For example, AVX2 supports v32i8. Increasing this limit, however,
6457 // may cause a significant compile-time increase.
6458 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI += 16) {
6459 unsigned Len = std::min<unsigned>(CE - CI, 16);
6460 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
6463 return Changed;
6466 char SLPVectorizer::ID = 0;
6468 static const char lv_name[] = "SLP Vectorizer";
6470 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
6471 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6472 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6473 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6474 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6475 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6476 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
6477 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
6478 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
6480 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }