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/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/AssumptionTracker.h"
25 #include "llvm/Analysis/CodeMetrics.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/NoFolder.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/Verifier.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/VectorUtils.h"
52 #define SV_NAME "slp-vectorizer"
53 #define DEBUG_TYPE "SLP"
55 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
58 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
59 cl::desc("Only vectorize if you gain more than this "
63 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
64 cl::desc("Attempt to vectorize horizontal reductions"));
66 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
67 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
69 "Attempt to vectorize horizontal reductions feeding into a store"));
73 static const unsigned MinVecRegSize = 128;
75 static const unsigned RecursionMaxDepth = 12;
77 /// \returns the parent basic block if all of the instructions in \p VL
78 /// are in the same block or null otherwise.
79 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
80 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
83 BasicBlock *BB = I0->getParent();
84 for (int i = 1, e = VL.size(); i < e; i++) {
85 Instruction *I = dyn_cast<Instruction>(VL[i]);
89 if (BB != I->getParent())
95 /// \returns True if all of the values in \p VL are constants.
96 static bool allConstant(ArrayRef<Value *> VL) {
97 for (unsigned i = 0, e = VL.size(); i < e; ++i)
98 if (!isa<Constant>(VL[i]))
103 /// \returns True if all of the values in \p VL are identical.
104 static bool isSplat(ArrayRef<Value *> VL) {
105 for (unsigned i = 1, e = VL.size(); i < e; ++i)
111 ///\returns Opcode that can be clubbed with \p Op to create an alternate
112 /// sequence which can later be merged as a ShuffleVector instruction.
113 static unsigned getAltOpcode(unsigned Op) {
115 case Instruction::FAdd:
116 return Instruction::FSub;
117 case Instruction::FSub:
118 return Instruction::FAdd;
119 case Instruction::Add:
120 return Instruction::Sub;
121 case Instruction::Sub:
122 return Instruction::Add;
128 ///\returns bool representing if Opcode \p Op can be part
129 /// of an alternate sequence which can later be merged as
130 /// a ShuffleVector instruction.
131 static bool canCombineAsAltInst(unsigned Op) {
132 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
133 Op == Instruction::Sub || Op == Instruction::Add)
138 /// \returns ShuffleVector instruction if intructions in \p VL have
139 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
140 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
141 static unsigned isAltInst(ArrayRef<Value *> VL) {
142 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
143 unsigned Opcode = I0->getOpcode();
144 unsigned AltOpcode = getAltOpcode(Opcode);
145 for (int i = 1, e = VL.size(); i < e; i++) {
146 Instruction *I = dyn_cast<Instruction>(VL[i]);
147 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
150 return Instruction::ShuffleVector;
153 /// \returns The opcode if all of the Instructions in \p VL have the same
155 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
156 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
159 unsigned Opcode = I0->getOpcode();
160 for (int i = 1, e = VL.size(); i < e; i++) {
161 Instruction *I = dyn_cast<Instruction>(VL[i]);
162 if (!I || Opcode != I->getOpcode()) {
163 if (canCombineAsAltInst(Opcode) && i == 1)
164 return isAltInst(VL);
171 /// Get the intersection (logical and) of all of the potential IR flags
172 /// of each scalar operation (VL) that will be converted into a vector (I).
173 /// Flag set: NSW, NUW, exact, and all of fast-math.
174 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
175 if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
176 if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
177 // Intersection is initialized to the 0th scalar,
178 // so start counting from index '1'.
179 for (int i = 1, e = VL.size(); i < e; ++i) {
180 if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
181 Intersection->andIRFlags(Scalar);
183 VecOp->copyIRFlags(Intersection);
188 /// \returns \p I after propagating metadata from \p VL.
189 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
190 Instruction *I0 = cast<Instruction>(VL[0]);
191 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
192 I0->getAllMetadataOtherThanDebugLoc(Metadata);
194 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
195 unsigned Kind = Metadata[i].first;
196 MDNode *MD = Metadata[i].second;
198 for (int i = 1, e = VL.size(); MD && i != e; i++) {
199 Instruction *I = cast<Instruction>(VL[i]);
200 MDNode *IMD = I->getMetadata(Kind);
204 MD = nullptr; // Remove unknown metadata
206 case LLVMContext::MD_tbaa:
207 MD = MDNode::getMostGenericTBAA(MD, IMD);
209 case LLVMContext::MD_alias_scope:
210 case LLVMContext::MD_noalias:
211 MD = MDNode::intersect(MD, IMD);
213 case LLVMContext::MD_fpmath:
214 MD = MDNode::getMostGenericFPMath(MD, IMD);
218 I->setMetadata(Kind, MD);
223 /// \returns The type that all of the values in \p VL have or null if there
224 /// are different types.
225 static Type* getSameType(ArrayRef<Value *> VL) {
226 Type *Ty = VL[0]->getType();
227 for (int i = 1, e = VL.size(); i < e; i++)
228 if (VL[i]->getType() != Ty)
234 /// \returns True if the ExtractElement instructions in VL can be vectorized
235 /// to use the original vector.
236 static bool CanReuseExtract(ArrayRef<Value *> VL) {
237 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
238 // Check if all of the extracts come from the same vector and from the
241 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
242 Value *Vec = E0->getOperand(0);
244 // We have to extract from the same vector type.
245 unsigned NElts = Vec->getType()->getVectorNumElements();
247 if (NElts != VL.size())
250 // Check that all of the indices extract from the correct offset.
251 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
252 if (!CI || CI->getZExtValue())
255 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
256 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
257 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
259 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
266 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
267 SmallVectorImpl<Value *> &Left,
268 SmallVectorImpl<Value *> &Right) {
270 SmallVector<Value *, 16> OrigLeft, OrigRight;
272 bool AllSameOpcodeLeft = true;
273 bool AllSameOpcodeRight = true;
274 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
275 Instruction *I = cast<Instruction>(VL[i]);
276 Value *V0 = I->getOperand(0);
277 Value *V1 = I->getOperand(1);
279 OrigLeft.push_back(V0);
280 OrigRight.push_back(V1);
282 Instruction *I0 = dyn_cast<Instruction>(V0);
283 Instruction *I1 = dyn_cast<Instruction>(V1);
285 // Check whether all operands on one side have the same opcode. In this case
286 // we want to preserve the original order and not make things worse by
288 AllSameOpcodeLeft = I0;
289 AllSameOpcodeRight = I1;
291 if (i && AllSameOpcodeLeft) {
292 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
293 if(P0->getOpcode() != I0->getOpcode())
294 AllSameOpcodeLeft = false;
296 AllSameOpcodeLeft = false;
298 if (i && AllSameOpcodeRight) {
299 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
300 if(P1->getOpcode() != I1->getOpcode())
301 AllSameOpcodeRight = false;
303 AllSameOpcodeRight = false;
306 // Sort two opcodes. In the code below we try to preserve the ability to use
307 // broadcast of values instead of individual inserts.
314 // If we just sorted according to opcode we would leave the first line in
315 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
318 // Because vr2 and vr1 are from the same load we loose the opportunity of a
319 // broadcast for the packed right side in the backend: we have [vr1, vl2]
320 // instead of [vr1, vr2=vr1].
322 if(!i && I0->getOpcode() > I1->getOpcode()) {
325 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
326 // Try not to destroy a broad cast for no apparent benefit.
329 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
330 // Try preserve broadcasts.
333 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
334 // Try preserve broadcasts.
343 // One opcode, put the instruction on the right.
353 bool LeftBroadcast = isSplat(Left);
354 bool RightBroadcast = isSplat(Right);
356 // Don't reorder if the operands where good to begin with.
357 if (!(LeftBroadcast || RightBroadcast) &&
358 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
364 /// \returns True if in-tree use also needs extract. This refers to
365 /// possible scalar operand in vectorized instruction.
366 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
367 TargetLibraryInfo *TLI) {
369 unsigned Opcode = UserInst->getOpcode();
371 case Instruction::Load: {
372 LoadInst *LI = cast<LoadInst>(UserInst);
373 return (LI->getPointerOperand() == Scalar);
375 case Instruction::Store: {
376 StoreInst *SI = cast<StoreInst>(UserInst);
377 return (SI->getPointerOperand() == Scalar);
379 case Instruction::Call: {
380 CallInst *CI = cast<CallInst>(UserInst);
381 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
382 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
383 return (CI->getArgOperand(1) == Scalar);
391 /// Bottom Up SLP Vectorizer.
394 typedef SmallVector<Value *, 8> ValueList;
395 typedef SmallVector<Instruction *, 16> InstrList;
396 typedef SmallPtrSet<Value *, 16> ValueSet;
397 typedef SmallVector<StoreInst *, 8> StoreList;
399 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
400 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
401 LoopInfo *Li, DominatorTree *Dt, AssumptionTracker *AT)
402 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0),
403 F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
404 Builder(Se->getContext()) {
405 CodeMetrics::collectEphemeralValues(F, AT, EphValues);
408 /// \brief Vectorize the tree that starts with the elements in \p VL.
409 /// Returns the vectorized root.
410 Value *vectorizeTree();
412 /// \returns the cost incurred by unwanted spills and fills, caused by
413 /// holding live values over call sites.
416 /// \returns the vectorization cost of the subtree that starts at \p VL.
417 /// A negative number means that this is profitable.
420 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
421 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
422 void buildTree(ArrayRef<Value *> Roots,
423 ArrayRef<Value *> UserIgnoreLst = None);
425 /// Clear the internal data structures that are created by 'buildTree'.
427 VectorizableTree.clear();
428 ScalarToTreeEntry.clear();
430 ExternalUses.clear();
431 NumLoadsWantToKeepOrder = 0;
432 NumLoadsWantToChangeOrder = 0;
433 for (auto &Iter : BlocksSchedules) {
434 BlockScheduling *BS = Iter.second.get();
439 /// \returns true if the memory operations A and B are consecutive.
440 bool isConsecutiveAccess(Value *A, Value *B);
442 /// For consecutive loads (+(+ v0, v1)(+ v2, v3)), Left had v0 and v2
443 /// while Right had v1 and v3, which prevented bundling them into
444 /// a vector of loads. Rorder them so that Left now has v0 and v1
445 /// while Right has v2 and v3 enabling their bundling into a vector.
446 void reorderIfConsecutiveLoads(SmallVectorImpl<Value *> &Left,
447 SmallVectorImpl<Value *> &Right);
449 /// \brief Perform LICM and CSE on the newly generated gather sequences.
450 void optimizeGatherSequence();
452 /// \returns true if it is benefitial to reverse the vector order.
453 bool shouldReorder() const {
454 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
460 /// \returns the cost of the vectorizable entry.
461 int getEntryCost(TreeEntry *E);
463 /// This is the recursive part of buildTree.
464 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
466 /// Vectorize a single entry in the tree.
467 Value *vectorizeTree(TreeEntry *E);
469 /// Vectorize a single entry in the tree, starting in \p VL.
470 Value *vectorizeTree(ArrayRef<Value *> VL);
472 /// \returns the pointer to the vectorized value if \p VL is already
473 /// vectorized, or NULL. They may happen in cycles.
474 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
476 /// \brief Take the pointer operand from the Load/Store instruction.
477 /// \returns NULL if this is not a valid Load/Store instruction.
478 static Value *getPointerOperand(Value *I);
480 /// \brief Take the address space operand from the Load/Store instruction.
481 /// \returns -1 if this is not a valid Load/Store instruction.
482 static unsigned getAddressSpaceOperand(Value *I);
484 /// \returns the scalarization cost for this type. Scalarization in this
485 /// context means the creation of vectors from a group of scalars.
486 int getGatherCost(Type *Ty);
488 /// \returns the scalarization cost for this list of values. Assuming that
489 /// this subtree gets vectorized, we may need to extract the values from the
490 /// roots. This method calculates the cost of extracting the values.
491 int getGatherCost(ArrayRef<Value *> VL);
493 /// \brief Set the Builder insert point to one after the last instruction in
495 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
497 /// \returns a vector from a collection of scalars in \p VL.
498 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
500 /// \returns whether the VectorizableTree is fully vectoriable and will
501 /// be beneficial even the tree height is tiny.
502 bool isFullyVectorizableTinyTree();
505 TreeEntry() : Scalars(), VectorizedValue(nullptr),
508 /// \returns true if the scalars in VL are equal to this entry.
509 bool isSame(ArrayRef<Value *> VL) const {
510 assert(VL.size() == Scalars.size() && "Invalid size");
511 return std::equal(VL.begin(), VL.end(), Scalars.begin());
514 /// A vector of scalars.
517 /// The Scalars are vectorized into this value. It is initialized to Null.
518 Value *VectorizedValue;
520 /// Do we need to gather this sequence ?
524 /// Create a new VectorizableTree entry.
525 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
526 VectorizableTree.push_back(TreeEntry());
527 int idx = VectorizableTree.size() - 1;
528 TreeEntry *Last = &VectorizableTree[idx];
529 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
530 Last->NeedToGather = !Vectorized;
532 for (int i = 0, e = VL.size(); i != e; ++i) {
533 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
534 ScalarToTreeEntry[VL[i]] = idx;
537 MustGather.insert(VL.begin(), VL.end());
542 /// -- Vectorization State --
543 /// Holds all of the tree entries.
544 std::vector<TreeEntry> VectorizableTree;
546 /// Maps a specific scalar to its tree entry.
547 SmallDenseMap<Value*, int> ScalarToTreeEntry;
549 /// A list of scalars that we found that we need to keep as scalars.
552 /// This POD struct describes one external user in the vectorized tree.
553 struct ExternalUser {
554 ExternalUser (Value *S, llvm::User *U, int L) :
555 Scalar(S), User(U), Lane(L){};
556 // Which scalar in our function.
558 // Which user that uses the scalar.
560 // Which lane does the scalar belong to.
563 typedef SmallVector<ExternalUser, 16> UserList;
565 /// A list of values that need to extracted out of the tree.
566 /// This list holds pairs of (Internal Scalar : External User).
567 UserList ExternalUses;
569 /// Values used only by @llvm.assume calls.
570 SmallPtrSet<const Value *, 32> EphValues;
572 /// Holds all of the instructions that we gathered.
573 SetVector<Instruction *> GatherSeq;
574 /// A list of blocks that we are going to CSE.
575 SetVector<BasicBlock *> CSEBlocks;
577 /// Contains all scheduling relevant data for an instruction.
578 /// A ScheduleData either represents a single instruction or a member of an
579 /// instruction bundle (= a group of instructions which is combined into a
580 /// vector instruction).
581 struct ScheduleData {
583 // The initial value for the dependency counters. It means that the
584 // dependencies are not calculated yet.
585 enum { InvalidDeps = -1 };
588 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
589 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
590 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
591 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
593 void init(int BlockSchedulingRegionID) {
594 FirstInBundle = this;
595 NextInBundle = nullptr;
596 NextLoadStore = nullptr;
598 SchedulingRegionID = BlockSchedulingRegionID;
599 UnscheduledDepsInBundle = UnscheduledDeps;
603 /// Returns true if the dependency information has been calculated.
604 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
606 /// Returns true for single instructions and for bundle representatives
607 /// (= the head of a bundle).
608 bool isSchedulingEntity() const { return FirstInBundle == this; }
610 /// Returns true if it represents an instruction bundle and not only a
611 /// single instruction.
612 bool isPartOfBundle() const {
613 return NextInBundle != nullptr || FirstInBundle != this;
616 /// Returns true if it is ready for scheduling, i.e. it has no more
617 /// unscheduled depending instructions/bundles.
618 bool isReady() const {
619 assert(isSchedulingEntity() &&
620 "can't consider non-scheduling entity for ready list");
621 return UnscheduledDepsInBundle == 0 && !IsScheduled;
624 /// Modifies the number of unscheduled dependencies, also updating it for
625 /// the whole bundle.
626 int incrementUnscheduledDeps(int Incr) {
627 UnscheduledDeps += Incr;
628 return FirstInBundle->UnscheduledDepsInBundle += Incr;
631 /// Sets the number of unscheduled dependencies to the number of
633 void resetUnscheduledDeps() {
634 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
637 /// Clears all dependency information.
638 void clearDependencies() {
639 Dependencies = InvalidDeps;
640 resetUnscheduledDeps();
641 MemoryDependencies.clear();
644 void dump(raw_ostream &os) const {
645 if (!isSchedulingEntity()) {
647 } else if (NextInBundle) {
649 ScheduleData *SD = NextInBundle;
651 os << ';' << *SD->Inst;
652 SD = SD->NextInBundle;
662 /// Points to the head in an instruction bundle (and always to this for
663 /// single instructions).
664 ScheduleData *FirstInBundle;
666 /// Single linked list of all instructions in a bundle. Null if it is a
667 /// single instruction.
668 ScheduleData *NextInBundle;
670 /// Single linked list of all memory instructions (e.g. load, store, call)
671 /// in the block - until the end of the scheduling region.
672 ScheduleData *NextLoadStore;
674 /// The dependent memory instructions.
675 /// This list is derived on demand in calculateDependencies().
676 SmallVector<ScheduleData *, 4> MemoryDependencies;
678 /// This ScheduleData is in the current scheduling region if this matches
679 /// the current SchedulingRegionID of BlockScheduling.
680 int SchedulingRegionID;
682 /// Used for getting a "good" final ordering of instructions.
683 int SchedulingPriority;
685 /// The number of dependencies. Constitutes of the number of users of the
686 /// instruction plus the number of dependent memory instructions (if any).
687 /// This value is calculated on demand.
688 /// If InvalidDeps, the number of dependencies is not calculated yet.
692 /// The number of dependencies minus the number of dependencies of scheduled
693 /// instructions. As soon as this is zero, the instruction/bundle gets ready
695 /// Note that this is negative as long as Dependencies is not calculated.
698 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
699 /// single instructions.
700 int UnscheduledDepsInBundle;
702 /// True if this instruction is scheduled (or considered as scheduled in the
708 friend raw_ostream &operator<<(raw_ostream &os,
709 const BoUpSLP::ScheduleData &SD);
712 /// Contains all scheduling data for a basic block.
714 struct BlockScheduling {
716 BlockScheduling(BasicBlock *BB)
717 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
718 ScheduleStart(nullptr), ScheduleEnd(nullptr),
719 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
720 // Make sure that the initial SchedulingRegionID is greater than the
721 // initial SchedulingRegionID in ScheduleData (which is 0).
722 SchedulingRegionID(1) {}
726 ScheduleStart = nullptr;
727 ScheduleEnd = nullptr;
728 FirstLoadStoreInRegion = nullptr;
729 LastLoadStoreInRegion = nullptr;
731 // Make a new scheduling region, i.e. all existing ScheduleData is not
732 // in the new region yet.
733 ++SchedulingRegionID;
736 ScheduleData *getScheduleData(Value *V) {
737 ScheduleData *SD = ScheduleDataMap[V];
738 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
743 bool isInSchedulingRegion(ScheduleData *SD) {
744 return SD->SchedulingRegionID == SchedulingRegionID;
747 /// Marks an instruction as scheduled and puts all dependent ready
748 /// instructions into the ready-list.
749 template <typename ReadyListType>
750 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
751 SD->IsScheduled = true;
752 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
754 ScheduleData *BundleMember = SD;
755 while (BundleMember) {
756 // Handle the def-use chain dependencies.
757 for (Use &U : BundleMember->Inst->operands()) {
758 ScheduleData *OpDef = getScheduleData(U.get());
759 if (OpDef && OpDef->hasValidDependencies() &&
760 OpDef->incrementUnscheduledDeps(-1) == 0) {
761 // There are no more unscheduled dependencies after decrementing,
762 // so we can put the dependent instruction into the ready list.
763 ScheduleData *DepBundle = OpDef->FirstInBundle;
764 assert(!DepBundle->IsScheduled &&
765 "already scheduled bundle gets ready");
766 ReadyList.insert(DepBundle);
767 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
770 // Handle the memory dependencies.
771 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
772 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
773 // There are no more unscheduled dependencies after decrementing,
774 // so we can put the dependent instruction into the ready list.
775 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
776 assert(!DepBundle->IsScheduled &&
777 "already scheduled bundle gets ready");
778 ReadyList.insert(DepBundle);
779 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
782 BundleMember = BundleMember->NextInBundle;
786 /// Put all instructions into the ReadyList which are ready for scheduling.
787 template <typename ReadyListType>
788 void initialFillReadyList(ReadyListType &ReadyList) {
789 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
790 ScheduleData *SD = getScheduleData(I);
791 if (SD->isSchedulingEntity() && SD->isReady()) {
792 ReadyList.insert(SD);
793 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
798 /// Checks if a bundle of instructions can be scheduled, i.e. has no
799 /// cyclic dependencies. This is only a dry-run, no instructions are
800 /// actually moved at this stage.
801 bool tryScheduleBundle(ArrayRef<Value *> VL, AliasAnalysis *AA);
803 /// Un-bundles a group of instructions.
804 void cancelScheduling(ArrayRef<Value *> VL);
806 /// Extends the scheduling region so that V is inside the region.
807 void extendSchedulingRegion(Value *V);
809 /// Initialize the ScheduleData structures for new instructions in the
810 /// scheduling region.
811 void initScheduleData(Instruction *FromI, Instruction *ToI,
812 ScheduleData *PrevLoadStore,
813 ScheduleData *NextLoadStore);
815 /// Updates the dependency information of a bundle and of all instructions/
816 /// bundles which depend on the original bundle.
817 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
820 /// Sets all instruction in the scheduling region to un-scheduled.
821 void resetSchedule();
825 /// Simple memory allocation for ScheduleData.
826 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
828 /// The size of a ScheduleData array in ScheduleDataChunks.
831 /// The allocator position in the current chunk, which is the last entry
832 /// of ScheduleDataChunks.
835 /// Attaches ScheduleData to Instruction.
836 /// Note that the mapping survives during all vectorization iterations, i.e.
837 /// ScheduleData structures are recycled.
838 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
840 struct ReadyList : SmallVector<ScheduleData *, 8> {
841 void insert(ScheduleData *SD) { push_back(SD); }
844 /// The ready-list for scheduling (only used for the dry-run).
845 ReadyList ReadyInsts;
847 /// The first instruction of the scheduling region.
848 Instruction *ScheduleStart;
850 /// The first instruction _after_ the scheduling region.
851 Instruction *ScheduleEnd;
853 /// The first memory accessing instruction in the scheduling region
855 ScheduleData *FirstLoadStoreInRegion;
857 /// The last memory accessing instruction in the scheduling region
859 ScheduleData *LastLoadStoreInRegion;
861 /// The ID of the scheduling region. For a new vectorization iteration this
862 /// is incremented which "removes" all ScheduleData from the region.
863 int SchedulingRegionID;
866 /// Attaches the BlockScheduling structures to basic blocks.
867 DenseMap<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
869 /// Performs the "real" scheduling. Done before vectorization is actually
870 /// performed in a basic block.
871 void scheduleBlock(BlockScheduling *BS);
873 /// List of users to ignore during scheduling and that don't need extracting.
874 ArrayRef<Value *> UserIgnoreList;
876 // Number of load-bundles, which contain consecutive loads.
877 int NumLoadsWantToKeepOrder;
879 // Number of load-bundles of size 2, which are consecutive loads if reversed.
880 int NumLoadsWantToChangeOrder;
882 // Analysis and block reference.
885 const DataLayout *DL;
886 TargetTransformInfo *TTI;
887 TargetLibraryInfo *TLI;
891 /// Instruction builder to construct the vectorized tree.
896 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
902 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
903 ArrayRef<Value *> UserIgnoreLst) {
905 UserIgnoreList = UserIgnoreLst;
906 if (!getSameType(Roots))
908 buildTree_rec(Roots, 0);
910 // Collect the values that we need to extract from the tree.
911 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
912 TreeEntry *Entry = &VectorizableTree[EIdx];
915 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
916 Value *Scalar = Entry->Scalars[Lane];
918 // No need to handle users of gathered values.
919 if (Entry->NeedToGather)
922 for (User *U : Scalar->users()) {
923 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
925 Instruction *UserInst = dyn_cast<Instruction>(U);
929 // Skip in-tree scalars that become vectors
930 if (ScalarToTreeEntry.count(U)) {
931 int Idx = ScalarToTreeEntry[U];
932 TreeEntry *UseEntry = &VectorizableTree[Idx];
933 Value *UseScalar = UseEntry->Scalars[0];
934 // Some in-tree scalars will remain as scalar in vectorized
935 // instructions. If that is the case, the one in Lane 0 will
937 if (UseScalar != U ||
938 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
939 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
941 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
946 // Ignore users in the user ignore list.
947 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
948 UserIgnoreList.end())
951 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
952 Lane << " from " << *Scalar << ".\n");
953 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
960 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
961 bool SameTy = getSameType(VL); (void)SameTy;
962 bool isAltShuffle = false;
963 assert(SameTy && "Invalid types!");
965 if (Depth == RecursionMaxDepth) {
966 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
967 newTreeEntry(VL, false);
971 // Don't handle vectors.
972 if (VL[0]->getType()->isVectorTy()) {
973 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
974 newTreeEntry(VL, false);
978 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
979 if (SI->getValueOperand()->getType()->isVectorTy()) {
980 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
981 newTreeEntry(VL, false);
984 unsigned Opcode = getSameOpcode(VL);
986 // Check that this shuffle vector refers to the alternate
987 // sequence of opcodes.
988 if (Opcode == Instruction::ShuffleVector) {
989 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
990 unsigned Op = I0->getOpcode();
991 if (Op != Instruction::ShuffleVector)
995 // If all of the operands are identical or constant we have a simple solution.
996 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
997 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
998 newTreeEntry(VL, false);
1002 // We now know that this is a vector of instructions of the same type from
1005 // Don't vectorize ephemeral values.
1006 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1007 if (EphValues.count(VL[i])) {
1008 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1009 ") is ephemeral.\n");
1010 newTreeEntry(VL, false);
1015 // Check if this is a duplicate of another entry.
1016 if (ScalarToTreeEntry.count(VL[0])) {
1017 int Idx = ScalarToTreeEntry[VL[0]];
1018 TreeEntry *E = &VectorizableTree[Idx];
1019 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1020 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
1021 if (E->Scalars[i] != VL[i]) {
1022 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1023 newTreeEntry(VL, false);
1027 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
1031 // Check that none of the instructions in the bundle are already in the tree.
1032 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1033 if (ScalarToTreeEntry.count(VL[i])) {
1034 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1035 ") is already in tree.\n");
1036 newTreeEntry(VL, false);
1041 // If any of the scalars appears in the table OR it is marked as a value that
1042 // needs to stat scalar then we need to gather the scalars.
1043 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1044 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
1045 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
1046 newTreeEntry(VL, false);
1051 // Check that all of the users of the scalars that we want to vectorize are
1053 Instruction *VL0 = cast<Instruction>(VL[0]);
1054 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1056 if (!DT->isReachableFromEntry(BB)) {
1057 // Don't go into unreachable blocks. They may contain instructions with
1058 // dependency cycles which confuse the final scheduling.
1059 DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1060 newTreeEntry(VL, false);
1064 // Check that every instructions appears once in this bundle.
1065 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1066 for (unsigned j = i+1; j < e; ++j)
1067 if (VL[i] == VL[j]) {
1068 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1069 newTreeEntry(VL, false);
1073 auto &BSRef = BlocksSchedules[BB];
1075 BSRef = llvm::make_unique<BlockScheduling>(BB);
1077 BlockScheduling &BS = *BSRef.get();
1079 if (!BS.tryScheduleBundle(VL, AA)) {
1080 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1081 BS.cancelScheduling(VL);
1082 newTreeEntry(VL, false);
1085 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1088 case Instruction::PHI: {
1089 PHINode *PH = dyn_cast<PHINode>(VL0);
1091 // Check for terminator values (e.g. invoke).
1092 for (unsigned j = 0; j < VL.size(); ++j)
1093 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1094 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1095 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1097 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1098 BS.cancelScheduling(VL);
1099 newTreeEntry(VL, false);
1104 newTreeEntry(VL, true);
1105 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1107 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1109 // Prepare the operand vector.
1110 for (unsigned j = 0; j < VL.size(); ++j)
1111 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1112 PH->getIncomingBlock(i)));
1114 buildTree_rec(Operands, Depth + 1);
1118 case Instruction::ExtractElement: {
1119 bool Reuse = CanReuseExtract(VL);
1121 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1123 BS.cancelScheduling(VL);
1125 newTreeEntry(VL, Reuse);
1128 case Instruction::Load: {
1129 // Check if the loads are consecutive or of we need to swizzle them.
1130 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1131 LoadInst *L = cast<LoadInst>(VL[i]);
1132 if (!L->isSimple()) {
1133 BS.cancelScheduling(VL);
1134 newTreeEntry(VL, false);
1135 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1138 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1139 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1140 ++NumLoadsWantToChangeOrder;
1142 BS.cancelScheduling(VL);
1143 newTreeEntry(VL, false);
1144 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1148 ++NumLoadsWantToKeepOrder;
1149 newTreeEntry(VL, true);
1150 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1153 case Instruction::ZExt:
1154 case Instruction::SExt:
1155 case Instruction::FPToUI:
1156 case Instruction::FPToSI:
1157 case Instruction::FPExt:
1158 case Instruction::PtrToInt:
1159 case Instruction::IntToPtr:
1160 case Instruction::SIToFP:
1161 case Instruction::UIToFP:
1162 case Instruction::Trunc:
1163 case Instruction::FPTrunc:
1164 case Instruction::BitCast: {
1165 Type *SrcTy = VL0->getOperand(0)->getType();
1166 for (unsigned i = 0; i < VL.size(); ++i) {
1167 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1168 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1169 BS.cancelScheduling(VL);
1170 newTreeEntry(VL, false);
1171 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1175 newTreeEntry(VL, true);
1176 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1178 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1180 // Prepare the operand vector.
1181 for (unsigned j = 0; j < VL.size(); ++j)
1182 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1184 buildTree_rec(Operands, Depth+1);
1188 case Instruction::ICmp:
1189 case Instruction::FCmp: {
1190 // Check that all of the compares have the same predicate.
1191 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1192 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1193 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1194 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1195 if (Cmp->getPredicate() != P0 ||
1196 Cmp->getOperand(0)->getType() != ComparedTy) {
1197 BS.cancelScheduling(VL);
1198 newTreeEntry(VL, false);
1199 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1204 newTreeEntry(VL, true);
1205 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1207 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1209 // Prepare the operand vector.
1210 for (unsigned j = 0; j < VL.size(); ++j)
1211 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1213 buildTree_rec(Operands, Depth+1);
1217 case Instruction::Select:
1218 case Instruction::Add:
1219 case Instruction::FAdd:
1220 case Instruction::Sub:
1221 case Instruction::FSub:
1222 case Instruction::Mul:
1223 case Instruction::FMul:
1224 case Instruction::UDiv:
1225 case Instruction::SDiv:
1226 case Instruction::FDiv:
1227 case Instruction::URem:
1228 case Instruction::SRem:
1229 case Instruction::FRem:
1230 case Instruction::Shl:
1231 case Instruction::LShr:
1232 case Instruction::AShr:
1233 case Instruction::And:
1234 case Instruction::Or:
1235 case Instruction::Xor: {
1236 newTreeEntry(VL, true);
1237 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1239 // Sort operands of the instructions so that each side is more likely to
1240 // have the same opcode.
1241 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1242 ValueList Left, Right;
1243 reorderInputsAccordingToOpcode(VL, Left, Right);
1244 reorderIfConsecutiveLoads (Left, Right);
1245 buildTree_rec(Left, Depth + 1);
1246 buildTree_rec(Right, Depth + 1);
1250 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1252 // Prepare the operand vector.
1253 for (unsigned j = 0; j < VL.size(); ++j)
1254 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1256 buildTree_rec(Operands, Depth+1);
1260 case Instruction::GetElementPtr: {
1261 // We don't combine GEPs with complicated (nested) indexing.
1262 for (unsigned j = 0; j < VL.size(); ++j) {
1263 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1264 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1265 BS.cancelScheduling(VL);
1266 newTreeEntry(VL, false);
1271 // We can't combine several GEPs into one vector if they operate on
1273 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1274 for (unsigned j = 0; j < VL.size(); ++j) {
1275 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1277 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1278 BS.cancelScheduling(VL);
1279 newTreeEntry(VL, false);
1284 // We don't combine GEPs with non-constant indexes.
1285 for (unsigned j = 0; j < VL.size(); ++j) {
1286 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1287 if (!isa<ConstantInt>(Op)) {
1289 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1290 BS.cancelScheduling(VL);
1291 newTreeEntry(VL, false);
1296 newTreeEntry(VL, true);
1297 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1298 for (unsigned i = 0, e = 2; i < e; ++i) {
1300 // Prepare the operand vector.
1301 for (unsigned j = 0; j < VL.size(); ++j)
1302 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1304 buildTree_rec(Operands, Depth + 1);
1308 case Instruction::Store: {
1309 // Check if the stores are consecutive or of we need to swizzle them.
1310 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1311 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1312 BS.cancelScheduling(VL);
1313 newTreeEntry(VL, false);
1314 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1318 newTreeEntry(VL, true);
1319 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1322 for (unsigned j = 0; j < VL.size(); ++j)
1323 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1325 buildTree_rec(Operands, Depth + 1);
1328 case Instruction::Call: {
1329 // Check if the calls are all to the same vectorizable intrinsic.
1330 CallInst *CI = cast<CallInst>(VL[0]);
1331 // Check if this is an Intrinsic call or something that can be
1332 // represented by an intrinsic call
1333 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1334 if (!isTriviallyVectorizable(ID)) {
1335 BS.cancelScheduling(VL);
1336 newTreeEntry(VL, false);
1337 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1340 Function *Int = CI->getCalledFunction();
1341 Value *A1I = nullptr;
1342 if (hasVectorInstrinsicScalarOpd(ID, 1))
1343 A1I = CI->getArgOperand(1);
1344 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1345 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1346 if (!CI2 || CI2->getCalledFunction() != Int ||
1347 getIntrinsicIDForCall(CI2, TLI) != ID) {
1348 BS.cancelScheduling(VL);
1349 newTreeEntry(VL, false);
1350 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1354 // ctlz,cttz and powi are special intrinsics whose second argument
1355 // should be same in order for them to be vectorized.
1356 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1357 Value *A1J = CI2->getArgOperand(1);
1359 BS.cancelScheduling(VL);
1360 newTreeEntry(VL, false);
1361 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1362 << " argument "<< A1I<<"!=" << A1J
1369 newTreeEntry(VL, true);
1370 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1372 // Prepare the operand vector.
1373 for (unsigned j = 0; j < VL.size(); ++j) {
1374 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1375 Operands.push_back(CI2->getArgOperand(i));
1377 buildTree_rec(Operands, Depth + 1);
1381 case Instruction::ShuffleVector: {
1382 // If this is not an alternate sequence of opcode like add-sub
1383 // then do not vectorize this instruction.
1384 if (!isAltShuffle) {
1385 BS.cancelScheduling(VL);
1386 newTreeEntry(VL, false);
1387 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1390 newTreeEntry(VL, true);
1391 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1392 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1394 // Prepare the operand vector.
1395 for (unsigned j = 0; j < VL.size(); ++j)
1396 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1398 buildTree_rec(Operands, Depth + 1);
1403 BS.cancelScheduling(VL);
1404 newTreeEntry(VL, false);
1405 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1410 int BoUpSLP::getEntryCost(TreeEntry *E) {
1411 ArrayRef<Value*> VL = E->Scalars;
1413 Type *ScalarTy = VL[0]->getType();
1414 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1415 ScalarTy = SI->getValueOperand()->getType();
1416 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1418 if (E->NeedToGather) {
1419 if (allConstant(VL))
1422 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1424 return getGatherCost(E->Scalars);
1426 unsigned Opcode = getSameOpcode(VL);
1427 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1428 Instruction *VL0 = cast<Instruction>(VL[0]);
1430 case Instruction::PHI: {
1433 case Instruction::ExtractElement: {
1434 if (CanReuseExtract(VL)) {
1436 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1437 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1439 // Take credit for instruction that will become dead.
1441 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1445 return getGatherCost(VecTy);
1447 case Instruction::ZExt:
1448 case Instruction::SExt:
1449 case Instruction::FPToUI:
1450 case Instruction::FPToSI:
1451 case Instruction::FPExt:
1452 case Instruction::PtrToInt:
1453 case Instruction::IntToPtr:
1454 case Instruction::SIToFP:
1455 case Instruction::UIToFP:
1456 case Instruction::Trunc:
1457 case Instruction::FPTrunc:
1458 case Instruction::BitCast: {
1459 Type *SrcTy = VL0->getOperand(0)->getType();
1461 // Calculate the cost of this instruction.
1462 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1463 VL0->getType(), SrcTy);
1465 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1466 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1467 return VecCost - ScalarCost;
1469 case Instruction::FCmp:
1470 case Instruction::ICmp:
1471 case Instruction::Select:
1472 case Instruction::Add:
1473 case Instruction::FAdd:
1474 case Instruction::Sub:
1475 case Instruction::FSub:
1476 case Instruction::Mul:
1477 case Instruction::FMul:
1478 case Instruction::UDiv:
1479 case Instruction::SDiv:
1480 case Instruction::FDiv:
1481 case Instruction::URem:
1482 case Instruction::SRem:
1483 case Instruction::FRem:
1484 case Instruction::Shl:
1485 case Instruction::LShr:
1486 case Instruction::AShr:
1487 case Instruction::And:
1488 case Instruction::Or:
1489 case Instruction::Xor: {
1490 // Calculate the cost of this instruction.
1493 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1494 Opcode == Instruction::Select) {
1495 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1496 ScalarCost = VecTy->getNumElements() *
1497 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1498 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1500 // Certain instructions can be cheaper to vectorize if they have a
1501 // constant second vector operand.
1502 TargetTransformInfo::OperandValueKind Op1VK =
1503 TargetTransformInfo::OK_AnyValue;
1504 TargetTransformInfo::OperandValueKind Op2VK =
1505 TargetTransformInfo::OK_UniformConstantValue;
1506 TargetTransformInfo::OperandValueProperties Op1VP =
1507 TargetTransformInfo::OP_None;
1508 TargetTransformInfo::OperandValueProperties Op2VP =
1509 TargetTransformInfo::OP_None;
1511 // If all operands are exactly the same ConstantInt then set the
1512 // operand kind to OK_UniformConstantValue.
1513 // If instead not all operands are constants, then set the operand kind
1514 // to OK_AnyValue. If all operands are constants but not the same,
1515 // then set the operand kind to OK_NonUniformConstantValue.
1516 ConstantInt *CInt = nullptr;
1517 for (unsigned i = 0; i < VL.size(); ++i) {
1518 const Instruction *I = cast<Instruction>(VL[i]);
1519 if (!isa<ConstantInt>(I->getOperand(1))) {
1520 Op2VK = TargetTransformInfo::OK_AnyValue;
1524 CInt = cast<ConstantInt>(I->getOperand(1));
1527 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1528 CInt != cast<ConstantInt>(I->getOperand(1)))
1529 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1531 // FIXME: Currently cost of model modification for division by
1532 // power of 2 is handled only for X86. Add support for other targets.
1533 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1534 CInt->getValue().isPowerOf2())
1535 Op2VP = TargetTransformInfo::OP_PowerOf2;
1537 ScalarCost = VecTy->getNumElements() *
1538 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1540 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1543 return VecCost - ScalarCost;
1545 case Instruction::GetElementPtr: {
1546 TargetTransformInfo::OperandValueKind Op1VK =
1547 TargetTransformInfo::OK_AnyValue;
1548 TargetTransformInfo::OperandValueKind Op2VK =
1549 TargetTransformInfo::OK_UniformConstantValue;
1552 VecTy->getNumElements() *
1553 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1555 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1557 return VecCost - ScalarCost;
1559 case Instruction::Load: {
1560 // Cost of wide load - cost of scalar loads.
1561 int ScalarLdCost = VecTy->getNumElements() *
1562 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1563 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1564 return VecLdCost - ScalarLdCost;
1566 case Instruction::Store: {
1567 // We know that we can merge the stores. Calculate the cost.
1568 int ScalarStCost = VecTy->getNumElements() *
1569 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1570 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1571 return VecStCost - ScalarStCost;
1573 case Instruction::Call: {
1574 CallInst *CI = cast<CallInst>(VL0);
1575 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1577 // Calculate the cost of the scalar and vector calls.
1578 SmallVector<Type*, 4> ScalarTys, VecTys;
1579 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1580 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1581 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1582 VecTy->getNumElements()));
1585 int ScalarCallCost = VecTy->getNumElements() *
1586 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1588 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1590 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1591 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1592 << " for " << *CI << "\n");
1594 return VecCallCost - ScalarCallCost;
1596 case Instruction::ShuffleVector: {
1597 TargetTransformInfo::OperandValueKind Op1VK =
1598 TargetTransformInfo::OK_AnyValue;
1599 TargetTransformInfo::OperandValueKind Op2VK =
1600 TargetTransformInfo::OK_AnyValue;
1603 for (unsigned i = 0; i < VL.size(); ++i) {
1604 Instruction *I = cast<Instruction>(VL[i]);
1608 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1610 // VecCost is equal to sum of the cost of creating 2 vectors
1611 // and the cost of creating shuffle.
1612 Instruction *I0 = cast<Instruction>(VL[0]);
1614 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1615 Instruction *I1 = cast<Instruction>(VL[1]);
1617 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1619 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1620 return VecCost - ScalarCost;
1623 llvm_unreachable("Unknown instruction");
1627 bool BoUpSLP::isFullyVectorizableTinyTree() {
1628 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1629 VectorizableTree.size() << " is fully vectorizable .\n");
1631 // We only handle trees of height 2.
1632 if (VectorizableTree.size() != 2)
1635 // Handle splat stores.
1636 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1639 // Gathering cost would be too much for tiny trees.
1640 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1646 int BoUpSLP::getSpillCost() {
1647 // Walk from the bottom of the tree to the top, tracking which values are
1648 // live. When we see a call instruction that is not part of our tree,
1649 // query TTI to see if there is a cost to keeping values live over it
1650 // (for example, if spills and fills are required).
1651 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1654 SmallPtrSet<Instruction*, 4> LiveValues;
1655 Instruction *PrevInst = nullptr;
1657 for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1658 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1668 dbgs() << "SLP: #LV: " << LiveValues.size();
1669 for (auto *X : LiveValues)
1670 dbgs() << " " << X->getName();
1671 dbgs() << ", Looking at ";
1675 // Update LiveValues.
1676 LiveValues.erase(PrevInst);
1677 for (auto &J : PrevInst->operands()) {
1678 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1679 LiveValues.insert(cast<Instruction>(&*J));
1682 // Now find the sequence of instructions between PrevInst and Inst.
1683 BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1685 while (InstIt != PrevInstIt) {
1686 if (PrevInstIt == PrevInst->getParent()->rend()) {
1687 PrevInstIt = Inst->getParent()->rbegin();
1691 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1692 SmallVector<Type*, 4> V;
1693 for (auto *II : LiveValues)
1694 V.push_back(VectorType::get(II->getType(), BundleWidth));
1695 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1704 DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1708 int BoUpSLP::getTreeCost() {
1710 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1711 VectorizableTree.size() << ".\n");
1713 // We only vectorize tiny trees if it is fully vectorizable.
1714 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1715 if (!VectorizableTree.size()) {
1716 assert(!ExternalUses.size() && "We should not have any external users");
1721 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1723 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1724 int C = getEntryCost(&VectorizableTree[i]);
1725 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1726 << *VectorizableTree[i].Scalars[0] << " .\n");
1730 SmallSet<Value *, 16> ExtractCostCalculated;
1731 int ExtractCost = 0;
1732 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1734 // We only add extract cost once for the same scalar.
1735 if (!ExtractCostCalculated.insert(I->Scalar).second)
1738 // Uses by ephemeral values are free (because the ephemeral value will be
1739 // removed prior to code generation, and so the extraction will be
1740 // removed as well).
1741 if (EphValues.count(I->User))
1744 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1745 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1749 Cost += getSpillCost();
1751 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1752 return Cost + ExtractCost;
1755 int BoUpSLP::getGatherCost(Type *Ty) {
1757 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1758 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1762 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1763 // Find the type of the operands in VL.
1764 Type *ScalarTy = VL[0]->getType();
1765 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1766 ScalarTy = SI->getValueOperand()->getType();
1767 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1768 // Find the cost of inserting/extracting values from the vector.
1769 return getGatherCost(VecTy);
1772 Value *BoUpSLP::getPointerOperand(Value *I) {
1773 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1774 return LI->getPointerOperand();
1775 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1776 return SI->getPointerOperand();
1780 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1781 if (LoadInst *L = dyn_cast<LoadInst>(I))
1782 return L->getPointerAddressSpace();
1783 if (StoreInst *S = dyn_cast<StoreInst>(I))
1784 return S->getPointerAddressSpace();
1788 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1789 Value *PtrA = getPointerOperand(A);
1790 Value *PtrB = getPointerOperand(B);
1791 unsigned ASA = getAddressSpaceOperand(A);
1792 unsigned ASB = getAddressSpaceOperand(B);
1794 // Check that the address spaces match and that the pointers are valid.
1795 if (!PtrA || !PtrB || (ASA != ASB))
1798 // Make sure that A and B are different pointers of the same type.
1799 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1802 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1803 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1804 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1806 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1807 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1808 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1810 APInt OffsetDelta = OffsetB - OffsetA;
1812 // Check if they are based on the same pointer. That makes the offsets
1815 return OffsetDelta == Size;
1817 // Compute the necessary base pointer delta to have the necessary final delta
1818 // equal to the size.
1819 APInt BaseDelta = Size - OffsetDelta;
1821 // Otherwise compute the distance with SCEV between the base pointers.
1822 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1823 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1824 const SCEV *C = SE->getConstant(BaseDelta);
1825 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1826 return X == PtrSCEVB;
1829 void BoUpSLP::reorderIfConsecutiveLoads(SmallVectorImpl<Value *> &Left,
1830 SmallVectorImpl<Value *> &Right) {
1831 for (unsigned i = 0, e = Left.size(); i < e - 1; ++i) {
1832 if (!isa<LoadInst>(Left[i]) || !isa<LoadInst>(Right[i]))
1834 if (!(isConsecutiveAccess(Left[i], Right[i]) &&
1835 isConsecutiveAccess(Right[i], Left[i + 1])))
1838 std::swap(Left[i + 1], Right[i]);
1842 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1843 Instruction *VL0 = cast<Instruction>(VL[0]);
1844 BasicBlock::iterator NextInst = VL0;
1846 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1847 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1850 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1851 Value *Vec = UndefValue::get(Ty);
1852 // Generate the 'InsertElement' instruction.
1853 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1854 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1855 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1856 GatherSeq.insert(Insrt);
1857 CSEBlocks.insert(Insrt->getParent());
1859 // Add to our 'need-to-extract' list.
1860 if (ScalarToTreeEntry.count(VL[i])) {
1861 int Idx = ScalarToTreeEntry[VL[i]];
1862 TreeEntry *E = &VectorizableTree[Idx];
1863 // Find which lane we need to extract.
1865 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1866 // Is this the lane of the scalar that we are looking for ?
1867 if (E->Scalars[Lane] == VL[i]) {
1872 assert(FoundLane >= 0 && "Could not find the correct lane");
1873 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1881 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1882 SmallDenseMap<Value*, int>::const_iterator Entry
1883 = ScalarToTreeEntry.find(VL[0]);
1884 if (Entry != ScalarToTreeEntry.end()) {
1885 int Idx = Entry->second;
1886 const TreeEntry *En = &VectorizableTree[Idx];
1887 if (En->isSame(VL) && En->VectorizedValue)
1888 return En->VectorizedValue;
1893 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1894 if (ScalarToTreeEntry.count(VL[0])) {
1895 int Idx = ScalarToTreeEntry[VL[0]];
1896 TreeEntry *E = &VectorizableTree[Idx];
1898 return vectorizeTree(E);
1901 Type *ScalarTy = VL[0]->getType();
1902 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1903 ScalarTy = SI->getValueOperand()->getType();
1904 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1906 return Gather(VL, VecTy);
1909 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1910 IRBuilder<>::InsertPointGuard Guard(Builder);
1912 if (E->VectorizedValue) {
1913 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1914 return E->VectorizedValue;
1917 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1918 Type *ScalarTy = VL0->getType();
1919 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1920 ScalarTy = SI->getValueOperand()->getType();
1921 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1923 if (E->NeedToGather) {
1924 setInsertPointAfterBundle(E->Scalars);
1925 return Gather(E->Scalars, VecTy);
1928 unsigned Opcode = getSameOpcode(E->Scalars);
1931 case Instruction::PHI: {
1932 PHINode *PH = dyn_cast<PHINode>(VL0);
1933 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1934 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1935 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1936 E->VectorizedValue = NewPhi;
1938 // PHINodes may have multiple entries from the same block. We want to
1939 // visit every block once.
1940 SmallSet<BasicBlock*, 4> VisitedBBs;
1942 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1944 BasicBlock *IBB = PH->getIncomingBlock(i);
1946 if (!VisitedBBs.insert(IBB).second) {
1947 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1951 // Prepare the operand vector.
1952 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1953 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1954 getIncomingValueForBlock(IBB));
1956 Builder.SetInsertPoint(IBB->getTerminator());
1957 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1958 Value *Vec = vectorizeTree(Operands);
1959 NewPhi->addIncoming(Vec, IBB);
1962 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1963 "Invalid number of incoming values");
1967 case Instruction::ExtractElement: {
1968 if (CanReuseExtract(E->Scalars)) {
1969 Value *V = VL0->getOperand(0);
1970 E->VectorizedValue = V;
1973 return Gather(E->Scalars, VecTy);
1975 case Instruction::ZExt:
1976 case Instruction::SExt:
1977 case Instruction::FPToUI:
1978 case Instruction::FPToSI:
1979 case Instruction::FPExt:
1980 case Instruction::PtrToInt:
1981 case Instruction::IntToPtr:
1982 case Instruction::SIToFP:
1983 case Instruction::UIToFP:
1984 case Instruction::Trunc:
1985 case Instruction::FPTrunc:
1986 case Instruction::BitCast: {
1988 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1989 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1991 setInsertPointAfterBundle(E->Scalars);
1993 Value *InVec = vectorizeTree(INVL);
1995 if (Value *V = alreadyVectorized(E->Scalars))
1998 CastInst *CI = dyn_cast<CastInst>(VL0);
1999 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2000 E->VectorizedValue = V;
2001 ++NumVectorInstructions;
2004 case Instruction::FCmp:
2005 case Instruction::ICmp: {
2006 ValueList LHSV, RHSV;
2007 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2008 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2009 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2012 setInsertPointAfterBundle(E->Scalars);
2014 Value *L = vectorizeTree(LHSV);
2015 Value *R = vectorizeTree(RHSV);
2017 if (Value *V = alreadyVectorized(E->Scalars))
2020 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
2022 if (Opcode == Instruction::FCmp)
2023 V = Builder.CreateFCmp(P0, L, R);
2025 V = Builder.CreateICmp(P0, L, R);
2027 E->VectorizedValue = V;
2028 ++NumVectorInstructions;
2031 case Instruction::Select: {
2032 ValueList TrueVec, FalseVec, CondVec;
2033 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2034 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2035 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2036 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
2039 setInsertPointAfterBundle(E->Scalars);
2041 Value *Cond = vectorizeTree(CondVec);
2042 Value *True = vectorizeTree(TrueVec);
2043 Value *False = vectorizeTree(FalseVec);
2045 if (Value *V = alreadyVectorized(E->Scalars))
2048 Value *V = Builder.CreateSelect(Cond, True, False);
2049 E->VectorizedValue = V;
2050 ++NumVectorInstructions;
2053 case Instruction::Add:
2054 case Instruction::FAdd:
2055 case Instruction::Sub:
2056 case Instruction::FSub:
2057 case Instruction::Mul:
2058 case Instruction::FMul:
2059 case Instruction::UDiv:
2060 case Instruction::SDiv:
2061 case Instruction::FDiv:
2062 case Instruction::URem:
2063 case Instruction::SRem:
2064 case Instruction::FRem:
2065 case Instruction::Shl:
2066 case Instruction::LShr:
2067 case Instruction::AShr:
2068 case Instruction::And:
2069 case Instruction::Or:
2070 case Instruction::Xor: {
2071 ValueList LHSVL, RHSVL;
2072 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
2073 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2074 reorderIfConsecutiveLoads(LHSVL, RHSVL);
2076 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2077 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2078 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2081 setInsertPointAfterBundle(E->Scalars);
2083 Value *LHS = vectorizeTree(LHSVL);
2084 Value *RHS = vectorizeTree(RHSVL);
2086 if (LHS == RHS && isa<Instruction>(LHS)) {
2087 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2090 if (Value *V = alreadyVectorized(E->Scalars))
2093 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2094 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2095 E->VectorizedValue = V;
2096 propagateIRFlags(E->VectorizedValue, E->Scalars);
2097 ++NumVectorInstructions;
2099 if (Instruction *I = dyn_cast<Instruction>(V))
2100 return propagateMetadata(I, E->Scalars);
2104 case Instruction::Load: {
2105 // Loads are inserted at the head of the tree because we don't want to
2106 // sink them all the way down past store instructions.
2107 setInsertPointAfterBundle(E->Scalars);
2109 LoadInst *LI = cast<LoadInst>(VL0);
2110 Type *ScalarLoadTy = LI->getType();
2111 unsigned AS = LI->getPointerAddressSpace();
2113 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2114 VecTy->getPointerTo(AS));
2116 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2117 // ExternalUses list to make sure that an extract will be generated in the
2119 if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2120 ExternalUses.push_back(
2121 ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2123 unsigned Alignment = LI->getAlignment();
2124 LI = Builder.CreateLoad(VecPtr);
2126 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2127 LI->setAlignment(Alignment);
2128 E->VectorizedValue = LI;
2129 ++NumVectorInstructions;
2130 return propagateMetadata(LI, E->Scalars);
2132 case Instruction::Store: {
2133 StoreInst *SI = cast<StoreInst>(VL0);
2134 unsigned Alignment = SI->getAlignment();
2135 unsigned AS = SI->getPointerAddressSpace();
2138 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2139 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2141 setInsertPointAfterBundle(E->Scalars);
2143 Value *VecValue = vectorizeTree(ValueOp);
2144 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2145 VecTy->getPointerTo(AS));
2146 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2148 // The pointer operand uses an in-tree scalar so we add the new BitCast to
2149 // ExternalUses list to make sure that an extract will be generated in the
2151 if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2152 ExternalUses.push_back(
2153 ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2156 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2157 S->setAlignment(Alignment);
2158 E->VectorizedValue = S;
2159 ++NumVectorInstructions;
2160 return propagateMetadata(S, E->Scalars);
2162 case Instruction::GetElementPtr: {
2163 setInsertPointAfterBundle(E->Scalars);
2166 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2167 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2169 Value *Op0 = vectorizeTree(Op0VL);
2171 std::vector<Value *> OpVecs;
2172 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2175 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2176 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2178 Value *OpVec = vectorizeTree(OpVL);
2179 OpVecs.push_back(OpVec);
2182 Value *V = Builder.CreateGEP(Op0, OpVecs);
2183 E->VectorizedValue = V;
2184 ++NumVectorInstructions;
2186 if (Instruction *I = dyn_cast<Instruction>(V))
2187 return propagateMetadata(I, E->Scalars);
2191 case Instruction::Call: {
2192 CallInst *CI = cast<CallInst>(VL0);
2193 setInsertPointAfterBundle(E->Scalars);
2195 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2196 Value *ScalarArg = nullptr;
2197 if (CI && (FI = CI->getCalledFunction())) {
2198 IID = (Intrinsic::ID) FI->getIntrinsicID();
2200 std::vector<Value *> OpVecs;
2201 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2203 // ctlz,cttz and powi are special intrinsics whose second argument is
2204 // a scalar. This argument should not be vectorized.
2205 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2206 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2207 ScalarArg = CEI->getArgOperand(j);
2208 OpVecs.push_back(CEI->getArgOperand(j));
2211 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2212 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2213 OpVL.push_back(CEI->getArgOperand(j));
2216 Value *OpVec = vectorizeTree(OpVL);
2217 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2218 OpVecs.push_back(OpVec);
2221 Module *M = F->getParent();
2222 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2223 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2224 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2225 Value *V = Builder.CreateCall(CF, OpVecs);
2227 // The scalar argument uses an in-tree scalar so we add the new vectorized
2228 // call to ExternalUses list to make sure that an extract will be
2229 // generated in the future.
2230 if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2231 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2233 E->VectorizedValue = V;
2234 ++NumVectorInstructions;
2237 case Instruction::ShuffleVector: {
2238 ValueList LHSVL, RHSVL;
2239 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2240 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2241 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2243 setInsertPointAfterBundle(E->Scalars);
2245 Value *LHS = vectorizeTree(LHSVL);
2246 Value *RHS = vectorizeTree(RHSVL);
2248 if (Value *V = alreadyVectorized(E->Scalars))
2251 // Create a vector of LHS op1 RHS
2252 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2253 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2255 // Create a vector of LHS op2 RHS
2256 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2257 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2258 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2260 // Create shuffle to take alternate operations from the vector.
2261 // Also, gather up odd and even scalar ops to propagate IR flags to
2262 // each vector operation.
2263 ValueList OddScalars, EvenScalars;
2264 unsigned e = E->Scalars.size();
2265 SmallVector<Constant *, 8> Mask(e);
2266 for (unsigned i = 0; i < e; ++i) {
2268 Mask[i] = Builder.getInt32(e + i);
2269 OddScalars.push_back(E->Scalars[i]);
2271 Mask[i] = Builder.getInt32(i);
2272 EvenScalars.push_back(E->Scalars[i]);
2276 Value *ShuffleMask = ConstantVector::get(Mask);
2277 propagateIRFlags(V0, EvenScalars);
2278 propagateIRFlags(V1, OddScalars);
2280 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2281 E->VectorizedValue = V;
2282 ++NumVectorInstructions;
2283 if (Instruction *I = dyn_cast<Instruction>(V))
2284 return propagateMetadata(I, E->Scalars);
2289 llvm_unreachable("unknown inst");
2294 Value *BoUpSLP::vectorizeTree() {
2296 // All blocks must be scheduled before any instructions are inserted.
2297 for (auto &BSIter : BlocksSchedules) {
2298 scheduleBlock(BSIter.second.get());
2301 Builder.SetInsertPoint(F->getEntryBlock().begin());
2302 vectorizeTree(&VectorizableTree[0]);
2304 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2306 // Extract all of the elements with the external uses.
2307 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2309 Value *Scalar = it->Scalar;
2310 llvm::User *User = it->User;
2312 // Skip users that we already RAUW. This happens when one instruction
2313 // has multiple uses of the same value.
2314 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2317 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2319 int Idx = ScalarToTreeEntry[Scalar];
2320 TreeEntry *E = &VectorizableTree[Idx];
2321 assert(!E->NeedToGather && "Extracting from a gather list");
2323 Value *Vec = E->VectorizedValue;
2324 assert(Vec && "Can't find vectorizable value");
2326 Value *Lane = Builder.getInt32(it->Lane);
2327 // Generate extracts for out-of-tree users.
2328 // Find the insertion point for the extractelement lane.
2329 if (isa<Instruction>(Vec)){
2330 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2331 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2332 if (PH->getIncomingValue(i) == Scalar) {
2333 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2334 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2335 CSEBlocks.insert(PH->getIncomingBlock(i));
2336 PH->setOperand(i, Ex);
2340 Builder.SetInsertPoint(cast<Instruction>(User));
2341 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2342 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2343 User->replaceUsesOfWith(Scalar, Ex);
2346 Builder.SetInsertPoint(F->getEntryBlock().begin());
2347 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2348 CSEBlocks.insert(&F->getEntryBlock());
2349 User->replaceUsesOfWith(Scalar, Ex);
2352 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2355 // For each vectorized value:
2356 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2357 TreeEntry *Entry = &VectorizableTree[EIdx];
2360 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2361 Value *Scalar = Entry->Scalars[Lane];
2362 // No need to handle users of gathered values.
2363 if (Entry->NeedToGather)
2366 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2368 Type *Ty = Scalar->getType();
2369 if (!Ty->isVoidTy()) {
2371 for (User *U : Scalar->users()) {
2372 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2374 assert((ScalarToTreeEntry.count(U) ||
2375 // It is legal to replace users in the ignorelist by undef.
2376 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2377 UserIgnoreList.end())) &&
2378 "Replacing out-of-tree value with undef");
2381 Value *Undef = UndefValue::get(Ty);
2382 Scalar->replaceAllUsesWith(Undef);
2384 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2385 cast<Instruction>(Scalar)->eraseFromParent();
2389 Builder.ClearInsertionPoint();
2391 return VectorizableTree[0].VectorizedValue;
2394 void BoUpSLP::optimizeGatherSequence() {
2395 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2396 << " gather sequences instructions.\n");
2397 // LICM InsertElementInst sequences.
2398 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2399 e = GatherSeq.end(); it != e; ++it) {
2400 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2405 // Check if this block is inside a loop.
2406 Loop *L = LI->getLoopFor(Insert->getParent());
2410 // Check if it has a preheader.
2411 BasicBlock *PreHeader = L->getLoopPreheader();
2415 // If the vector or the element that we insert into it are
2416 // instructions that are defined in this basic block then we can't
2417 // hoist this instruction.
2418 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2419 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2420 if (CurrVec && L->contains(CurrVec))
2422 if (NewElem && L->contains(NewElem))
2425 // We can hoist this instruction. Move it to the pre-header.
2426 Insert->moveBefore(PreHeader->getTerminator());
2429 // Make a list of all reachable blocks in our CSE queue.
2430 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2431 CSEWorkList.reserve(CSEBlocks.size());
2432 for (BasicBlock *BB : CSEBlocks)
2433 if (DomTreeNode *N = DT->getNode(BB)) {
2434 assert(DT->isReachableFromEntry(N));
2435 CSEWorkList.push_back(N);
2438 // Sort blocks by domination. This ensures we visit a block after all blocks
2439 // dominating it are visited.
2440 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2441 [this](const DomTreeNode *A, const DomTreeNode *B) {
2442 return DT->properlyDominates(A, B);
2445 // Perform O(N^2) search over the gather sequences and merge identical
2446 // instructions. TODO: We can further optimize this scan if we split the
2447 // instructions into different buckets based on the insert lane.
2448 SmallVector<Instruction *, 16> Visited;
2449 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2450 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2451 "Worklist not sorted properly!");
2452 BasicBlock *BB = (*I)->getBlock();
2453 // For all instructions in blocks containing gather sequences:
2454 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2455 Instruction *In = it++;
2456 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2459 // Check if we can replace this instruction with any of the
2460 // visited instructions.
2461 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2464 if (In->isIdenticalTo(*v) &&
2465 DT->dominates((*v)->getParent(), In->getParent())) {
2466 In->replaceAllUsesWith(*v);
2467 In->eraseFromParent();
2473 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2474 Visited.push_back(In);
2482 // Groups the instructions to a bundle (which is then a single scheduling entity)
2483 // and schedules instructions until the bundle gets ready.
2484 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2485 AliasAnalysis *AA) {
2486 if (isa<PHINode>(VL[0]))
2489 // Initialize the instruction bundle.
2490 Instruction *OldScheduleEnd = ScheduleEnd;
2491 ScheduleData *PrevInBundle = nullptr;
2492 ScheduleData *Bundle = nullptr;
2493 bool ReSchedule = false;
2494 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2495 for (Value *V : VL) {
2496 extendSchedulingRegion(V);
2497 ScheduleData *BundleMember = getScheduleData(V);
2498 assert(BundleMember &&
2499 "no ScheduleData for bundle member (maybe not in same basic block)");
2500 if (BundleMember->IsScheduled) {
2501 // A bundle member was scheduled as single instruction before and now
2502 // needs to be scheduled as part of the bundle. We just get rid of the
2503 // existing schedule.
2504 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2505 << " was already scheduled\n");
2508 assert(BundleMember->isSchedulingEntity() &&
2509 "bundle member already part of other bundle");
2511 PrevInBundle->NextInBundle = BundleMember;
2513 Bundle = BundleMember;
2515 BundleMember->UnscheduledDepsInBundle = 0;
2516 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2518 // Group the instructions to a bundle.
2519 BundleMember->FirstInBundle = Bundle;
2520 PrevInBundle = BundleMember;
2522 if (ScheduleEnd != OldScheduleEnd) {
2523 // The scheduling region got new instructions at the lower end (or it is a
2524 // new region for the first bundle). This makes it necessary to
2525 // recalculate all dependencies.
2526 // It is seldom that this needs to be done a second time after adding the
2527 // initial bundle to the region.
2528 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2529 ScheduleData *SD = getScheduleData(I);
2530 SD->clearDependencies();
2536 initialFillReadyList(ReadyInsts);
2539 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2540 << BB->getName() << "\n");
2542 calculateDependencies(Bundle, true, AA);
2544 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2545 // means that there are no cyclic dependencies and we can schedule it.
2546 // Note that's important that we don't "schedule" the bundle yet (see
2547 // cancelScheduling).
2548 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2550 ScheduleData *pickedSD = ReadyInsts.back();
2551 ReadyInsts.pop_back();
2553 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2554 schedule(pickedSD, ReadyInsts);
2557 return Bundle->isReady();
2560 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2561 if (isa<PHINode>(VL[0]))
2564 ScheduleData *Bundle = getScheduleData(VL[0]);
2565 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2566 assert(!Bundle->IsScheduled &&
2567 "Can't cancel bundle which is already scheduled");
2568 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2569 "tried to unbundle something which is not a bundle");
2571 // Un-bundle: make single instructions out of the bundle.
2572 ScheduleData *BundleMember = Bundle;
2573 while (BundleMember) {
2574 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2575 BundleMember->FirstInBundle = BundleMember;
2576 ScheduleData *Next = BundleMember->NextInBundle;
2577 BundleMember->NextInBundle = nullptr;
2578 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2579 if (BundleMember->UnscheduledDepsInBundle == 0) {
2580 ReadyInsts.insert(BundleMember);
2582 BundleMember = Next;
2586 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2587 if (getScheduleData(V))
2589 Instruction *I = dyn_cast<Instruction>(V);
2590 assert(I && "bundle member must be an instruction");
2591 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2592 if (!ScheduleStart) {
2593 // It's the first instruction in the new region.
2594 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2596 ScheduleEnd = I->getNextNode();
2597 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2598 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2601 // Search up and down at the same time, because we don't know if the new
2602 // instruction is above or below the existing scheduling region.
2603 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2604 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2605 BasicBlock::iterator DownIter(ScheduleEnd);
2606 BasicBlock::iterator LowerEnd = BB->end();
2608 if (UpIter != UpperEnd) {
2609 if (&*UpIter == I) {
2610 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2612 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2617 if (DownIter != LowerEnd) {
2618 if (&*DownIter == I) {
2619 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2621 ScheduleEnd = I->getNextNode();
2622 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2623 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2628 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2629 "instruction not found in block");
2633 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2635 ScheduleData *PrevLoadStore,
2636 ScheduleData *NextLoadStore) {
2637 ScheduleData *CurrentLoadStore = PrevLoadStore;
2638 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2639 ScheduleData *SD = ScheduleDataMap[I];
2641 // Allocate a new ScheduleData for the instruction.
2642 if (ChunkPos >= ChunkSize) {
2643 ScheduleDataChunks.push_back(
2644 llvm::make_unique<ScheduleData[]>(ChunkSize));
2647 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2648 ScheduleDataMap[I] = SD;
2651 assert(!isInSchedulingRegion(SD) &&
2652 "new ScheduleData already in scheduling region");
2653 SD->init(SchedulingRegionID);
2655 if (I->mayReadOrWriteMemory()) {
2656 // Update the linked list of memory accessing instructions.
2657 if (CurrentLoadStore) {
2658 CurrentLoadStore->NextLoadStore = SD;
2660 FirstLoadStoreInRegion = SD;
2662 CurrentLoadStore = SD;
2665 if (NextLoadStore) {
2666 if (CurrentLoadStore)
2667 CurrentLoadStore->NextLoadStore = NextLoadStore;
2669 LastLoadStoreInRegion = CurrentLoadStore;
2673 /// \returns the AA location that is being access by the instruction.
2674 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
2675 if (StoreInst *SI = dyn_cast<StoreInst>(I))
2676 return AA->getLocation(SI);
2677 if (LoadInst *LI = dyn_cast<LoadInst>(I))
2678 return AA->getLocation(LI);
2679 return AliasAnalysis::Location();
2682 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2683 bool InsertInReadyList,
2684 AliasAnalysis *AA) {
2685 assert(SD->isSchedulingEntity());
2687 SmallVector<ScheduleData *, 10> WorkList;
2688 WorkList.push_back(SD);
2690 while (!WorkList.empty()) {
2691 ScheduleData *SD = WorkList.back();
2692 WorkList.pop_back();
2694 ScheduleData *BundleMember = SD;
2695 while (BundleMember) {
2696 assert(isInSchedulingRegion(BundleMember));
2697 if (!BundleMember->hasValidDependencies()) {
2699 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2700 BundleMember->Dependencies = 0;
2701 BundleMember->resetUnscheduledDeps();
2703 // Handle def-use chain dependencies.
2704 for (User *U : BundleMember->Inst->users()) {
2705 if (isa<Instruction>(U)) {
2706 ScheduleData *UseSD = getScheduleData(U);
2707 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2708 BundleMember->Dependencies++;
2709 ScheduleData *DestBundle = UseSD->FirstInBundle;
2710 if (!DestBundle->IsScheduled) {
2711 BundleMember->incrementUnscheduledDeps(1);
2713 if (!DestBundle->hasValidDependencies()) {
2714 WorkList.push_back(DestBundle);
2718 // I'm not sure if this can ever happen. But we need to be safe.
2719 // This lets the instruction/bundle never be scheduled and eventally
2720 // disable vectorization.
2721 BundleMember->Dependencies++;
2722 BundleMember->incrementUnscheduledDeps(1);
2726 // Handle the memory dependencies.
2727 ScheduleData *DepDest = BundleMember->NextLoadStore;
2729 AliasAnalysis::Location SrcLoc = getLocation(BundleMember->Inst, AA);
2730 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2733 assert(isInSchedulingRegion(DepDest));
2734 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2735 AliasAnalysis::Location DstLoc = getLocation(DepDest->Inst, AA);
2736 if (!SrcLoc.Ptr || !DstLoc.Ptr || AA->alias(SrcLoc, DstLoc)) {
2737 DepDest->MemoryDependencies.push_back(BundleMember);
2738 BundleMember->Dependencies++;
2739 ScheduleData *DestBundle = DepDest->FirstInBundle;
2740 if (!DestBundle->IsScheduled) {
2741 BundleMember->incrementUnscheduledDeps(1);
2743 if (!DestBundle->hasValidDependencies()) {
2744 WorkList.push_back(DestBundle);
2748 DepDest = DepDest->NextLoadStore;
2752 BundleMember = BundleMember->NextInBundle;
2754 if (InsertInReadyList && SD->isReady()) {
2755 ReadyInsts.push_back(SD);
2756 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2761 void BoUpSLP::BlockScheduling::resetSchedule() {
2762 assert(ScheduleStart &&
2763 "tried to reset schedule on block which has not been scheduled");
2764 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2765 ScheduleData *SD = getScheduleData(I);
2766 assert(isInSchedulingRegion(SD));
2767 SD->IsScheduled = false;
2768 SD->resetUnscheduledDeps();
2773 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2775 if (!BS->ScheduleStart)
2778 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2780 BS->resetSchedule();
2782 // For the real scheduling we use a more sophisticated ready-list: it is
2783 // sorted by the original instruction location. This lets the final schedule
2784 // be as close as possible to the original instruction order.
2785 struct ScheduleDataCompare {
2786 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2787 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2790 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2792 // Ensure that all depencency data is updated and fill the ready-list with
2793 // initial instructions.
2795 int NumToSchedule = 0;
2796 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2797 I = I->getNextNode()) {
2798 ScheduleData *SD = BS->getScheduleData(I);
2800 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2801 "scheduler and vectorizer have different opinion on what is a bundle");
2802 SD->FirstInBundle->SchedulingPriority = Idx++;
2803 if (SD->isSchedulingEntity()) {
2804 BS->calculateDependencies(SD, false, AA);
2808 BS->initialFillReadyList(ReadyInsts);
2810 Instruction *LastScheduledInst = BS->ScheduleEnd;
2812 // Do the "real" scheduling.
2813 while (!ReadyInsts.empty()) {
2814 ScheduleData *picked = *ReadyInsts.begin();
2815 ReadyInsts.erase(ReadyInsts.begin());
2817 // Move the scheduled instruction(s) to their dedicated places, if not
2819 ScheduleData *BundleMember = picked;
2820 while (BundleMember) {
2821 Instruction *pickedInst = BundleMember->Inst;
2822 if (LastScheduledInst->getNextNode() != pickedInst) {
2823 BS->BB->getInstList().remove(pickedInst);
2824 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2826 LastScheduledInst = pickedInst;
2827 BundleMember = BundleMember->NextInBundle;
2830 BS->schedule(picked, ReadyInsts);
2833 assert(NumToSchedule == 0 && "could not schedule all instructions");
2835 // Avoid duplicate scheduling of the block.
2836 BS->ScheduleStart = nullptr;
2839 /// The SLPVectorizer Pass.
2840 struct SLPVectorizer : public FunctionPass {
2841 typedef SmallVector<StoreInst *, 8> StoreList;
2842 typedef MapVector<Value *, StoreList> StoreListMap;
2844 /// Pass identification, replacement for typeid
2847 explicit SLPVectorizer() : FunctionPass(ID) {
2848 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2851 ScalarEvolution *SE;
2852 const DataLayout *DL;
2853 TargetTransformInfo *TTI;
2854 TargetLibraryInfo *TLI;
2858 AssumptionTracker *AT;
2860 bool runOnFunction(Function &F) override {
2861 if (skipOptnoneFunction(F))
2864 SE = &getAnalysis<ScalarEvolution>();
2865 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2866 DL = DLP ? &DLP->getDataLayout() : nullptr;
2867 TTI = &getAnalysis<TargetTransformInfo>();
2868 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2869 AA = &getAnalysis<AliasAnalysis>();
2870 LI = &getAnalysis<LoopInfo>();
2871 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2872 AT = &getAnalysis<AssumptionTracker>();
2875 bool Changed = false;
2877 // If the target claims to have no vector registers don't attempt
2879 if (!TTI->getNumberOfRegisters(true))
2882 // Must have DataLayout. We can't require it because some tests run w/o
2887 // Don't vectorize when the attribute NoImplicitFloat is used.
2888 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2891 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2893 // Use the bottom up slp vectorizer to construct chains that start with
2894 // store instructions.
2895 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AT);
2897 // Scan the blocks in the function in post order.
2898 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2899 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2900 BasicBlock *BB = *it;
2901 // Vectorize trees that end at stores.
2902 if (unsigned count = collectStores(BB, R)) {
2904 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2905 Changed |= vectorizeStoreChains(R);
2908 // Vectorize trees that end at reductions.
2909 Changed |= vectorizeChainsInBlock(BB, R);
2913 R.optimizeGatherSequence();
2914 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2915 DEBUG(verifyFunction(F));
2920 void getAnalysisUsage(AnalysisUsage &AU) const override {
2921 FunctionPass::getAnalysisUsage(AU);
2922 AU.addRequired<AssumptionTracker>();
2923 AU.addRequired<ScalarEvolution>();
2924 AU.addRequired<AliasAnalysis>();
2925 AU.addRequired<TargetTransformInfo>();
2926 AU.addRequired<LoopInfo>();
2927 AU.addRequired<DominatorTreeWrapperPass>();
2928 AU.addPreserved<LoopInfo>();
2929 AU.addPreserved<DominatorTreeWrapperPass>();
2930 AU.setPreservesCFG();
2935 /// \brief Collect memory references and sort them according to their base
2936 /// object. We sort the stores to their base objects to reduce the cost of the
2937 /// quadratic search on the stores. TODO: We can further reduce this cost
2938 /// if we flush the chain creation every time we run into a memory barrier.
2939 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2941 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2942 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2944 /// \brief Try to vectorize a list of operands.
2945 /// \@param BuildVector A list of users to ignore for the purpose of
2946 /// scheduling and that don't need extracting.
2947 /// \returns true if a value was vectorized.
2948 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2949 ArrayRef<Value *> BuildVector = None,
2950 bool allowReorder = false);
2952 /// \brief Try to vectorize a chain that may start at the operands of \V;
2953 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2955 /// \brief Vectorize the stores that were collected in StoreRefs.
2956 bool vectorizeStoreChains(BoUpSLP &R);
2958 /// \brief Scan the basic block and look for patterns that are likely to start
2959 /// a vectorization chain.
2960 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2962 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2965 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2968 StoreListMap StoreRefs;
2971 /// \brief Check that the Values in the slice in VL array are still existent in
2972 /// the WeakVH array.
2973 /// Vectorization of part of the VL array may cause later values in the VL array
2974 /// to become invalid. We track when this has happened in the WeakVH array.
2975 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2976 SmallVectorImpl<WeakVH> &VH,
2977 unsigned SliceBegin,
2978 unsigned SliceSize) {
2979 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2986 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2987 int CostThreshold, BoUpSLP &R) {
2988 unsigned ChainLen = Chain.size();
2989 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2991 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2992 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2993 unsigned VF = MinVecRegSize / Sz;
2995 if (!isPowerOf2_32(Sz) || VF < 2)
2998 // Keep track of values that were deleted by vectorizing in the loop below.
2999 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3001 bool Changed = false;
3002 // Look for profitable vectorizable trees at all offsets, starting at zero.
3003 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3007 // Check that a previous iteration of this loop did not delete the Value.
3008 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3011 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3013 ArrayRef<Value *> Operands = Chain.slice(i, VF);
3015 R.buildTree(Operands);
3017 int Cost = R.getTreeCost();
3019 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3020 if (Cost < CostThreshold) {
3021 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3024 // Move to the next bundle.
3033 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3034 int costThreshold, BoUpSLP &R) {
3035 SetVector<Value *> Heads, Tails;
3036 SmallDenseMap<Value *, Value *> ConsecutiveChain;
3038 // We may run into multiple chains that merge into a single chain. We mark the
3039 // stores that we vectorized so that we don't visit the same store twice.
3040 BoUpSLP::ValueSet VectorizedStores;
3041 bool Changed = false;
3043 // Do a quadratic search on all of the given stores and find
3044 // all of the pairs of stores that follow each other.
3045 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3046 for (unsigned j = 0; j < e; ++j) {
3050 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
3051 Tails.insert(Stores[j]);
3052 Heads.insert(Stores[i]);
3053 ConsecutiveChain[Stores[i]] = Stores[j];
3058 // For stores that start but don't end a link in the chain:
3059 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
3061 if (Tails.count(*it))
3064 // We found a store instr that starts a chain. Now follow the chain and try
3066 BoUpSLP::ValueList Operands;
3068 // Collect the chain into a list.
3069 while (Tails.count(I) || Heads.count(I)) {
3070 if (VectorizedStores.count(I))
3072 Operands.push_back(I);
3073 // Move to the next value in the chain.
3074 I = ConsecutiveChain[I];
3077 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
3079 // Mark the vectorized stores so that we don't vectorize them again.
3081 VectorizedStores.insert(Operands.begin(), Operands.end());
3082 Changed |= Vectorized;
3089 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
3092 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3093 StoreInst *SI = dyn_cast<StoreInst>(it);
3097 // Don't touch volatile stores.
3098 if (!SI->isSimple())
3101 // Check that the pointer points to scalars.
3102 Type *Ty = SI->getValueOperand()->getType();
3103 if (Ty->isAggregateType() || Ty->isVectorTy())
3106 // Find the base pointer.
3107 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
3109 // Save the store locations.
3110 StoreRefs[Ptr].push_back(SI);
3116 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3119 Value *VL[] = { A, B };
3120 return tryToVectorizeList(VL, R, None, true);
3123 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3124 ArrayRef<Value *> BuildVector,
3125 bool allowReorder) {
3129 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3131 // Check that all of the parts are scalar instructions of the same type.
3132 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3136 unsigned Opcode0 = I0->getOpcode();
3138 Type *Ty0 = I0->getType();
3139 unsigned Sz = DL->getTypeSizeInBits(Ty0);
3140 unsigned VF = MinVecRegSize / Sz;
3142 for (int i = 0, e = VL.size(); i < e; ++i) {
3143 Type *Ty = VL[i]->getType();
3144 if (Ty->isAggregateType() || Ty->isVectorTy())
3146 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
3147 if (!Inst || Inst->getOpcode() != Opcode0)
3151 bool Changed = false;
3153 // Keep track of values that were deleted by vectorizing in the loop below.
3154 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3156 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3157 unsigned OpsWidth = 0;
3164 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3167 // Check that a previous iteration of this loop did not delete the Value.
3168 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3171 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3173 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3175 ArrayRef<Value *> BuildVectorSlice;
3176 if (!BuildVector.empty())
3177 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3179 R.buildTree(Ops, BuildVectorSlice);
3180 // TODO: check if we can allow reordering also for other cases than
3181 // tryToVectorizePair()
3182 if (allowReorder && R.shouldReorder()) {
3183 assert(Ops.size() == 2);
3184 assert(BuildVectorSlice.empty());
3185 Value *ReorderedOps[] = { Ops[1], Ops[0] };
3186 R.buildTree(ReorderedOps, None);
3188 int Cost = R.getTreeCost();
3190 if (Cost < -SLPCostThreshold) {
3191 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3192 Value *VectorizedRoot = R.vectorizeTree();
3194 // Reconstruct the build vector by extracting the vectorized root. This
3195 // way we handle the case where some elements of the vector are undefined.
3196 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3197 if (!BuildVectorSlice.empty()) {
3198 // The insert point is the last build vector instruction. The vectorized
3199 // root will precede it. This guarantees that we get an instruction. The
3200 // vectorized tree could have been constant folded.
3201 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3202 unsigned VecIdx = 0;
3203 for (auto &V : BuildVectorSlice) {
3204 IRBuilder<true, NoFolder> Builder(
3205 ++BasicBlock::iterator(InsertAfter));
3206 InsertElementInst *IE = cast<InsertElementInst>(V);
3207 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3208 VectorizedRoot, Builder.getInt32(VecIdx++)));
3209 IE->setOperand(1, Extract);
3210 IE->removeFromParent();
3211 IE->insertAfter(Extract);
3215 // Move to the next bundle.
3224 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3228 // Try to vectorize V.
3229 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3232 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3233 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3235 if (B && B->hasOneUse()) {
3236 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3237 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3238 if (tryToVectorizePair(A, B0, R)) {
3241 if (tryToVectorizePair(A, B1, R)) {
3247 if (A && A->hasOneUse()) {
3248 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3249 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3250 if (tryToVectorizePair(A0, B, R)) {
3253 if (tryToVectorizePair(A1, B, R)) {
3260 /// \brief Generate a shuffle mask to be used in a reduction tree.
3262 /// \param VecLen The length of the vector to be reduced.
3263 /// \param NumEltsToRdx The number of elements that should be reduced in the
3265 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3266 /// reduction. A pairwise reduction will generate a mask of
3267 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3268 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3269 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3270 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3271 bool IsPairwise, bool IsLeft,
3272 IRBuilder<> &Builder) {
3273 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3275 SmallVector<Constant *, 32> ShuffleMask(
3276 VecLen, UndefValue::get(Builder.getInt32Ty()));
3279 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3280 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3281 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3283 // Move the upper half of the vector to the lower half.
3284 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3285 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3287 return ConstantVector::get(ShuffleMask);
3291 /// Model horizontal reductions.
3293 /// A horizontal reduction is a tree of reduction operations (currently add and
3294 /// fadd) that has operations that can be put into a vector as its leaf.
3295 /// For example, this tree:
3302 /// This tree has "mul" as its reduced values and "+" as its reduction
3303 /// operations. A reduction might be feeding into a store or a binary operation
3318 class HorizontalReduction {
3319 SmallVector<Value *, 16> ReductionOps;
3320 SmallVector<Value *, 32> ReducedVals;
3322 BinaryOperator *ReductionRoot;
3323 PHINode *ReductionPHI;
3325 /// The opcode of the reduction.
3326 unsigned ReductionOpcode;
3327 /// The opcode of the values we perform a reduction on.
3328 unsigned ReducedValueOpcode;
3329 /// The width of one full horizontal reduction operation.
3330 unsigned ReduxWidth;
3331 /// Should we model this reduction as a pairwise reduction tree or a tree that
3332 /// splits the vector in halves and adds those halves.
3333 bool IsPairwiseReduction;
3336 HorizontalReduction()
3337 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3338 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3340 /// \brief Try to find a reduction tree.
3341 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3342 const DataLayout *DL) {
3344 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3345 "Thi phi needs to use the binary operator");
3347 // We could have a initial reductions that is not an add.
3348 // r *= v1 + v2 + v3 + v4
3349 // In such a case start looking for a tree rooted in the first '+'.
3351 if (B->getOperand(0) == Phi) {
3353 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3354 } else if (B->getOperand(1) == Phi) {
3356 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3363 Type *Ty = B->getType();
3364 if (Ty->isVectorTy())
3367 ReductionOpcode = B->getOpcode();
3368 ReducedValueOpcode = 0;
3369 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3376 // We currently only support adds.
3377 if (ReductionOpcode != Instruction::Add &&
3378 ReductionOpcode != Instruction::FAdd)
3381 // Post order traverse the reduction tree starting at B. We only handle true
3382 // trees containing only binary operators.
3383 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3384 Stack.push_back(std::make_pair(B, 0));
3385 while (!Stack.empty()) {
3386 BinaryOperator *TreeN = Stack.back().first;
3387 unsigned EdgeToVist = Stack.back().second++;
3388 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3390 // Only handle trees in the current basic block.
3391 if (TreeN->getParent() != B->getParent())
3394 // Each tree node needs to have one user except for the ultimate
3396 if (!TreeN->hasOneUse() && TreeN != B)
3400 if (EdgeToVist == 2 || IsReducedValue) {
3401 if (IsReducedValue) {
3402 // Make sure that the opcodes of the operations that we are going to
3404 if (!ReducedValueOpcode)
3405 ReducedValueOpcode = TreeN->getOpcode();
3406 else if (ReducedValueOpcode != TreeN->getOpcode())
3408 ReducedVals.push_back(TreeN);
3410 // We need to be able to reassociate the adds.
3411 if (!TreeN->isAssociative())
3413 ReductionOps.push_back(TreeN);
3420 // Visit left or right.
3421 Value *NextV = TreeN->getOperand(EdgeToVist);
3422 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3424 Stack.push_back(std::make_pair(Next, 0));
3425 else if (NextV != Phi)
3431 /// \brief Attempt to vectorize the tree found by
3432 /// matchAssociativeReduction.
3433 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3434 if (ReducedVals.empty())
3437 unsigned NumReducedVals = ReducedVals.size();
3438 if (NumReducedVals < ReduxWidth)
3441 Value *VectorizedTree = nullptr;
3442 IRBuilder<> Builder(ReductionRoot);
3443 FastMathFlags Unsafe;
3444 Unsafe.setUnsafeAlgebra();
3445 Builder.SetFastMathFlags(Unsafe);
3448 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3449 V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3452 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3453 if (Cost >= -SLPCostThreshold)
3456 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3459 // Vectorize a tree.
3460 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3461 Value *VectorizedRoot = V.vectorizeTree();
3463 // Emit a reduction.
3464 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3465 if (VectorizedTree) {
3466 Builder.SetCurrentDebugLocation(Loc);
3467 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3468 ReducedSubTree, "bin.rdx");
3470 VectorizedTree = ReducedSubTree;
3473 if (VectorizedTree) {
3474 // Finish the reduction.
3475 for (; i < NumReducedVals; ++i) {
3476 Builder.SetCurrentDebugLocation(
3477 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3478 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3483 assert(ReductionRoot && "Need a reduction operation");
3484 ReductionRoot->setOperand(0, VectorizedTree);
3485 ReductionRoot->setOperand(1, ReductionPHI);
3487 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3489 return VectorizedTree != nullptr;
3494 /// \brief Calcuate the cost of a reduction.
3495 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3496 Type *ScalarTy = FirstReducedVal->getType();
3497 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3499 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3500 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3502 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3503 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3505 int ScalarReduxCost =
3506 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3508 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3509 << " for reduction that starts with " << *FirstReducedVal
3511 << (IsPairwiseReduction ? "pairwise" : "splitting")
3512 << " reduction)\n");
3514 return VecReduxCost - ScalarReduxCost;
3517 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3518 Value *R, const Twine &Name = "") {
3519 if (Opcode == Instruction::FAdd)
3520 return Builder.CreateFAdd(L, R, Name);
3521 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3524 /// \brief Emit a horizontal reduction of the vectorized value.
3525 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3526 assert(VectorizedValue && "Need to have a vectorized tree node");
3527 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
3528 assert(isPowerOf2_32(ReduxWidth) &&
3529 "We only handle power-of-two reductions for now");
3531 Value *TmpVec = ValToReduce;
3532 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3533 if (IsPairwiseReduction) {
3535 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3537 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3539 Value *LeftShuf = Builder.CreateShuffleVector(
3540 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3541 Value *RightShuf = Builder.CreateShuffleVector(
3542 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3544 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3548 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3549 Value *Shuf = Builder.CreateShuffleVector(
3550 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3551 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3555 // The result is in the first element of the vector.
3556 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3560 /// \brief Recognize construction of vectors like
3561 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3562 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3563 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3564 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3566 /// Returns true if it matches
3568 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3569 SmallVectorImpl<Value *> &BuildVector,
3570 SmallVectorImpl<Value *> &BuildVectorOpds) {
3571 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3574 InsertElementInst *IE = FirstInsertElem;
3576 BuildVector.push_back(IE);
3577 BuildVectorOpds.push_back(IE->getOperand(1));
3579 if (IE->use_empty())
3582 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3586 // If this isn't the final use, make sure the next insertelement is the only
3587 // use. It's OK if the final constructed vector is used multiple times
3588 if (!IE->hasOneUse())
3597 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3598 return V->getType() < V2->getType();
3601 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3602 bool Changed = false;
3603 SmallVector<Value *, 4> Incoming;
3604 SmallSet<Value *, 16> VisitedInstrs;
3606 bool HaveVectorizedPhiNodes = true;
3607 while (HaveVectorizedPhiNodes) {
3608 HaveVectorizedPhiNodes = false;
3610 // Collect the incoming values from the PHIs.
3612 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3614 PHINode *P = dyn_cast<PHINode>(instr);
3618 if (!VisitedInstrs.count(P))
3619 Incoming.push_back(P);
3623 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3625 // Try to vectorize elements base on their type.
3626 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3630 // Look for the next elements with the same type.
3631 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3632 while (SameTypeIt != E &&
3633 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3634 VisitedInstrs.insert(*SameTypeIt);
3638 // Try to vectorize them.
3639 unsigned NumElts = (SameTypeIt - IncIt);
3640 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3641 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3642 // Success start over because instructions might have been changed.
3643 HaveVectorizedPhiNodes = true;
3648 // Start over at the next instruction of a different type (or the end).
3653 VisitedInstrs.clear();
3655 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3656 // We may go through BB multiple times so skip the one we have checked.
3657 if (!VisitedInstrs.insert(it).second)
3660 if (isa<DbgInfoIntrinsic>(it))
3663 // Try to vectorize reductions that use PHINodes.
3664 if (PHINode *P = dyn_cast<PHINode>(it)) {
3665 // Check that the PHI is a reduction PHI.
3666 if (P->getNumIncomingValues() != 2)
3669 (P->getIncomingBlock(0) == BB
3670 ? (P->getIncomingValue(0))
3671 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3673 // Check if this is a Binary Operator.
3674 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3678 // Try to match and vectorize a horizontal reduction.
3679 HorizontalReduction HorRdx;
3680 if (ShouldVectorizeHor &&
3681 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3682 HorRdx.tryToReduce(R, TTI)) {
3689 Value *Inst = BI->getOperand(0);
3691 Inst = BI->getOperand(1);
3693 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3694 // We would like to start over since some instructions are deleted
3695 // and the iterator may become invalid value.
3705 // Try to vectorize horizontal reductions feeding into a store.
3706 if (ShouldStartVectorizeHorAtStore)
3707 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3708 if (BinaryOperator *BinOp =
3709 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3710 HorizontalReduction HorRdx;
3711 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3712 HorRdx.tryToReduce(R, TTI)) ||
3713 tryToVectorize(BinOp, R))) {
3721 // Try to vectorize horizontal reductions feeding into a return.
3722 if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
3723 if (RI->getNumOperands() != 0)
3724 if (BinaryOperator *BinOp =
3725 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
3726 DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
3727 if (tryToVectorizePair(BinOp->getOperand(0),
3728 BinOp->getOperand(1), R)) {
3736 // Try to vectorize trees that start at compare instructions.
3737 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3738 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3740 // We would like to start over since some instructions are deleted
3741 // and the iterator may become invalid value.
3747 for (int i = 0; i < 2; ++i) {
3748 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3749 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3751 // We would like to start over since some instructions are deleted
3752 // and the iterator may become invalid value.
3761 // Try to vectorize trees that start at insertelement instructions.
3762 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3763 SmallVector<Value *, 16> BuildVector;
3764 SmallVector<Value *, 16> BuildVectorOpds;
3765 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3768 // Vectorize starting with the build vector operands ignoring the
3769 // BuildVector instructions for the purpose of scheduling and user
3771 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3784 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3785 bool Changed = false;
3786 // Attempt to sort and vectorize each of the store-groups.
3787 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3789 if (it->second.size() < 2)
3792 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3793 << it->second.size() << ".\n");
3795 // Process the stores in chunks of 16.
3796 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3797 unsigned Len = std::min<unsigned>(CE - CI, 16);
3798 Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3799 -SLPCostThreshold, R);
3805 } // end anonymous namespace
3807 char SLPVectorizer::ID = 0;
3808 static const char lv_name[] = "SLP Vectorizer";
3809 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3810 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3811 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3812 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
3813 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3814 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3815 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3818 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }