1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/CodeMetrics.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/Verifier.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Utils/VectorUtils.h"
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
56 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
59 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
60 cl::desc("Only vectorize if you gain more than this "
64 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
65 cl::desc("Attempt to vectorize horizontal reductions"));
67 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
68 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
70 "Attempt to vectorize horizontal reductions feeding into a store"));
74 static const unsigned MinVecRegSize = 128;
76 static const unsigned RecursionMaxDepth = 12;
78 // Limit the number of alias checks. The limit is chosen so that
79 // it has no negative effect on the llvm benchmarks.
80 static const unsigned AliasedCheckLimit = 10;
82 /// \returns the parent basic block if all of the instructions in \p VL
83 /// are in the same block or null otherwise.
84 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
85 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
88 BasicBlock *BB = I0->getParent();
89 for (int i = 1, e = VL.size(); i < e; i++) {
90 Instruction *I = dyn_cast<Instruction>(VL[i]);
94 if (BB != I->getParent())
100 /// \returns True if all of the values in \p VL are constants.
101 static bool allConstant(ArrayRef<Value *> VL) {
102 for (unsigned i = 0, e = VL.size(); i < e; ++i)
103 if (!isa<Constant>(VL[i]))
108 /// \returns True if all of the values in \p VL are identical.
109 static bool isSplat(ArrayRef<Value *> VL) {
110 for (unsigned i = 1, e = VL.size(); i < e; ++i)
116 ///\returns Opcode that can be clubbed with \p Op to create an alternate
117 /// sequence which can later be merged as a ShuffleVector instruction.
118 static unsigned getAltOpcode(unsigned Op) {
120 case Instruction::FAdd:
121 return Instruction::FSub;
122 case Instruction::FSub:
123 return Instruction::FAdd;
124 case Instruction::Add:
125 return Instruction::Sub;
126 case Instruction::Sub:
127 return Instruction::Add;
133 ///\returns bool representing if Opcode \p Op can be part
134 /// of an alternate sequence which can later be merged as
135 /// a ShuffleVector instruction.
136 static bool canCombineAsAltInst(unsigned Op) {
137 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
138 Op == Instruction::Sub || Op == Instruction::Add)
143 /// \returns ShuffleVector instruction if intructions in \p VL have
144 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
145 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
146 static unsigned isAltInst(ArrayRef<Value *> VL) {
147 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
148 unsigned Opcode = I0->getOpcode();
149 unsigned AltOpcode = getAltOpcode(Opcode);
150 for (int i = 1, e = VL.size(); i < e; i++) {
151 Instruction *I = dyn_cast<Instruction>(VL[i]);
152 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
155 return Instruction::ShuffleVector;
158 /// \returns The opcode if all of the Instructions in \p VL have the same
160 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
161 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
164 unsigned Opcode = I0->getOpcode();
165 for (int i = 1, e = VL.size(); i < e; i++) {
166 Instruction *I = dyn_cast<Instruction>(VL[i]);
167 if (!I || Opcode != I->getOpcode()) {
168 if (canCombineAsAltInst(Opcode) && i == 1)
169 return isAltInst(VL);
176 /// Get the intersection (logical and) of all of the potential IR flags
177 /// of each scalar operation (VL) that will be converted into a vector (I).
178 /// Flag set: NSW, NUW, exact, and all of fast-math.
179 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
180 if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
181 if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
182 // Intersection is initialized to the 0th scalar,
183 // so start counting from index '1'.
184 for (int i = 1, e = VL.size(); i < e; ++i) {
185 if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
186 Intersection->andIRFlags(Scalar);
188 VecOp->copyIRFlags(Intersection);
193 /// \returns \p I after propagating metadata from \p VL.
194 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
195 Instruction *I0 = cast<Instruction>(VL[0]);
196 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
197 I0->getAllMetadataOtherThanDebugLoc(Metadata);
199 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
200 unsigned Kind = Metadata[i].first;
201 MDNode *MD = Metadata[i].second;
203 for (int i = 1, e = VL.size(); MD && i != e; i++) {
204 Instruction *I = cast<Instruction>(VL[i]);
205 MDNode *IMD = I->getMetadata(Kind);
209 MD = nullptr; // Remove unknown metadata
211 case LLVMContext::MD_tbaa:
212 MD = MDNode::getMostGenericTBAA(MD, IMD);
214 case LLVMContext::MD_alias_scope:
215 case LLVMContext::MD_noalias:
216 MD = MDNode::intersect(MD, IMD);
218 case LLVMContext::MD_fpmath:
219 MD = MDNode::getMostGenericFPMath(MD, IMD);
223 I->setMetadata(Kind, MD);
228 /// \returns The type that all of the values in \p VL have or null if there
229 /// are different types.
230 static Type* getSameType(ArrayRef<Value *> VL) {
231 Type *Ty = VL[0]->getType();
232 for (int i = 1, e = VL.size(); i < e; i++)
233 if (VL[i]->getType() != Ty)
239 /// \returns True if the ExtractElement instructions in VL can be vectorized
240 /// to use the original vector.
241 static bool CanReuseExtract(ArrayRef<Value *> VL) {
242 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
243 // Check if all of the extracts come from the same vector and from the
246 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
247 Value *Vec = E0->getOperand(0);
249 // We have to extract from the same vector type.
250 unsigned NElts = Vec->getType()->getVectorNumElements();
252 if (NElts != VL.size())
255 // Check that all of the indices extract from the correct offset.
256 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
257 if (!CI || CI->getZExtValue())
260 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
261 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
262 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
264 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
271 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
272 SmallVectorImpl<Value *> &Left,
273 SmallVectorImpl<Value *> &Right) {
275 SmallVector<Value *, 16> OrigLeft, OrigRight;
277 bool AllSameOpcodeLeft = true;
278 bool AllSameOpcodeRight = true;
279 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
280 Instruction *I = cast<Instruction>(VL[i]);
281 Value *V0 = I->getOperand(0);
282 Value *V1 = I->getOperand(1);
284 OrigLeft.push_back(V0);
285 OrigRight.push_back(V1);
287 Instruction *I0 = dyn_cast<Instruction>(V0);
288 Instruction *I1 = dyn_cast<Instruction>(V1);
290 // Check whether all operands on one side have the same opcode. In this case
291 // we want to preserve the original order and not make things worse by
293 AllSameOpcodeLeft = I0;
294 AllSameOpcodeRight = I1;
296 if (i && AllSameOpcodeLeft) {
297 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
298 if(P0->getOpcode() != I0->getOpcode())
299 AllSameOpcodeLeft = false;
301 AllSameOpcodeLeft = false;
303 if (i && AllSameOpcodeRight) {
304 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
305 if(P1->getOpcode() != I1->getOpcode())
306 AllSameOpcodeRight = false;
308 AllSameOpcodeRight = false;
311 // Sort two opcodes. In the code below we try to preserve the ability to use
312 // broadcast of values instead of individual inserts.
319 // If we just sorted according to opcode we would leave the first line in
320 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
323 // Because vr2 and vr1 are from the same load we loose the opportunity of a
324 // broadcast for the packed right side in the backend: we have [vr1, vl2]
325 // instead of [vr1, vr2=vr1].
327 if(!i && I0->getOpcode() > I1->getOpcode()) {
330 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
331 // Try not to destroy a broad cast for no apparent benefit.
334 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
335 // Try preserve broadcasts.
338 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
339 // Try preserve broadcasts.
348 // One opcode, put the instruction on the right.
358 bool LeftBroadcast = isSplat(Left);
359 bool RightBroadcast = isSplat(Right);
361 // Don't reorder if the operands where good to begin with.
362 if (!(LeftBroadcast || RightBroadcast) &&
363 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
369 /// \returns True if in-tree use also needs extract. This refers to
370 /// possible scalar operand in vectorized instruction.
371 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
372 TargetLibraryInfo *TLI) {
374 unsigned Opcode = UserInst->getOpcode();
376 case Instruction::Load: {
377 LoadInst *LI = cast<LoadInst>(UserInst);
378 return (LI->getPointerOperand() == Scalar);
380 case Instruction::Store: {
381 StoreInst *SI = cast<StoreInst>(UserInst);
382 return (SI->getPointerOperand() == Scalar);
384 case Instruction::Call: {
385 CallInst *CI = cast<CallInst>(UserInst);
386 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
387 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
388 return (CI->getArgOperand(1) == Scalar);
396 /// \returns the AA location that is being access by the instruction.
397 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
398 if (StoreInst *SI = dyn_cast<StoreInst>(I))
399 return AA->getLocation(SI);
400 if (LoadInst *LI = dyn_cast<LoadInst>(I))
401 return AA->getLocation(LI);
402 return AliasAnalysis::Location();
405 /// Bottom Up SLP Vectorizer.
408 typedef SmallVector<Value *, 8> ValueList;
409 typedef SmallVector<Instruction *, 16> InstrList;
410 typedef SmallPtrSet<Value *, 16> ValueSet;
411 typedef SmallVector<StoreInst *, 8> StoreList;
413 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
414 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
415 LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC)
416 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
417 SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
418 Builder(Se->getContext()) {
419 CodeMetrics::collectEphemeralValues(F, AC, EphValues);
422 /// \brief Vectorize the tree that starts with the elements in \p VL.
423 /// Returns the vectorized root.
424 Value *vectorizeTree();
426 /// \returns the cost incurred by unwanted spills and fills, caused by
427 /// holding live values over call sites.
430 /// \returns the vectorization cost of the subtree that starts at \p VL.
431 /// A negative number means that this is profitable.
434 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
435 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
436 void buildTree(ArrayRef<Value *> Roots,
437 ArrayRef<Value *> UserIgnoreLst = None);
439 /// Clear the internal data structures that are created by 'buildTree'.
441 VectorizableTree.clear();
442 ScalarToTreeEntry.clear();
444 ExternalUses.clear();
445 NumLoadsWantToKeepOrder = 0;
446 NumLoadsWantToChangeOrder = 0;
447 for (auto &Iter : BlocksSchedules) {
448 BlockScheduling *BS = Iter.second.get();
453 /// \returns true if the memory operations A and B are consecutive.
454 bool isConsecutiveAccess(Value *A, Value *B);
456 /// \brief Perform LICM and CSE on the newly generated gather sequences.
457 void optimizeGatherSequence();
459 /// \returns true if it is benefitial to reverse the vector order.
460 bool shouldReorder() const {
461 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
467 /// \returns the cost of the vectorizable entry.
468 int getEntryCost(TreeEntry *E);
470 /// This is the recursive part of buildTree.
471 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
473 /// Vectorize a single entry in the tree.
474 Value *vectorizeTree(TreeEntry *E);
476 /// Vectorize a single entry in the tree, starting in \p VL.
477 Value *vectorizeTree(ArrayRef<Value *> VL);
479 /// \returns the pointer to the vectorized value if \p VL is already
480 /// vectorized, or NULL. They may happen in cycles.
481 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
483 /// \brief Take the pointer operand from the Load/Store instruction.
484 /// \returns NULL if this is not a valid Load/Store instruction.
485 static Value *getPointerOperand(Value *I);
487 /// \brief Take the address space operand from the Load/Store instruction.
488 /// \returns -1 if this is not a valid Load/Store instruction.
489 static unsigned getAddressSpaceOperand(Value *I);
491 /// \returns the scalarization cost for this type. Scalarization in this
492 /// context means the creation of vectors from a group of scalars.
493 int getGatherCost(Type *Ty);
495 /// \returns the scalarization cost for this list of values. Assuming that
496 /// this subtree gets vectorized, we may need to extract the values from the
497 /// roots. This method calculates the cost of extracting the values.
498 int getGatherCost(ArrayRef<Value *> VL);
500 /// \brief Set the Builder insert point to one after the last instruction in
502 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
504 /// \returns a vector from a collection of scalars in \p VL.
505 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
507 /// \returns whether the VectorizableTree is fully vectoriable and will
508 /// be beneficial even the tree height is tiny.
509 bool isFullyVectorizableTinyTree();
512 TreeEntry() : Scalars(), VectorizedValue(nullptr),
515 /// \returns true if the scalars in VL are equal to this entry.
516 bool isSame(ArrayRef<Value *> VL) const {
517 assert(VL.size() == Scalars.size() && "Invalid size");
518 return std::equal(VL.begin(), VL.end(), Scalars.begin());
521 /// A vector of scalars.
524 /// The Scalars are vectorized into this value. It is initialized to Null.
525 Value *VectorizedValue;
527 /// Do we need to gather this sequence ?
531 /// Create a new VectorizableTree entry.
532 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
533 VectorizableTree.push_back(TreeEntry());
534 int idx = VectorizableTree.size() - 1;
535 TreeEntry *Last = &VectorizableTree[idx];
536 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
537 Last->NeedToGather = !Vectorized;
539 for (int i = 0, e = VL.size(); i != e; ++i) {
540 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
541 ScalarToTreeEntry[VL[i]] = idx;
544 MustGather.insert(VL.begin(), VL.end());
549 /// -- Vectorization State --
550 /// Holds all of the tree entries.
551 std::vector<TreeEntry> VectorizableTree;
553 /// Maps a specific scalar to its tree entry.
554 SmallDenseMap<Value*, int> ScalarToTreeEntry;
556 /// A list of scalars that we found that we need to keep as scalars.
559 /// This POD struct describes one external user in the vectorized tree.
560 struct ExternalUser {
561 ExternalUser (Value *S, llvm::User *U, int L) :
562 Scalar(S), User(U), Lane(L){};
563 // Which scalar in our function.
565 // Which user that uses the scalar.
567 // Which lane does the scalar belong to.
570 typedef SmallVector<ExternalUser, 16> UserList;
572 /// Checks if two instructions may access the same memory.
574 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
575 /// is invariant in the calling loop.
576 bool isAliased(const AliasAnalysis::Location &Loc1, Instruction *Inst1,
577 Instruction *Inst2) {
579 // First check if the result is already in the cache.
580 AliasCacheKey key = std::make_pair(Inst1, Inst2);
581 Optional<bool> &result = AliasCache[key];
582 if (result.hasValue()) {
583 return result.getValue();
585 AliasAnalysis::Location Loc2 = getLocation(Inst2, AA);
587 if (Loc1.Ptr && Loc2.Ptr) {
588 // Do the alias check.
589 aliased = AA->alias(Loc1, Loc2);
591 // Store the result in the cache.
596 typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
598 /// Cache for alias results.
599 /// TODO: consider moving this to the AliasAnalysis itself.
600 DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
602 /// Removes an instruction from its block and eventually deletes it.
603 /// It's like Instruction::eraseFromParent() except that the actual deletion
604 /// is delayed until BoUpSLP is destructed.
605 /// This is required to ensure that there are no incorrect collisions in the
606 /// AliasCache, which can happen if a new instruction is allocated at the
607 /// same address as a previously deleted instruction.
608 void eraseInstruction(Instruction *I) {
609 I->removeFromParent();
610 I->dropAllReferences();
611 DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
614 /// Temporary store for deleted instructions. Instructions will be deleted
615 /// eventually when the BoUpSLP is destructed.
616 SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
618 /// A list of values that need to extracted out of the tree.
619 /// This list holds pairs of (Internal Scalar : External User).
620 UserList ExternalUses;
622 /// Values used only by @llvm.assume calls.
623 SmallPtrSet<const Value *, 32> EphValues;
625 /// Holds all of the instructions that we gathered.
626 SetVector<Instruction *> GatherSeq;
627 /// A list of blocks that we are going to CSE.
628 SetVector<BasicBlock *> CSEBlocks;
630 /// Contains all scheduling relevant data for an instruction.
631 /// A ScheduleData either represents a single instruction or a member of an
632 /// instruction bundle (= a group of instructions which is combined into a
633 /// vector instruction).
634 struct ScheduleData {
636 // The initial value for the dependency counters. It means that the
637 // dependencies are not calculated yet.
638 enum { InvalidDeps = -1 };
641 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
642 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
643 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
644 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
646 void init(int BlockSchedulingRegionID) {
647 FirstInBundle = this;
648 NextInBundle = nullptr;
649 NextLoadStore = nullptr;
651 SchedulingRegionID = BlockSchedulingRegionID;
652 UnscheduledDepsInBundle = UnscheduledDeps;
656 /// Returns true if the dependency information has been calculated.
657 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
659 /// Returns true for single instructions and for bundle representatives
660 /// (= the head of a bundle).
661 bool isSchedulingEntity() const { return FirstInBundle == this; }
663 /// Returns true if it represents an instruction bundle and not only a
664 /// single instruction.
665 bool isPartOfBundle() const {
666 return NextInBundle != nullptr || FirstInBundle != this;
669 /// Returns true if it is ready for scheduling, i.e. it has no more
670 /// unscheduled depending instructions/bundles.
671 bool isReady() const {
672 assert(isSchedulingEntity() &&
673 "can't consider non-scheduling entity for ready list");
674 return UnscheduledDepsInBundle == 0 && !IsScheduled;
677 /// Modifies the number of unscheduled dependencies, also updating it for
678 /// the whole bundle.
679 int incrementUnscheduledDeps(int Incr) {
680 UnscheduledDeps += Incr;
681 return FirstInBundle->UnscheduledDepsInBundle += Incr;
684 /// Sets the number of unscheduled dependencies to the number of
686 void resetUnscheduledDeps() {
687 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
690 /// Clears all dependency information.
691 void clearDependencies() {
692 Dependencies = InvalidDeps;
693 resetUnscheduledDeps();
694 MemoryDependencies.clear();
697 void dump(raw_ostream &os) const {
698 if (!isSchedulingEntity()) {
700 } else if (NextInBundle) {
702 ScheduleData *SD = NextInBundle;
704 os << ';' << *SD->Inst;
705 SD = SD->NextInBundle;
715 /// Points to the head in an instruction bundle (and always to this for
716 /// single instructions).
717 ScheduleData *FirstInBundle;
719 /// Single linked list of all instructions in a bundle. Null if it is a
720 /// single instruction.
721 ScheduleData *NextInBundle;
723 /// Single linked list of all memory instructions (e.g. load, store, call)
724 /// in the block - until the end of the scheduling region.
725 ScheduleData *NextLoadStore;
727 /// The dependent memory instructions.
728 /// This list is derived on demand in calculateDependencies().
729 SmallVector<ScheduleData *, 4> MemoryDependencies;
731 /// This ScheduleData is in the current scheduling region if this matches
732 /// the current SchedulingRegionID of BlockScheduling.
733 int SchedulingRegionID;
735 /// Used for getting a "good" final ordering of instructions.
736 int SchedulingPriority;
738 /// The number of dependencies. Constitutes of the number of users of the
739 /// instruction plus the number of dependent memory instructions (if any).
740 /// This value is calculated on demand.
741 /// If InvalidDeps, the number of dependencies is not calculated yet.
745 /// The number of dependencies minus the number of dependencies of scheduled
746 /// instructions. As soon as this is zero, the instruction/bundle gets ready
748 /// Note that this is negative as long as Dependencies is not calculated.
751 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
752 /// single instructions.
753 int UnscheduledDepsInBundle;
755 /// True if this instruction is scheduled (or considered as scheduled in the
761 friend raw_ostream &operator<<(raw_ostream &os,
762 const BoUpSLP::ScheduleData &SD);
765 /// Contains all scheduling data for a basic block.
767 struct BlockScheduling {
769 BlockScheduling(BasicBlock *BB)
770 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
771 ScheduleStart(nullptr), ScheduleEnd(nullptr),
772 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
773 // Make sure that the initial SchedulingRegionID is greater than the
774 // initial SchedulingRegionID in ScheduleData (which is 0).
775 SchedulingRegionID(1) {}
779 ScheduleStart = nullptr;
780 ScheduleEnd = nullptr;
781 FirstLoadStoreInRegion = nullptr;
782 LastLoadStoreInRegion = nullptr;
784 // Make a new scheduling region, i.e. all existing ScheduleData is not
785 // in the new region yet.
786 ++SchedulingRegionID;
789 ScheduleData *getScheduleData(Value *V) {
790 ScheduleData *SD = ScheduleDataMap[V];
791 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
796 bool isInSchedulingRegion(ScheduleData *SD) {
797 return SD->SchedulingRegionID == SchedulingRegionID;
800 /// Marks an instruction as scheduled and puts all dependent ready
801 /// instructions into the ready-list.
802 template <typename ReadyListType>
803 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
804 SD->IsScheduled = true;
805 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
807 ScheduleData *BundleMember = SD;
808 while (BundleMember) {
809 // Handle the def-use chain dependencies.
810 for (Use &U : BundleMember->Inst->operands()) {
811 ScheduleData *OpDef = getScheduleData(U.get());
812 if (OpDef && OpDef->hasValidDependencies() &&
813 OpDef->incrementUnscheduledDeps(-1) == 0) {
814 // There are no more unscheduled dependencies after decrementing,
815 // so we can put the dependent instruction into the ready list.
816 ScheduleData *DepBundle = OpDef->FirstInBundle;
817 assert(!DepBundle->IsScheduled &&
818 "already scheduled bundle gets ready");
819 ReadyList.insert(DepBundle);
820 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
823 // Handle the memory dependencies.
824 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
825 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
826 // There are no more unscheduled dependencies after decrementing,
827 // so we can put the dependent instruction into the ready list.
828 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
829 assert(!DepBundle->IsScheduled &&
830 "already scheduled bundle gets ready");
831 ReadyList.insert(DepBundle);
832 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
835 BundleMember = BundleMember->NextInBundle;
839 /// Put all instructions into the ReadyList which are ready for scheduling.
840 template <typename ReadyListType>
841 void initialFillReadyList(ReadyListType &ReadyList) {
842 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
843 ScheduleData *SD = getScheduleData(I);
844 if (SD->isSchedulingEntity() && SD->isReady()) {
845 ReadyList.insert(SD);
846 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
851 /// Checks if a bundle of instructions can be scheduled, i.e. has no
852 /// cyclic dependencies. This is only a dry-run, no instructions are
853 /// actually moved at this stage.
854 bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
856 /// Un-bundles a group of instructions.
857 void cancelScheduling(ArrayRef<Value *> VL);
859 /// Extends the scheduling region so that V is inside the region.
860 void extendSchedulingRegion(Value *V);
862 /// Initialize the ScheduleData structures for new instructions in the
863 /// scheduling region.
864 void initScheduleData(Instruction *FromI, Instruction *ToI,
865 ScheduleData *PrevLoadStore,
866 ScheduleData *NextLoadStore);
868 /// Updates the dependency information of a bundle and of all instructions/
869 /// bundles which depend on the original bundle.
870 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
873 /// Sets all instruction in the scheduling region to un-scheduled.
874 void resetSchedule();
878 /// Simple memory allocation for ScheduleData.
879 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
881 /// The size of a ScheduleData array in ScheduleDataChunks.
884 /// The allocator position in the current chunk, which is the last entry
885 /// of ScheduleDataChunks.
888 /// Attaches ScheduleData to Instruction.
889 /// Note that the mapping survives during all vectorization iterations, i.e.
890 /// ScheduleData structures are recycled.
891 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
893 struct ReadyList : SmallVector<ScheduleData *, 8> {
894 void insert(ScheduleData *SD) { push_back(SD); }
897 /// The ready-list for scheduling (only used for the dry-run).
898 ReadyList ReadyInsts;
900 /// The first instruction of the scheduling region.
901 Instruction *ScheduleStart;
903 /// The first instruction _after_ the scheduling region.
904 Instruction *ScheduleEnd;
906 /// The first memory accessing instruction in the scheduling region
908 ScheduleData *FirstLoadStoreInRegion;
910 /// The last memory accessing instruction in the scheduling region
912 ScheduleData *LastLoadStoreInRegion;
914 /// The ID of the scheduling region. For a new vectorization iteration this
915 /// is incremented which "removes" all ScheduleData from the region.
916 int SchedulingRegionID;
919 /// Attaches the BlockScheduling structures to basic blocks.
920 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
922 /// Performs the "real" scheduling. Done before vectorization is actually
923 /// performed in a basic block.
924 void scheduleBlock(BlockScheduling *BS);
926 /// List of users to ignore during scheduling and that don't need extracting.
927 ArrayRef<Value *> UserIgnoreList;
929 // Number of load-bundles, which contain consecutive loads.
930 int NumLoadsWantToKeepOrder;
932 // Number of load-bundles of size 2, which are consecutive loads if reversed.
933 int NumLoadsWantToChangeOrder;
935 // Analysis and block reference.
938 const DataLayout *DL;
939 TargetTransformInfo *TTI;
940 TargetLibraryInfo *TLI;
944 /// Instruction builder to construct the vectorized tree.
949 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
955 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
956 ArrayRef<Value *> UserIgnoreLst) {
958 UserIgnoreList = UserIgnoreLst;
959 if (!getSameType(Roots))
961 buildTree_rec(Roots, 0);
963 // Collect the values that we need to extract from the tree.
964 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
965 TreeEntry *Entry = &VectorizableTree[EIdx];
968 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
969 Value *Scalar = Entry->Scalars[Lane];
971 // No need to handle users of gathered values.
972 if (Entry->NeedToGather)
975 for (User *U : Scalar->users()) {
976 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
978 Instruction *UserInst = dyn_cast<Instruction>(U);
982 // Skip in-tree scalars that become vectors
983 if (ScalarToTreeEntry.count(U)) {
984 int Idx = ScalarToTreeEntry[U];
985 TreeEntry *UseEntry = &VectorizableTree[Idx];
986 Value *UseScalar = UseEntry->Scalars[0];
987 // Some in-tree scalars will remain as scalar in vectorized
988 // instructions. If that is the case, the one in Lane 0 will
990 if (UseScalar != U ||
991 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
992 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
994 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
999 // Ignore users in the user ignore list.
1000 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
1001 UserIgnoreList.end())
1004 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
1005 Lane << " from " << *Scalar << ".\n");
1006 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
1013 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
1014 bool SameTy = getSameType(VL); (void)SameTy;
1015 bool isAltShuffle = false;
1016 assert(SameTy && "Invalid types!");
1018 if (Depth == RecursionMaxDepth) {
1019 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1020 newTreeEntry(VL, false);
1024 // Don't handle vectors.
1025 if (VL[0]->getType()->isVectorTy()) {
1026 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1027 newTreeEntry(VL, false);
1031 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1032 if (SI->getValueOperand()->getType()->isVectorTy()) {
1033 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1034 newTreeEntry(VL, false);
1037 unsigned Opcode = getSameOpcode(VL);
1039 // Check that this shuffle vector refers to the alternate
1040 // sequence of opcodes.
1041 if (Opcode == Instruction::ShuffleVector) {
1042 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1043 unsigned Op = I0->getOpcode();
1044 if (Op != Instruction::ShuffleVector)
1045 isAltShuffle = true;
1048 // If all of the operands are identical or constant we have a simple solution.
1049 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
1050 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1051 newTreeEntry(VL, false);
1055 // We now know that this is a vector of instructions of the same type from
1058 // Don't vectorize ephemeral values.
1059 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1060 if (EphValues.count(VL[i])) {
1061 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1062 ") is ephemeral.\n");
1063 newTreeEntry(VL, false);
1068 // Check if this is a duplicate of another entry.
1069 if (ScalarToTreeEntry.count(VL[0])) {
1070 int Idx = ScalarToTreeEntry[VL[0]];
1071 TreeEntry *E = &VectorizableTree[Idx];
1072 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1073 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1074 if (E->Scalars[i] != VL[i]) {
1075 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1076 newTreeEntry(VL, false);
1080 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1084 // Check that none of the instructions in the bundle are already in the tree.
1085 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1086 if (ScalarToTreeEntry.count(VL[i])) {
1087 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1088 ") is already in tree.\n");
1089 newTreeEntry(VL, false);
1094 // If any of the scalars is marked as a value that needs to stay scalar then
1095 // we need to gather the scalars.
1096 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1097 if (MustGather.count(VL[i])) {
1098 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1099 newTreeEntry(VL, false);
1104 // Check that all of the users of the scalars that we want to vectorize are
1106 Instruction *VL0 = cast<Instruction>(VL[0]);
1107 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1109 if (!DT->isReachableFromEntry(BB)) {
1110 // Don't go into unreachable blocks. They may contain instructions with
1111 // dependency cycles which confuse the final scheduling.
1112 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1113 newTreeEntry(VL, false);
1117 // Check that every instructions appears once in this bundle.
1118 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1119 for (unsigned j = i+1; j < e; ++j)
1120 if (VL[i] == VL[j]) {
1121 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1122 newTreeEntry(VL, false);
1126 auto &BSRef = BlocksSchedules[BB];
1128 BSRef = llvm::make_unique<BlockScheduling>(BB);
1130 BlockScheduling &BS = *BSRef.get();
1132 if (!BS.tryScheduleBundle(VL, this)) {
1133 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1134 BS.cancelScheduling(VL);
1135 newTreeEntry(VL, false);
1138 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1141 case Instruction::PHI: {
1142 PHINode *PH = dyn_cast<PHINode>(VL0);
1144 // Check for terminator values (e.g. invoke).
1145 for (unsigned j = 0; j < VL.size(); ++j)
1146 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1147 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1148 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1150 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1151 BS.cancelScheduling(VL);
1152 newTreeEntry(VL, false);
1157 newTreeEntry(VL, true);
1158 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1160 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1162 // Prepare the operand vector.
1163 for (unsigned j = 0; j < VL.size(); ++j)
1164 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1165 PH->getIncomingBlock(i)));
1167 buildTree_rec(Operands, Depth + 1);
1171 case Instruction::ExtractElement: {
1172 bool Reuse = CanReuseExtract(VL);
1174 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1176 BS.cancelScheduling(VL);
1178 newTreeEntry(VL, Reuse);
1181 case Instruction::Load: {
1182 // Check if the loads are consecutive or of we need to swizzle them.
1183 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1184 LoadInst *L = cast<LoadInst>(VL[i]);
1185 if (!L->isSimple()) {
1186 BS.cancelScheduling(VL);
1187 newTreeEntry(VL, false);
1188 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1191 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1192 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1193 ++NumLoadsWantToChangeOrder;
1195 BS.cancelScheduling(VL);
1196 newTreeEntry(VL, false);
1197 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1201 ++NumLoadsWantToKeepOrder;
1202 newTreeEntry(VL, true);
1203 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1206 case Instruction::ZExt:
1207 case Instruction::SExt:
1208 case Instruction::FPToUI:
1209 case Instruction::FPToSI:
1210 case Instruction::FPExt:
1211 case Instruction::PtrToInt:
1212 case Instruction::IntToPtr:
1213 case Instruction::SIToFP:
1214 case Instruction::UIToFP:
1215 case Instruction::Trunc:
1216 case Instruction::FPTrunc:
1217 case Instruction::BitCast: {
1218 Type *SrcTy = VL0->getOperand(0)->getType();
1219 for (unsigned i = 0; i < VL.size(); ++i) {
1220 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1221 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1222 BS.cancelScheduling(VL);
1223 newTreeEntry(VL, false);
1224 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1228 newTreeEntry(VL, true);
1229 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1231 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1233 // Prepare the operand vector.
1234 for (unsigned j = 0; j < VL.size(); ++j)
1235 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1237 buildTree_rec(Operands, Depth+1);
1241 case Instruction::ICmp:
1242 case Instruction::FCmp: {
1243 // Check that all of the compares have the same predicate.
1244 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1245 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1246 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1247 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1248 if (Cmp->getPredicate() != P0 ||
1249 Cmp->getOperand(0)->getType() != ComparedTy) {
1250 BS.cancelScheduling(VL);
1251 newTreeEntry(VL, false);
1252 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1257 newTreeEntry(VL, true);
1258 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1260 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1262 // Prepare the operand vector.
1263 for (unsigned j = 0; j < VL.size(); ++j)
1264 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1266 buildTree_rec(Operands, Depth+1);
1270 case Instruction::Select:
1271 case Instruction::Add:
1272 case Instruction::FAdd:
1273 case Instruction::Sub:
1274 case Instruction::FSub:
1275 case Instruction::Mul:
1276 case Instruction::FMul:
1277 case Instruction::UDiv:
1278 case Instruction::SDiv:
1279 case Instruction::FDiv:
1280 case Instruction::URem:
1281 case Instruction::SRem:
1282 case Instruction::FRem:
1283 case Instruction::Shl:
1284 case Instruction::LShr:
1285 case Instruction::AShr:
1286 case Instruction::And:
1287 case Instruction::Or:
1288 case Instruction::Xor: {
1289 newTreeEntry(VL, true);
1290 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1292 // Sort operands of the instructions so that each side is more likely to
1293 // have the same opcode.
1294 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1295 ValueList Left, Right;
1296 reorderInputsAccordingToOpcode(VL, Left, Right);
1297 buildTree_rec(Left, Depth + 1);
1298 buildTree_rec(Right, Depth + 1);
1302 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1304 // Prepare the operand vector.
1305 for (unsigned j = 0; j < VL.size(); ++j)
1306 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1308 buildTree_rec(Operands, Depth+1);
1312 case Instruction::GetElementPtr: {
1313 // We don't combine GEPs with complicated (nested) indexing.
1314 for (unsigned j = 0; j < VL.size(); ++j) {
1315 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1316 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1317 BS.cancelScheduling(VL);
1318 newTreeEntry(VL, false);
1323 // We can't combine several GEPs into one vector if they operate on
1325 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1326 for (unsigned j = 0; j < VL.size(); ++j) {
1327 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1329 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1330 BS.cancelScheduling(VL);
1331 newTreeEntry(VL, false);
1336 // We don't combine GEPs with non-constant indexes.
1337 for (unsigned j = 0; j < VL.size(); ++j) {
1338 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1339 if (!isa<ConstantInt>(Op)) {
1341 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1342 BS.cancelScheduling(VL);
1343 newTreeEntry(VL, false);
1348 newTreeEntry(VL, true);
1349 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1350 for (unsigned i = 0, e = 2; i < e; ++i) {
1352 // Prepare the operand vector.
1353 for (unsigned j = 0; j < VL.size(); ++j)
1354 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1356 buildTree_rec(Operands, Depth + 1);
1360 case Instruction::Store: {
1361 // Check if the stores are consecutive or of we need to swizzle them.
1362 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1363 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1364 BS.cancelScheduling(VL);
1365 newTreeEntry(VL, false);
1366 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1370 newTreeEntry(VL, true);
1371 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1374 for (unsigned j = 0; j < VL.size(); ++j)
1375 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1377 buildTree_rec(Operands, Depth + 1);
1380 case Instruction::Call: {
1381 // Check if the calls are all to the same vectorizable intrinsic.
1382 CallInst *CI = cast<CallInst>(VL[0]);
1383 // Check if this is an Intrinsic call or something that can be
1384 // represented by an intrinsic call
1385 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1386 if (!isTriviallyVectorizable(ID)) {
1387 BS.cancelScheduling(VL);
1388 newTreeEntry(VL, false);
1389 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1392 Function *Int = CI->getCalledFunction();
1393 Value *A1I = nullptr;
1394 if (hasVectorInstrinsicScalarOpd(ID, 1))
1395 A1I = CI->getArgOperand(1);
1396 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1397 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1398 if (!CI2 || CI2->getCalledFunction() != Int ||
1399 getIntrinsicIDForCall(CI2, TLI) != ID) {
1400 BS.cancelScheduling(VL);
1401 newTreeEntry(VL, false);
1402 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1406 // ctlz,cttz and powi are special intrinsics whose second argument
1407 // should be same in order for them to be vectorized.
1408 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1409 Value *A1J = CI2->getArgOperand(1);
1411 BS.cancelScheduling(VL);
1412 newTreeEntry(VL, false);
1413 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1414 << " argument "<< A1I<<"!=" << A1J
1421 newTreeEntry(VL, true);
1422 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1424 // Prepare the operand vector.
1425 for (unsigned j = 0; j < VL.size(); ++j) {
1426 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1427 Operands.push_back(CI2->getArgOperand(i));
1429 buildTree_rec(Operands, Depth + 1);
1433 case Instruction::ShuffleVector: {
1434 // If this is not an alternate sequence of opcode like add-sub
1435 // then do not vectorize this instruction.
1436 if (!isAltShuffle) {
1437 BS.cancelScheduling(VL);
1438 newTreeEntry(VL, false);
1439 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1442 newTreeEntry(VL, true);
1443 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1444 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1446 // Prepare the operand vector.
1447 for (unsigned j = 0; j < VL.size(); ++j)
1448 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1450 buildTree_rec(Operands, Depth + 1);
1455 BS.cancelScheduling(VL);
1456 newTreeEntry(VL, false);
1457 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1462 int BoUpSLP::getEntryCost(TreeEntry *E) {
1463 ArrayRef<Value*> VL = E->Scalars;
1465 Type *ScalarTy = VL[0]->getType();
1466 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1467 ScalarTy = SI->getValueOperand()->getType();
1468 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1470 if (E->NeedToGather) {
1471 if (allConstant(VL))
1474 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1476 return getGatherCost(E->Scalars);
1478 unsigned Opcode = getSameOpcode(VL);
1479 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1480 Instruction *VL0 = cast<Instruction>(VL[0]);
1482 case Instruction::PHI: {
1485 case Instruction::ExtractElement: {
1486 if (CanReuseExtract(VL)) {
1488 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1489 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1491 // Take credit for instruction that will become dead.
1493 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1497 return getGatherCost(VecTy);
1499 case Instruction::ZExt:
1500 case Instruction::SExt:
1501 case Instruction::FPToUI:
1502 case Instruction::FPToSI:
1503 case Instruction::FPExt:
1504 case Instruction::PtrToInt:
1505 case Instruction::IntToPtr:
1506 case Instruction::SIToFP:
1507 case Instruction::UIToFP:
1508 case Instruction::Trunc:
1509 case Instruction::FPTrunc:
1510 case Instruction::BitCast: {
1511 Type *SrcTy = VL0->getOperand(0)->getType();
1513 // Calculate the cost of this instruction.
1514 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1515 VL0->getType(), SrcTy);
1517 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1518 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1519 return VecCost - ScalarCost;
1521 case Instruction::FCmp:
1522 case Instruction::ICmp:
1523 case Instruction::Select:
1524 case Instruction::Add:
1525 case Instruction::FAdd:
1526 case Instruction::Sub:
1527 case Instruction::FSub:
1528 case Instruction::Mul:
1529 case Instruction::FMul:
1530 case Instruction::UDiv:
1531 case Instruction::SDiv:
1532 case Instruction::FDiv:
1533 case Instruction::URem:
1534 case Instruction::SRem:
1535 case Instruction::FRem:
1536 case Instruction::Shl:
1537 case Instruction::LShr:
1538 case Instruction::AShr:
1539 case Instruction::And:
1540 case Instruction::Or:
1541 case Instruction::Xor: {
1542 // Calculate the cost of this instruction.
1545 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1546 Opcode == Instruction::Select) {
1547 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1548 ScalarCost = VecTy->getNumElements() *
1549 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1550 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1552 // Certain instructions can be cheaper to vectorize if they have a
1553 // constant second vector operand.
1554 TargetTransformInfo::OperandValueKind Op1VK =
1555 TargetTransformInfo::OK_AnyValue;
1556 TargetTransformInfo::OperandValueKind Op2VK =
1557 TargetTransformInfo::OK_UniformConstantValue;
1558 TargetTransformInfo::OperandValueProperties Op1VP =
1559 TargetTransformInfo::OP_None;
1560 TargetTransformInfo::OperandValueProperties Op2VP =
1561 TargetTransformInfo::OP_None;
1563 // If all operands are exactly the same ConstantInt then set the
1564 // operand kind to OK_UniformConstantValue.
1565 // If instead not all operands are constants, then set the operand kind
1566 // to OK_AnyValue. If all operands are constants but not the same,
1567 // then set the operand kind to OK_NonUniformConstantValue.
1568 ConstantInt *CInt = nullptr;
1569 for (unsigned i = 0; i < VL.size(); ++i) {
1570 const Instruction *I = cast<Instruction>(VL[i]);
1571 if (!isa<ConstantInt>(I->getOperand(1))) {
1572 Op2VK = TargetTransformInfo::OK_AnyValue;
1576 CInt = cast<ConstantInt>(I->getOperand(1));
1579 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1580 CInt != cast<ConstantInt>(I->getOperand(1)))
1581 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1583 // FIXME: Currently cost of model modification for division by
1584 // power of 2 is handled only for X86. Add support for other targets.
1585 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1586 CInt->getValue().isPowerOf2())
1587 Op2VP = TargetTransformInfo::OP_PowerOf2;
1589 ScalarCost = VecTy->getNumElements() *
1590 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1592 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1595 return VecCost - ScalarCost;
1597 case Instruction::GetElementPtr: {
1598 TargetTransformInfo::OperandValueKind Op1VK =
1599 TargetTransformInfo::OK_AnyValue;
1600 TargetTransformInfo::OperandValueKind Op2VK =
1601 TargetTransformInfo::OK_UniformConstantValue;
1604 VecTy->getNumElements() *
1605 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1607 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1609 return VecCost - ScalarCost;
1611 case Instruction::Load: {
1612 // Cost of wide load - cost of scalar loads.
1613 int ScalarLdCost = VecTy->getNumElements() *
1614 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1615 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1616 return VecLdCost - ScalarLdCost;
1618 case Instruction::Store: {
1619 // We know that we can merge the stores. Calculate the cost.
1620 int ScalarStCost = VecTy->getNumElements() *
1621 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1622 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1623 return VecStCost - ScalarStCost;
1625 case Instruction::Call: {
1626 CallInst *CI = cast<CallInst>(VL0);
1627 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1629 // Calculate the cost of the scalar and vector calls.
1630 SmallVector<Type*, 4> ScalarTys, VecTys;
1631 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1632 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1633 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1634 VecTy->getNumElements()));
1637 int ScalarCallCost = VecTy->getNumElements() *
1638 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1640 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1642 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1643 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1644 << " for " << *CI << "\n");
1646 return VecCallCost - ScalarCallCost;
1648 case Instruction::ShuffleVector: {
1649 TargetTransformInfo::OperandValueKind Op1VK =
1650 TargetTransformInfo::OK_AnyValue;
1651 TargetTransformInfo::OperandValueKind Op2VK =
1652 TargetTransformInfo::OK_AnyValue;
1655 for (unsigned i = 0; i < VL.size(); ++i) {
1656 Instruction *I = cast<Instruction>(VL[i]);
1660 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1662 // VecCost is equal to sum of the cost of creating 2 vectors
1663 // and the cost of creating shuffle.
1664 Instruction *I0 = cast<Instruction>(VL[0]);
1666 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1667 Instruction *I1 = cast<Instruction>(VL[1]);
1669 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1671 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1672 return VecCost - ScalarCost;
1675 llvm_unreachable("Unknown instruction");
1679 bool BoUpSLP::isFullyVectorizableTinyTree() {
1680 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1681 VectorizableTree.size() << " is fully vectorizable .\n");
1683 // We only handle trees of height 2.
1684 if (VectorizableTree.size() != 2)
1687 // Handle splat stores.
1688 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1691 // Gathering cost would be too much for tiny trees.
1692 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1698 int BoUpSLP::getSpillCost() {
1699 // Walk from the bottom of the tree to the top, tracking which values are
1700 // live. When we see a call instruction that is not part of our tree,
1701 // query TTI to see if there is a cost to keeping values live over it
1702 // (for example, if spills and fills are required).
1703 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1706 SmallPtrSet<Instruction*, 4> LiveValues;
1707 Instruction *PrevInst = nullptr;
1709 for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1710 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1720 dbgs() << "SLP: #LV: " << LiveValues.size();
1721 for (auto *X : LiveValues)
1722 dbgs() << " " << X->getName();
1723 dbgs() << ", Looking at ";
1727 // Update LiveValues.
1728 LiveValues.erase(PrevInst);
1729 for (auto &J : PrevInst->operands()) {
1730 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1731 LiveValues.insert(cast<Instruction>(&*J));
1734 // Now find the sequence of instructions between PrevInst and Inst.
1735 BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1737 while (InstIt != PrevInstIt) {
1738 if (PrevInstIt == PrevInst->getParent()->rend()) {
1739 PrevInstIt = Inst->getParent()->rbegin();
1743 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1744 SmallVector<Type*, 4> V;
1745 for (auto *II : LiveValues)
1746 V.push_back(VectorType::get(II->getType(), BundleWidth));
1747 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1756 DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1760 int BoUpSLP::getTreeCost() {
1762 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1763 VectorizableTree.size() << ".\n");
1765 // We only vectorize tiny trees if it is fully vectorizable.
1766 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1767 if (VectorizableTree.empty()) {
1768 assert(!ExternalUses.size() && "We should not have any external users");
1773 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1775 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1776 int C = getEntryCost(&VectorizableTree[i]);
1777 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1778 << *VectorizableTree[i].Scalars[0] << " .\n");
1782 SmallSet<Value *, 16> ExtractCostCalculated;
1783 int ExtractCost = 0;
1784 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1786 // We only add extract cost once for the same scalar.
1787 if (!ExtractCostCalculated.insert(I->Scalar).second)
1790 // Uses by ephemeral values are free (because the ephemeral value will be
1791 // removed prior to code generation, and so the extraction will be
1792 // removed as well).
1793 if (EphValues.count(I->User))
1796 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1797 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1801 Cost += getSpillCost();
1803 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1804 return Cost + ExtractCost;
1807 int BoUpSLP::getGatherCost(Type *Ty) {
1809 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1810 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1814 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1815 // Find the type of the operands in VL.
1816 Type *ScalarTy = VL[0]->getType();
1817 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1818 ScalarTy = SI->getValueOperand()->getType();
1819 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1820 // Find the cost of inserting/extracting values from the vector.
1821 return getGatherCost(VecTy);
1824 Value *BoUpSLP::getPointerOperand(Value *I) {
1825 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1826 return LI->getPointerOperand();
1827 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1828 return SI->getPointerOperand();
1832 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1833 if (LoadInst *L = dyn_cast<LoadInst>(I))
1834 return L->getPointerAddressSpace();
1835 if (StoreInst *S = dyn_cast<StoreInst>(I))
1836 return S->getPointerAddressSpace();
1840 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1841 Value *PtrA = getPointerOperand(A);
1842 Value *PtrB = getPointerOperand(B);
1843 unsigned ASA = getAddressSpaceOperand(A);
1844 unsigned ASB = getAddressSpaceOperand(B);
1846 // Check that the address spaces match and that the pointers are valid.
1847 if (!PtrA || !PtrB || (ASA != ASB))
1850 // Make sure that A and B are different pointers of the same type.
1851 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1854 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1855 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1856 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1858 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1859 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1860 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1862 APInt OffsetDelta = OffsetB - OffsetA;
1864 // Check if they are based on the same pointer. That makes the offsets
1867 return OffsetDelta == Size;
1869 // Compute the necessary base pointer delta to have the necessary final delta
1870 // equal to the size.
1871 APInt BaseDelta = Size - OffsetDelta;
1873 // Otherwise compute the distance with SCEV between the base pointers.
1874 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1875 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1876 const SCEV *C = SE->getConstant(BaseDelta);
1877 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1878 return X == PtrSCEVB;
1881 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1882 Instruction *VL0 = cast<Instruction>(VL[0]);
1883 BasicBlock::iterator NextInst = VL0;
1885 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1886 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1889 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1890 Value *Vec = UndefValue::get(Ty);
1891 // Generate the 'InsertElement' instruction.
1892 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1893 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1894 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1895 GatherSeq.insert(Insrt);
1896 CSEBlocks.insert(Insrt->getParent());
1898 // Add to our 'need-to-extract' list.
1899 if (ScalarToTreeEntry.count(VL[i])) {
1900 int Idx = ScalarToTreeEntry[VL[i]];
1901 TreeEntry *E = &VectorizableTree[Idx];
1902 // Find which lane we need to extract.
1904 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1905 // Is this the lane of the scalar that we are looking for ?
1906 if (E->Scalars[Lane] == VL[i]) {
1911 assert(FoundLane >= 0 && "Could not find the correct lane");
1912 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1920 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1921 SmallDenseMap<Value*, int>::const_iterator Entry
1922 = ScalarToTreeEntry.find(VL[0]);
1923 if (Entry != ScalarToTreeEntry.end()) {
1924 int Idx = Entry->second;
1925 const TreeEntry *En = &VectorizableTree[Idx];
1926 if (En->isSame(VL) && En->VectorizedValue)
1927 return En->VectorizedValue;
1932 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1933 if (ScalarToTreeEntry.count(VL[0])) {
1934 int Idx = ScalarToTreeEntry[VL[0]];
1935 TreeEntry *E = &VectorizableTree[Idx];
1937 return vectorizeTree(E);
1940 Type *ScalarTy = VL[0]->getType();
1941 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1942 ScalarTy = SI->getValueOperand()->getType();
1943 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1945 return Gather(VL, VecTy);
1948 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1949 IRBuilder<>::InsertPointGuard Guard(Builder);
1951 if (E->VectorizedValue) {
1952 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1953 return E->VectorizedValue;
1956 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1957 Type *ScalarTy = VL0->getType();
1958 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1959 ScalarTy = SI->getValueOperand()->getType();
1960 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1962 if (E->NeedToGather) {
1963 setInsertPointAfterBundle(E->Scalars);
1964 return Gather(E->Scalars, VecTy);
1967 unsigned Opcode = getSameOpcode(E->Scalars);
1970 case Instruction::PHI: {
1971 PHINode *PH = dyn_cast<PHINode>(VL0);
1972 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1973 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1974 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1975 E->VectorizedValue = NewPhi;
1977 // PHINodes may have multiple entries from the same block. We want to
1978 // visit every block once.
1979 SmallSet<BasicBlock*, 4> VisitedBBs;
1981 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1983 BasicBlock *IBB = PH->getIncomingBlock(i);
1985 if (!VisitedBBs.insert(IBB).second) {
1986 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1990 // Prepare the operand vector.
1991 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1992 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1993 getIncomingValueForBlock(IBB));
1995 Builder.SetInsertPoint(IBB->getTerminator());
1996 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1997 Value *Vec = vectorizeTree(Operands);
1998 NewPhi->addIncoming(Vec, IBB);
2001 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2002 "Invalid number of incoming values");
2006 case Instruction::ExtractElement: {
2007 if (CanReuseExtract(E->Scalars)) {
2008 Value *V = VL0->getOperand(0);
2009 E->VectorizedValue = V;
2012 return Gather(E->Scalars, VecTy);
2014 case Instruction::ZExt:
2015 case Instruction::SExt:
2016 case Instruction::FPToUI:
2017 case Instruction::FPToSI:
2018 case Instruction::FPExt:
2019 case Instruction::PtrToInt:
2020 case Instruction::IntToPtr:
2021 case Instruction::SIToFP:
2022 case Instruction::UIToFP:
2023 case Instruction::Trunc:
2024 case Instruction::FPTrunc:
2025 case Instruction::BitCast: {
2027 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2028 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2030 setInsertPointAfterBundle(E->Scalars);
2032 Value *InVec = vectorizeTree(INVL);
2034 if (Value *V = alreadyVectorized(E->Scalars))
2037 CastInst *CI = dyn_cast<CastInst>(VL0);
2038 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2039 E->VectorizedValue = V;
2040 ++NumVectorInstructions;
2043 case Instruction::FCmp:
2044 case Instruction::ICmp: {
2045 ValueList LHSV, RHSV;
2046 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2047 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2048 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2051 setInsertPointAfterBundle(E->Scalars);
2053 Value *L = vectorizeTree(LHSV);
2054 Value *R = vectorizeTree(RHSV);
2056 if (Value *V = alreadyVectorized(E->Scalars))
2059 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
2061 if (Opcode == Instruction::FCmp)
2062 V = Builder.CreateFCmp(P0, L, R);
2064 V = Builder.CreateICmp(P0, L, R);
2066 E->VectorizedValue = V;
2067 ++NumVectorInstructions;
2070 case Instruction::Select: {
2071 ValueList TrueVec, FalseVec, CondVec;
2072 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2073 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2074 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2075 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
2078 setInsertPointAfterBundle(E->Scalars);
2080 Value *Cond = vectorizeTree(CondVec);
2081 Value *True = vectorizeTree(TrueVec);
2082 Value *False = vectorizeTree(FalseVec);
2084 if (Value *V = alreadyVectorized(E->Scalars))
2087 Value *V = Builder.CreateSelect(Cond, True, False);
2088 E->VectorizedValue = V;
2089 ++NumVectorInstructions;
2092 case Instruction::Add:
2093 case Instruction::FAdd:
2094 case Instruction::Sub:
2095 case Instruction::FSub:
2096 case Instruction::Mul:
2097 case Instruction::FMul:
2098 case Instruction::UDiv:
2099 case Instruction::SDiv:
2100 case Instruction::FDiv:
2101 case Instruction::URem:
2102 case Instruction::SRem:
2103 case Instruction::FRem:
2104 case Instruction::Shl:
2105 case Instruction::LShr:
2106 case Instruction::AShr:
2107 case Instruction::And:
2108 case Instruction::Or:
2109 case Instruction::Xor: {
2110 ValueList LHSVL, RHSVL;
2111 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2112 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2114 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2115 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2116 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2119 setInsertPointAfterBundle(E->Scalars);
2121 Value *LHS = vectorizeTree(LHSVL);
2122 Value *RHS = vectorizeTree(RHSVL);
2124 if (LHS == RHS && isa<Instruction>(LHS)) {
2125 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2128 if (Value *V = alreadyVectorized(E->Scalars))
2131 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2132 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2133 E->VectorizedValue = V;
2134 propagateIRFlags(E->VectorizedValue, E->Scalars);
2135 ++NumVectorInstructions;
2137 if (Instruction *I = dyn_cast<Instruction>(V))
2138 return propagateMetadata(I, E->Scalars);
2142 case Instruction::Load: {
2143 // Loads are inserted at the head of the tree because we don't want to
2144 // sink them all the way down past store instructions.
2145 setInsertPointAfterBundle(E->Scalars);
2147 LoadInst *LI = cast<LoadInst>(VL0);
2148 Type *ScalarLoadTy = LI->getType();
2149 unsigned AS = LI->getPointerAddressSpace();
2151 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2152 VecTy->getPointerTo(AS));
2154 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2155 // ExternalUses list to make sure that an extract will be generated in the
2157 if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2158 ExternalUses.push_back(
2159 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2161 unsigned Alignment = LI->getAlignment();
2162 LI = Builder.CreateLoad(VecPtr);
2164 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2165 LI->setAlignment(Alignment);
2166 E->VectorizedValue = LI;
2167 ++NumVectorInstructions;
2168 return propagateMetadata(LI, E->Scalars);
2170 case Instruction::Store: {
2171 StoreInst *SI = cast<StoreInst>(VL0);
2172 unsigned Alignment = SI->getAlignment();
2173 unsigned AS = SI->getPointerAddressSpace();
2176 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2177 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2179 setInsertPointAfterBundle(E->Scalars);
2181 Value *VecValue = vectorizeTree(ValueOp);
2182 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2183 VecTy->getPointerTo(AS));
2184 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2186 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2187 // ExternalUses list to make sure that an extract will be generated in the
2189 if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2190 ExternalUses.push_back(
2191 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2194 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2195 S->setAlignment(Alignment);
2196 E->VectorizedValue = S;
2197 ++NumVectorInstructions;
2198 return propagateMetadata(S, E->Scalars);
2200 case Instruction::GetElementPtr: {
2201 setInsertPointAfterBundle(E->Scalars);
2204 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2205 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2207 Value *Op0 = vectorizeTree(Op0VL);
2209 std::vector<Value *> OpVecs;
2210 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2213 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2214 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2216 Value *OpVec = vectorizeTree(OpVL);
2217 OpVecs.push_back(OpVec);
2220 Value *V = Builder.CreateGEP(Op0, OpVecs);
2221 E->VectorizedValue = V;
2222 ++NumVectorInstructions;
2224 if (Instruction *I = dyn_cast<Instruction>(V))
2225 return propagateMetadata(I, E->Scalars);
2229 case Instruction::Call: {
2230 CallInst *CI = cast<CallInst>(VL0);
2231 setInsertPointAfterBundle(E->Scalars);
2233 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2234 Value *ScalarArg = nullptr;
2235 if (CI && (FI = CI->getCalledFunction())) {
2236 IID = (Intrinsic::ID) FI->getIntrinsicID();
2238 std::vector<Value *> OpVecs;
2239 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2241 // ctlz,cttz and powi are special intrinsics whose second argument is
2242 // a scalar. This argument should not be vectorized.
2243 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2244 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2245 ScalarArg = CEI->getArgOperand(j);
2246 OpVecs.push_back(CEI->getArgOperand(j));
2249 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2250 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2251 OpVL.push_back(CEI->getArgOperand(j));
2254 Value *OpVec = vectorizeTree(OpVL);
2255 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2256 OpVecs.push_back(OpVec);
2259 Module *M = F->getParent();
2260 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2261 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2262 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2263 Value *V = Builder.CreateCall(CF, OpVecs);
2265 // The scalar argument uses an in-tree scalar so we add the new vectorized
2266 // call to ExternalUses list to make sure that an extract will be
2267 // generated in the future.
2268 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2269 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2271 E->VectorizedValue = V;
2272 ++NumVectorInstructions;
2275 case Instruction::ShuffleVector: {
2276 ValueList LHSVL, RHSVL;
2277 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2278 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2279 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2281 setInsertPointAfterBundle(E->Scalars);
2283 Value *LHS = vectorizeTree(LHSVL);
2284 Value *RHS = vectorizeTree(RHSVL);
2286 if (Value *V = alreadyVectorized(E->Scalars))
2289 // Create a vector of LHS op1 RHS
2290 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2291 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2293 // Create a vector of LHS op2 RHS
2294 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2295 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2296 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2298 // Create shuffle to take alternate operations from the vector.
2299 // Also, gather up odd and even scalar ops to propagate IR flags to
2300 // each vector operation.
2301 ValueList OddScalars, EvenScalars;
2302 unsigned e = E->Scalars.size();
2303 SmallVector<Constant *, 8> Mask(e);
2304 for (unsigned i = 0; i < e; ++i) {
2306 Mask[i] = Builder.getInt32(e + i);
2307 OddScalars.push_back(E->Scalars[i]);
2309 Mask[i] = Builder.getInt32(i);
2310 EvenScalars.push_back(E->Scalars[i]);
2314 Value *ShuffleMask = ConstantVector::get(Mask);
2315 propagateIRFlags(V0, EvenScalars);
2316 propagateIRFlags(V1, OddScalars);
2318 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2319 E->VectorizedValue = V;
2320 ++NumVectorInstructions;
2321 if (Instruction *I = dyn_cast<Instruction>(V))
2322 return propagateMetadata(I, E->Scalars);
2327 llvm_unreachable("unknown inst");
2332 Value *BoUpSLP::vectorizeTree() {
2334 // All blocks must be scheduled before any instructions are inserted.
2335 for (auto &BSIter : BlocksSchedules) {
2336 scheduleBlock(BSIter.second.get());
2339 Builder.SetInsertPoint(F->getEntryBlock().begin());
2340 vectorizeTree(&VectorizableTree[0]);
2342 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2344 // Extract all of the elements with the external uses.
2345 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2347 Value *Scalar = it->Scalar;
2348 llvm::User *User = it->User;
2350 // Skip users that we already RAUW. This happens when one instruction
2351 // has multiple uses of the same value.
2352 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2355 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2357 int Idx = ScalarToTreeEntry[Scalar];
2358 TreeEntry *E = &VectorizableTree[Idx];
2359 assert(!E->NeedToGather && "Extracting from a gather list");
2361 Value *Vec = E->VectorizedValue;
2362 assert(Vec && "Can't find vectorizable value");
2364 Value *Lane = Builder.getInt32(it->Lane);
2365 // Generate extracts for out-of-tree users.
2366 // Find the insertion point for the extractelement lane.
2367 if (isa<Instruction>(Vec)){
2368 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2369 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2370 if (PH->getIncomingValue(i) == Scalar) {
2371 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2372 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2373 CSEBlocks.insert(PH->getIncomingBlock(i));
2374 PH->setOperand(i, Ex);
2378 Builder.SetInsertPoint(cast<Instruction>(User));
2379 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2380 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2381 User->replaceUsesOfWith(Scalar, Ex);
2384 Builder.SetInsertPoint(F->getEntryBlock().begin());
2385 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2386 CSEBlocks.insert(&F->getEntryBlock());
2387 User->replaceUsesOfWith(Scalar, Ex);
2390 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2393 // For each vectorized value:
2394 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2395 TreeEntry *Entry = &VectorizableTree[EIdx];
2398 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2399 Value *Scalar = Entry->Scalars[Lane];
2400 // No need to handle users of gathered values.
2401 if (Entry->NeedToGather)
2404 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2406 Type *Ty = Scalar->getType();
2407 if (!Ty->isVoidTy()) {
2409 for (User *U : Scalar->users()) {
2410 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2412 assert((ScalarToTreeEntry.count(U) ||
2413 // It is legal to replace users in the ignorelist by undef.
2414 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2415 UserIgnoreList.end())) &&
2416 "Replacing out-of-tree value with undef");
2419 Value *Undef = UndefValue::get(Ty);
2420 Scalar->replaceAllUsesWith(Undef);
2422 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2423 eraseInstruction(cast<Instruction>(Scalar));
2427 Builder.ClearInsertionPoint();
2429 return VectorizableTree[0].VectorizedValue;
2432 void BoUpSLP::optimizeGatherSequence() {
2433 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2434 << " gather sequences instructions.\n");
2435 // LICM InsertElementInst sequences.
2436 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2437 e = GatherSeq.end(); it != e; ++it) {
2438 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2443 // Check if this block is inside a loop.
2444 Loop *L = LI->getLoopFor(Insert->getParent());
2448 // Check if it has a preheader.
2449 BasicBlock *PreHeader = L->getLoopPreheader();
2453 // If the vector or the element that we insert into it are
2454 // instructions that are defined in this basic block then we can't
2455 // hoist this instruction.
2456 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2457 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2458 if (CurrVec && L->contains(CurrVec))
2460 if (NewElem && L->contains(NewElem))
2463 // We can hoist this instruction. Move it to the pre-header.
2464 Insert->moveBefore(PreHeader->getTerminator());
2467 // Make a list of all reachable blocks in our CSE queue.
2468 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2469 CSEWorkList.reserve(CSEBlocks.size());
2470 for (BasicBlock *BB : CSEBlocks)
2471 if (DomTreeNode *N = DT->getNode(BB)) {
2472 assert(DT->isReachableFromEntry(N));
2473 CSEWorkList.push_back(N);
2476 // Sort blocks by domination. This ensures we visit a block after all blocks
2477 // dominating it are visited.
2478 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2479 [this](const DomTreeNode *A, const DomTreeNode *B) {
2480 return DT->properlyDominates(A, B);
2483 // Perform O(N^2) search over the gather sequences and merge identical
2484 // instructions. TODO: We can further optimize this scan if we split the
2485 // instructions into different buckets based on the insert lane.
2486 SmallVector<Instruction *, 16> Visited;
2487 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2488 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2489 "Worklist not sorted properly!");
2490 BasicBlock *BB = (*I)->getBlock();
2491 // For all instructions in blocks containing gather sequences:
2492 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2493 Instruction *In = it++;
2494 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2497 // Check if we can replace this instruction with any of the
2498 // visited instructions.
2499 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2502 if (In->isIdenticalTo(*v) &&
2503 DT->dominates((*v)->getParent(), In->getParent())) {
2504 In->replaceAllUsesWith(*v);
2505 eraseInstruction(In);
2511 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2512 Visited.push_back(In);
2520 // Groups the instructions to a bundle (which is then a single scheduling entity)
2521 // and schedules instructions until the bundle gets ready.
2522 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2524 if (isa<PHINode>(VL[0]))
2527 // Initialize the instruction bundle.
2528 Instruction *OldScheduleEnd = ScheduleEnd;
2529 ScheduleData *PrevInBundle = nullptr;
2530 ScheduleData *Bundle = nullptr;
2531 bool ReSchedule = false;
2532 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2533 for (Value *V : VL) {
2534 extendSchedulingRegion(V);
2535 ScheduleData *BundleMember = getScheduleData(V);
2536 assert(BundleMember &&
2537 "no ScheduleData for bundle member (maybe not in same basic block)");
2538 if (BundleMember->IsScheduled) {
2539 // A bundle member was scheduled as single instruction before and now
2540 // needs to be scheduled as part of the bundle. We just get rid of the
2541 // existing schedule.
2542 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2543 << " was already scheduled\n");
2546 assert(BundleMember->isSchedulingEntity() &&
2547 "bundle member already part of other bundle");
2549 PrevInBundle->NextInBundle = BundleMember;
2551 Bundle = BundleMember;
2553 BundleMember->UnscheduledDepsInBundle = 0;
2554 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2556 // Group the instructions to a bundle.
2557 BundleMember->FirstInBundle = Bundle;
2558 PrevInBundle = BundleMember;
2560 if (ScheduleEnd != OldScheduleEnd) {
2561 // The scheduling region got new instructions at the lower end (or it is a
2562 // new region for the first bundle). This makes it necessary to
2563 // recalculate all dependencies.
2564 // It is seldom that this needs to be done a second time after adding the
2565 // initial bundle to the region.
2566 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2567 ScheduleData *SD = getScheduleData(I);
2568 SD->clearDependencies();
2574 initialFillReadyList(ReadyInsts);
2577 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2578 << BB->getName() << "\n");
2580 calculateDependencies(Bundle, true, SLP);
2582 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2583 // means that there are no cyclic dependencies and we can schedule it.
2584 // Note that's important that we don't "schedule" the bundle yet (see
2585 // cancelScheduling).
2586 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2588 ScheduleData *pickedSD = ReadyInsts.back();
2589 ReadyInsts.pop_back();
2591 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2592 schedule(pickedSD, ReadyInsts);
2595 return Bundle->isReady();
2598 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2599 if (isa<PHINode>(VL[0]))
2602 ScheduleData *Bundle = getScheduleData(VL[0]);
2603 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2604 assert(!Bundle->IsScheduled &&
2605 "Can't cancel bundle which is already scheduled");
2606 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2607 "tried to unbundle something which is not a bundle");
2609 // Un-bundle: make single instructions out of the bundle.
2610 ScheduleData *BundleMember = Bundle;
2611 while (BundleMember) {
2612 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2613 BundleMember->FirstInBundle = BundleMember;
2614 ScheduleData *Next = BundleMember->NextInBundle;
2615 BundleMember->NextInBundle = nullptr;
2616 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2617 if (BundleMember->UnscheduledDepsInBundle == 0) {
2618 ReadyInsts.insert(BundleMember);
2620 BundleMember = Next;
2624 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2625 if (getScheduleData(V))
2627 Instruction *I = dyn_cast<Instruction>(V);
2628 assert(I && "bundle member must be an instruction");
2629 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2630 if (!ScheduleStart) {
2631 // It's the first instruction in the new region.
2632 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2634 ScheduleEnd = I->getNextNode();
2635 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2636 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2639 // Search up and down at the same time, because we don't know if the new
2640 // instruction is above or below the existing scheduling region.
2641 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2642 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2643 BasicBlock::iterator DownIter(ScheduleEnd);
2644 BasicBlock::iterator LowerEnd = BB->end();
2646 if (UpIter != UpperEnd) {
2647 if (&*UpIter == I) {
2648 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2650 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2655 if (DownIter != LowerEnd) {
2656 if (&*DownIter == I) {
2657 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2659 ScheduleEnd = I->getNextNode();
2660 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2661 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2666 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2667 "instruction not found in block");
2671 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2673 ScheduleData *PrevLoadStore,
2674 ScheduleData *NextLoadStore) {
2675 ScheduleData *CurrentLoadStore = PrevLoadStore;
2676 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2677 ScheduleData *SD = ScheduleDataMap[I];
2679 // Allocate a new ScheduleData for the instruction.
2680 if (ChunkPos >= ChunkSize) {
2681 ScheduleDataChunks.push_back(
2682 llvm::make_unique<ScheduleData[]>(ChunkSize));
2685 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2686 ScheduleDataMap[I] = SD;
2689 assert(!isInSchedulingRegion(SD) &&
2690 "new ScheduleData already in scheduling region");
2691 SD->init(SchedulingRegionID);
2693 if (I->mayReadOrWriteMemory()) {
2694 // Update the linked list of memory accessing instructions.
2695 if (CurrentLoadStore) {
2696 CurrentLoadStore->NextLoadStore = SD;
2698 FirstLoadStoreInRegion = SD;
2700 CurrentLoadStore = SD;
2703 if (NextLoadStore) {
2704 if (CurrentLoadStore)
2705 CurrentLoadStore->NextLoadStore = NextLoadStore;
2707 LastLoadStoreInRegion = CurrentLoadStore;
2711 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2712 bool InsertInReadyList,
2714 assert(SD->isSchedulingEntity());
2716 SmallVector<ScheduleData *, 10> WorkList;
2717 WorkList.push_back(SD);
2719 while (!WorkList.empty()) {
2720 ScheduleData *SD = WorkList.back();
2721 WorkList.pop_back();
2723 ScheduleData *BundleMember = SD;
2724 while (BundleMember) {
2725 assert(isInSchedulingRegion(BundleMember));
2726 if (!BundleMember->hasValidDependencies()) {
2728 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2729 BundleMember->Dependencies = 0;
2730 BundleMember->resetUnscheduledDeps();
2732 // Handle def-use chain dependencies.
2733 for (User *U : BundleMember->Inst->users()) {
2734 if (isa<Instruction>(U)) {
2735 ScheduleData *UseSD = getScheduleData(U);
2736 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2737 BundleMember->Dependencies++;
2738 ScheduleData *DestBundle = UseSD->FirstInBundle;
2739 if (!DestBundle->IsScheduled) {
2740 BundleMember->incrementUnscheduledDeps(1);
2742 if (!DestBundle->hasValidDependencies()) {
2743 WorkList.push_back(DestBundle);
2747 // I'm not sure if this can ever happen. But we need to be safe.
2748 // This lets the instruction/bundle never be scheduled and eventally
2749 // disable vectorization.
2750 BundleMember->Dependencies++;
2751 BundleMember->incrementUnscheduledDeps(1);
2755 // Handle the memory dependencies.
2756 ScheduleData *DepDest = BundleMember->NextLoadStore;
2758 Instruction *SrcInst = BundleMember->Inst;
2759 AliasAnalysis::Location SrcLoc = getLocation(SrcInst, SLP->AA);
2760 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2761 unsigned numAliased = 0;
2764 assert(isInSchedulingRegion(DepDest));
2765 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2767 // Limit the number of alias checks, becaus SLP->isAliased() is
2768 // the expensive part in the following loop.
2769 if (numAliased >= AliasedCheckLimit
2770 || SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)) {
2772 // We increment the counter only if the locations are aliased
2773 // (instead of counting all alias checks). This gives a better
2774 // balance between reduced runtime accurate dependencies.
2777 DepDest->MemoryDependencies.push_back(BundleMember);
2778 BundleMember->Dependencies++;
2779 ScheduleData *DestBundle = DepDest->FirstInBundle;
2780 if (!DestBundle->IsScheduled) {
2781 BundleMember->incrementUnscheduledDeps(1);
2783 if (!DestBundle->hasValidDependencies()) {
2784 WorkList.push_back(DestBundle);
2788 DepDest = DepDest->NextLoadStore;
2792 BundleMember = BundleMember->NextInBundle;
2794 if (InsertInReadyList && SD->isReady()) {
2795 ReadyInsts.push_back(SD);
2796 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2801 void BoUpSLP::BlockScheduling::resetSchedule() {
2802 assert(ScheduleStart &&
2803 "tried to reset schedule on block which has not been scheduled");
2804 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2805 ScheduleData *SD = getScheduleData(I);
2806 assert(isInSchedulingRegion(SD));
2807 SD->IsScheduled = false;
2808 SD->resetUnscheduledDeps();
2813 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2815 if (!BS->ScheduleStart)
2818 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2820 BS->resetSchedule();
2822 // For the real scheduling we use a more sophisticated ready-list: it is
2823 // sorted by the original instruction location. This lets the final schedule
2824 // be as close as possible to the original instruction order.
2825 struct ScheduleDataCompare {
2826 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2827 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2830 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2832 // Ensure that all depencency data is updated and fill the ready-list with
2833 // initial instructions.
2835 int NumToSchedule = 0;
2836 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2837 I = I->getNextNode()) {
2838 ScheduleData *SD = BS->getScheduleData(I);
2840 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2841 "scheduler and vectorizer have different opinion on what is a bundle");
2842 SD->FirstInBundle->SchedulingPriority = Idx++;
2843 if (SD->isSchedulingEntity()) {
2844 BS->calculateDependencies(SD, false, this);
2848 BS->initialFillReadyList(ReadyInsts);
2850 Instruction *LastScheduledInst = BS->ScheduleEnd;
2852 // Do the "real" scheduling.
2853 while (!ReadyInsts.empty()) {
2854 ScheduleData *picked = *ReadyInsts.begin();
2855 ReadyInsts.erase(ReadyInsts.begin());
2857 // Move the scheduled instruction(s) to their dedicated places, if not
2859 ScheduleData *BundleMember = picked;
2860 while (BundleMember) {
2861 Instruction *pickedInst = BundleMember->Inst;
2862 if (LastScheduledInst->getNextNode() != pickedInst) {
2863 BS->BB->getInstList().remove(pickedInst);
2864 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2866 LastScheduledInst = pickedInst;
2867 BundleMember = BundleMember->NextInBundle;
2870 BS->schedule(picked, ReadyInsts);
2873 assert(NumToSchedule == 0 && "could not schedule all instructions");
2875 // Avoid duplicate scheduling of the block.
2876 BS->ScheduleStart = nullptr;
2879 /// The SLPVectorizer Pass.
2880 struct SLPVectorizer : public FunctionPass {
2881 typedef SmallVector<StoreInst *, 8> StoreList;
2882 typedef MapVector<Value *, StoreList> StoreListMap;
2884 /// Pass identification, replacement for typeid
2887 explicit SLPVectorizer() : FunctionPass(ID) {
2888 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2891 ScalarEvolution *SE;
2892 const DataLayout *DL;
2893 TargetTransformInfo *TTI;
2894 TargetLibraryInfo *TLI;
2898 AssumptionCache *AC;
2900 bool runOnFunction(Function &F) override {
2901 if (skipOptnoneFunction(F))
2904 SE = &getAnalysis<ScalarEvolution>();
2905 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2906 DL = DLP ? &DLP->getDataLayout() : nullptr;
2907 TTI = &getAnalysis<TargetTransformInfo>();
2908 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2909 TLI = TLIP ? &TLIP->getTLI() : nullptr;
2910 AA = &getAnalysis<AliasAnalysis>();
2911 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2912 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2913 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2916 bool Changed = false;
2918 // If the target claims to have no vector registers don't attempt
2920 if (!TTI->getNumberOfRegisters(true))
2923 // Must have DataLayout. We can't require it because some tests run w/o
2928 // Don't vectorize when the attribute NoImplicitFloat is used.
2929 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2932 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2934 // Use the bottom up slp vectorizer to construct chains that start with
2935 // store instructions.
2936 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AC);
2938 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
2939 // delete instructions.
2941 // Scan the blocks in the function in post order.
2942 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2943 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2944 BasicBlock *BB = *it;
2945 // Vectorize trees that end at stores.
2946 if (unsigned count = collectStores(BB, R)) {
2948 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2949 Changed |= vectorizeStoreChains(R);
2952 // Vectorize trees that end at reductions.
2953 Changed |= vectorizeChainsInBlock(BB, R);
2957 R.optimizeGatherSequence();
2958 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2959 DEBUG(verifyFunction(F));
2964 void getAnalysisUsage(AnalysisUsage &AU) const override {
2965 FunctionPass::getAnalysisUsage(AU);
2966 AU.addRequired<AssumptionCacheTracker>();
2967 AU.addRequired<ScalarEvolution>();
2968 AU.addRequired<AliasAnalysis>();
2969 AU.addRequired<TargetTransformInfo>();
2970 AU.addRequired<LoopInfoWrapperPass>();
2971 AU.addRequired<DominatorTreeWrapperPass>();
2972 AU.addPreserved<LoopInfoWrapperPass>();
2973 AU.addPreserved<DominatorTreeWrapperPass>();
2974 AU.setPreservesCFG();
2979 /// \brief Collect memory references and sort them according to their base
2980 /// object. We sort the stores to their base objects to reduce the cost of the
2981 /// quadratic search on the stores. TODO: We can further reduce this cost
2982 /// if we flush the chain creation every time we run into a memory barrier.
2983 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2985 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2986 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2988 /// \brief Try to vectorize a list of operands.
2989 /// \@param BuildVector A list of users to ignore for the purpose of
2990 /// scheduling and that don't need extracting.
2991 /// \returns true if a value was vectorized.
2992 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2993 ArrayRef<Value *> BuildVector = None,
2994 bool allowReorder = false);
2996 /// \brief Try to vectorize a chain that may start at the operands of \V;
2997 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2999 /// \brief Vectorize the stores that were collected in StoreRefs.
3000 bool vectorizeStoreChains(BoUpSLP &R);
3002 /// \brief Scan the basic block and look for patterns that are likely to start
3003 /// a vectorization chain.
3004 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
3006 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
3009 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
3012 StoreListMap StoreRefs;
3015 /// \brief Check that the Values in the slice in VL array are still existent in
3016 /// the WeakVH array.
3017 /// Vectorization of part of the VL array may cause later values in the VL array
3018 /// to become invalid. We track when this has happened in the WeakVH array.
3019 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
3020 SmallVectorImpl<WeakVH> &VH,
3021 unsigned SliceBegin,
3022 unsigned SliceSize) {
3023 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
3030 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
3031 int CostThreshold, BoUpSLP &R) {
3032 unsigned ChainLen = Chain.size();
3033 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3035 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
3036 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
3037 unsigned VF = MinVecRegSize / Sz;
3039 if (!isPowerOf2_32(Sz) || VF < 2)
3042 // Keep track of values that were deleted by vectorizing in the loop below.
3043 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3045 bool Changed = false;
3046 // Look for profitable vectorizable trees at all offsets, starting at zero.
3047 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3051 // Check that a previous iteration of this loop did not delete the Value.
3052 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3055 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3057 ArrayRef<Value *> Operands = Chain.slice(i, VF);
3059 R.buildTree(Operands);
3061 int Cost = R.getTreeCost();
3063 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3064 if (Cost < CostThreshold) {
3065 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3068 // Move to the next bundle.
3077 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3078 int costThreshold, BoUpSLP &R) {
3079 SetVector<Value *> Heads, Tails;
3080 SmallDenseMap<Value *, Value *> ConsecutiveChain;
3082 // We may run into multiple chains that merge into a single chain. We mark the
3083 // stores that we vectorized so that we don't visit the same store twice.
3084 BoUpSLP::ValueSet VectorizedStores;
3085 bool Changed = false;
3087 // Do a quadratic search on all of the given stores and find
3088 // all of the pairs of stores that follow each other.
3089 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3090 for (unsigned j = 0; j < e; ++j) {
3094 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
3095 Tails.insert(Stores[j]);
3096 Heads.insert(Stores[i]);
3097 ConsecutiveChain[Stores[i]] = Stores[j];
3102 // For stores that start but don't end a link in the chain:
3103 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
3105 if (Tails.count(*it))
3108 // We found a store instr that starts a chain. Now follow the chain and try
3110 BoUpSLP::ValueList Operands;
3112 // Collect the chain into a list.
3113 while (Tails.count(I) || Heads.count(I)) {
3114 if (VectorizedStores.count(I))
3116 Operands.push_back(I);
3117 // Move to the next value in the chain.
3118 I = ConsecutiveChain[I];
3121 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
3123 // Mark the vectorized stores so that we don't vectorize them again.
3125 VectorizedStores.insert(Operands.begin(), Operands.end());
3126 Changed |= Vectorized;
3133 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
3136 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3137 StoreInst *SI = dyn_cast<StoreInst>(it);
3141 // Don't touch volatile stores.
3142 if (!SI->isSimple())
3145 // Check that the pointer points to scalars.
3146 Type *Ty = SI->getValueOperand()->getType();
3147 if (Ty->isAggregateType() || Ty->isVectorTy())
3150 // Find the base pointer.
3151 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
3153 // Save the store locations.
3154 StoreRefs[Ptr].push_back(SI);
3160 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3163 Value *VL[] = { A, B };
3164 return tryToVectorizeList(VL, R, None, true);
3167 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3168 ArrayRef<Value *> BuildVector,
3169 bool allowReorder) {
3173 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3175 // Check that all of the parts are scalar instructions of the same type.
3176 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3180 unsigned Opcode0 = I0->getOpcode();
3182 Type *Ty0 = I0->getType();
3183 unsigned Sz = DL->getTypeSizeInBits(Ty0);
3184 unsigned VF = MinVecRegSize / Sz;
3186 for (int i = 0, e = VL.size(); i < e; ++i) {
3187 Type *Ty = VL[i]->getType();
3188 if (Ty->isAggregateType() || Ty->isVectorTy())
3190 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
3191 if (!Inst || Inst->getOpcode() != Opcode0)
3195 bool Changed = false;
3197 // Keep track of values that were deleted by vectorizing in the loop below.
3198 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3200 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3201 unsigned OpsWidth = 0;
3208 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3211 // Check that a previous iteration of this loop did not delete the Value.
3212 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3215 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3217 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3219 ArrayRef<Value *> BuildVectorSlice;
3220 if (!BuildVector.empty())
3221 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3223 R.buildTree(Ops, BuildVectorSlice);
3224 // TODO: check if we can allow reordering also for other cases than
3225 // tryToVectorizePair()
3226 if (allowReorder && R.shouldReorder()) {
3227 assert(Ops.size() == 2);
3228 assert(BuildVectorSlice.empty());
3229 Value *ReorderedOps[] = { Ops[1], Ops[0] };
3230 R.buildTree(ReorderedOps, None);
3232 int Cost = R.getTreeCost();
3234 if (Cost < -SLPCostThreshold) {
3235 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3236 Value *VectorizedRoot = R.vectorizeTree();
3238 // Reconstruct the build vector by extracting the vectorized root. This
3239 // way we handle the case where some elements of the vector are undefined.
3240 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3241 if (!BuildVectorSlice.empty()) {
3242 // The insert point is the last build vector instruction. The vectorized
3243 // root will precede it. This guarantees that we get an instruction. The
3244 // vectorized tree could have been constant folded.
3245 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3246 unsigned VecIdx = 0;
3247 for (auto &V : BuildVectorSlice) {
3248 IRBuilder<true, NoFolder> Builder(
3249 ++BasicBlock::iterator(InsertAfter));
3250 InsertElementInst *IE = cast<InsertElementInst>(V);
3251 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3252 VectorizedRoot, Builder.getInt32(VecIdx++)));
3253 IE->setOperand(1, Extract);
3254 IE->removeFromParent();
3255 IE->insertAfter(Extract);
3259 // Move to the next bundle.
3268 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3272 // Try to vectorize V.
3273 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3276 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3277 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3279 if (B && B->hasOneUse()) {
3280 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3281 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3282 if (tryToVectorizePair(A, B0, R)) {
3285 if (tryToVectorizePair(A, B1, R)) {
3291 if (A && A->hasOneUse()) {
3292 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3293 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3294 if (tryToVectorizePair(A0, B, R)) {
3297 if (tryToVectorizePair(A1, B, R)) {
3304 /// \brief Generate a shuffle mask to be used in a reduction tree.
3306 /// \param VecLen The length of the vector to be reduced.
3307 /// \param NumEltsToRdx The number of elements that should be reduced in the
3309 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3310 /// reduction. A pairwise reduction will generate a mask of
3311 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3312 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3313 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3314 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3315 bool IsPairwise, bool IsLeft,
3316 IRBuilder<> &Builder) {
3317 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3319 SmallVector<Constant *, 32> ShuffleMask(
3320 VecLen, UndefValue::get(Builder.getInt32Ty()));
3323 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3324 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3325 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3327 // Move the upper half of the vector to the lower half.
3328 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3329 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3331 return ConstantVector::get(ShuffleMask);
3335 /// Model horizontal reductions.
3337 /// A horizontal reduction is a tree of reduction operations (currently add and
3338 /// fadd) that has operations that can be put into a vector as its leaf.
3339 /// For example, this tree:
3346 /// This tree has "mul" as its reduced values and "+" as its reduction
3347 /// operations. A reduction might be feeding into a store or a binary operation
3362 class HorizontalReduction {
3363 SmallVector<Value *, 16> ReductionOps;
3364 SmallVector<Value *, 32> ReducedVals;
3366 BinaryOperator *ReductionRoot;
3367 PHINode *ReductionPHI;
3369 /// The opcode of the reduction.
3370 unsigned ReductionOpcode;
3371 /// The opcode of the values we perform a reduction on.
3372 unsigned ReducedValueOpcode;
3373 /// The width of one full horizontal reduction operation.
3374 unsigned ReduxWidth;
3375 /// Should we model this reduction as a pairwise reduction tree or a tree that
3376 /// splits the vector in halves and adds those halves.
3377 bool IsPairwiseReduction;
3380 HorizontalReduction()
3381 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3382 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3384 /// \brief Try to find a reduction tree.
3385 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3386 const DataLayout *DL) {
3388 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3389 "Thi phi needs to use the binary operator");
3391 // We could have a initial reductions that is not an add.
3392 // r *= v1 + v2 + v3 + v4
3393 // In such a case start looking for a tree rooted in the first '+'.
3395 if (B->getOperand(0) == Phi) {
3397 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3398 } else if (B->getOperand(1) == Phi) {
3400 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3407 Type *Ty = B->getType();
3408 if (Ty->isVectorTy())
3411 ReductionOpcode = B->getOpcode();
3412 ReducedValueOpcode = 0;
3413 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3420 // We currently only support adds.
3421 if (ReductionOpcode != Instruction::Add &&
3422 ReductionOpcode != Instruction::FAdd)
3425 // Post order traverse the reduction tree starting at B. We only handle true
3426 // trees containing only binary operators.
3427 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3428 Stack.push_back(std::make_pair(B, 0));
3429 while (!Stack.empty()) {
3430 BinaryOperator *TreeN = Stack.back().first;
3431 unsigned EdgeToVist = Stack.back().second++;
3432 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3434 // Only handle trees in the current basic block.
3435 if (TreeN->getParent() != B->getParent())
3438 // Each tree node needs to have one user except for the ultimate
3440 if (!TreeN->hasOneUse() && TreeN != B)
3444 if (EdgeToVist == 2 || IsReducedValue) {
3445 if (IsReducedValue) {
3446 // Make sure that the opcodes of the operations that we are going to
3448 if (!ReducedValueOpcode)
3449 ReducedValueOpcode = TreeN->getOpcode();
3450 else if (ReducedValueOpcode != TreeN->getOpcode())
3452 ReducedVals.push_back(TreeN);
3454 // We need to be able to reassociate the adds.
3455 if (!TreeN->isAssociative())
3457 ReductionOps.push_back(TreeN);
3464 // Visit left or right.
3465 Value *NextV = TreeN->getOperand(EdgeToVist);
3466 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3468 Stack.push_back(std::make_pair(Next, 0));
3469 else if (NextV != Phi)
3475 /// \brief Attempt to vectorize the tree found by
3476 /// matchAssociativeReduction.
3477 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3478 if (ReducedVals.empty())
3481 unsigned NumReducedVals = ReducedVals.size();
3482 if (NumReducedVals < ReduxWidth)
3485 Value *VectorizedTree = nullptr;
3486 IRBuilder<> Builder(ReductionRoot);
3487 FastMathFlags Unsafe;
3488 Unsafe.setUnsafeAlgebra();
3489 Builder.SetFastMathFlags(Unsafe);
3492 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3493 V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3496 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3497 if (Cost >= -SLPCostThreshold)
3500 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3503 // Vectorize a tree.
3504 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3505 Value *VectorizedRoot = V.vectorizeTree();
3507 // Emit a reduction.
3508 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3509 if (VectorizedTree) {
3510 Builder.SetCurrentDebugLocation(Loc);
3511 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3512 ReducedSubTree, "bin.rdx");
3514 VectorizedTree = ReducedSubTree;
3517 if (VectorizedTree) {
3518 // Finish the reduction.
3519 for (; i < NumReducedVals; ++i) {
3520 Builder.SetCurrentDebugLocation(
3521 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3522 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3527 assert(ReductionRoot && "Need a reduction operation");
3528 ReductionRoot->setOperand(0, VectorizedTree);
3529 ReductionRoot->setOperand(1, ReductionPHI);
3531 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3533 return VectorizedTree != nullptr;
3538 /// \brief Calcuate the cost of a reduction.
3539 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3540 Type *ScalarTy = FirstReducedVal->getType();
3541 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3543 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3544 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3546 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3547 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3549 int ScalarReduxCost =
3550 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3552 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3553 << " for reduction that starts with " << *FirstReducedVal
3555 << (IsPairwiseReduction ? "pairwise" : "splitting")
3556 << " reduction)\n");
3558 return VecReduxCost - ScalarReduxCost;
3561 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3562 Value *R, const Twine &Name = "") {
3563 if (Opcode == Instruction::FAdd)
3564 return Builder.CreateFAdd(L, R, Name);
3565 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3568 /// \brief Emit a horizontal reduction of the vectorized value.
3569 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3570 assert(VectorizedValue && "Need to have a vectorized tree node");
3571 assert(isPowerOf2_32(ReduxWidth) &&
3572 "We only handle power-of-two reductions for now");
3574 Value *TmpVec = VectorizedValue;
3575 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3576 if (IsPairwiseReduction) {
3578 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3580 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3582 Value *LeftShuf = Builder.CreateShuffleVector(
3583 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3584 Value *RightShuf = Builder.CreateShuffleVector(
3585 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3587 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3591 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3592 Value *Shuf = Builder.CreateShuffleVector(
3593 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3594 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3598 // The result is in the first element of the vector.
3599 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3603 /// \brief Recognize construction of vectors like
3604 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3605 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3606 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3607 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3609 /// Returns true if it matches
3611 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3612 SmallVectorImpl<Value *> &BuildVector,
3613 SmallVectorImpl<Value *> &BuildVectorOpds) {
3614 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3617 InsertElementInst *IE = FirstInsertElem;
3619 BuildVector.push_back(IE);
3620 BuildVectorOpds.push_back(IE->getOperand(1));
3622 if (IE->use_empty())
3625 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3629 // If this isn't the final use, make sure the next insertelement is the only
3630 // use. It's OK if the final constructed vector is used multiple times
3631 if (!IE->hasOneUse())
3640 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3641 return V->getType() < V2->getType();
3644 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3645 bool Changed = false;
3646 SmallVector<Value *, 4> Incoming;
3647 SmallSet<Value *, 16> VisitedInstrs;
3649 bool HaveVectorizedPhiNodes = true;
3650 while (HaveVectorizedPhiNodes) {
3651 HaveVectorizedPhiNodes = false;
3653 // Collect the incoming values from the PHIs.
3655 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3657 PHINode *P = dyn_cast<PHINode>(instr);
3661 if (!VisitedInstrs.count(P))
3662 Incoming.push_back(P);
3666 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3668 // Try to vectorize elements base on their type.
3669 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3673 // Look for the next elements with the same type.
3674 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3675 while (SameTypeIt != E &&
3676 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3677 VisitedInstrs.insert(*SameTypeIt);
3681 // Try to vectorize them.
3682 unsigned NumElts = (SameTypeIt - IncIt);
3683 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3684 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3685 // Success start over because instructions might have been changed.
3686 HaveVectorizedPhiNodes = true;
3691 // Start over at the next instruction of a different type (or the end).
3696 VisitedInstrs.clear();
3698 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3699 // We may go through BB multiple times so skip the one we have checked.
3700 if (!VisitedInstrs.insert(it).second)
3703 if (isa<DbgInfoIntrinsic>(it))
3706 // Try to vectorize reductions that use PHINodes.
3707 if (PHINode *P = dyn_cast<PHINode>(it)) {
3708 // Check that the PHI is a reduction PHI.
3709 if (P->getNumIncomingValues() != 2)
3712 (P->getIncomingBlock(0) == BB
3713 ? (P->getIncomingValue(0))
3714 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3716 // Check if this is a Binary Operator.
3717 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3721 // Try to match and vectorize a horizontal reduction.
3722 HorizontalReduction HorRdx;
3723 if (ShouldVectorizeHor &&
3724 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3725 HorRdx.tryToReduce(R, TTI)) {
3732 Value *Inst = BI->getOperand(0);
3734 Inst = BI->getOperand(1);
3736 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3737 // We would like to start over since some instructions are deleted
3738 // and the iterator may become invalid value.
3748 // Try to vectorize horizontal reductions feeding into a store.
3749 if (ShouldStartVectorizeHorAtStore)
3750 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3751 if (BinaryOperator *BinOp =
3752 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3753 HorizontalReduction HorRdx;
3754 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3755 HorRdx.tryToReduce(R, TTI)) ||
3756 tryToVectorize(BinOp, R))) {
3764 // Try to vectorize horizontal reductions feeding into a return.
3765 if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
3766 if (RI->getNumOperands() != 0)
3767 if (BinaryOperator *BinOp =
3768 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
3769 DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
3770 if (tryToVectorizePair(BinOp->getOperand(0),
3771 BinOp->getOperand(1), R)) {
3779 // Try to vectorize trees that start at compare instructions.
3780 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3781 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3783 // We would like to start over since some instructions are deleted
3784 // and the iterator may become invalid value.
3790 for (int i = 0; i < 2; ++i) {
3791 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3792 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3794 // We would like to start over since some instructions are deleted
3795 // and the iterator may become invalid value.
3804 // Try to vectorize trees that start at insertelement instructions.
3805 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3806 SmallVector<Value *, 16> BuildVector;
3807 SmallVector<Value *, 16> BuildVectorOpds;
3808 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3811 // Vectorize starting with the build vector operands ignoring the
3812 // BuildVector instructions for the purpose of scheduling and user
3814 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3827 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3828 bool Changed = false;
3829 // Attempt to sort and vectorize each of the store-groups.
3830 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3832 if (it->second.size() < 2)
3835 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3836 << it->second.size() << ".\n");
3838 // Process the stores in chunks of 16.
3839 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3840 unsigned Len = std::min<unsigned>(CE - CI, 16);
3841 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3842 -SLPCostThreshold, R);
3848 } // end anonymous namespace
3850 char SLPVectorizer::ID = 0;
3851 static const char lv_name[] = "SLP Vectorizer";
3852 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3853 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3854 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3855 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3856 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3857 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3858 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3861 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }