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/LoopInfo.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/NoFolder.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/Utils/VectorUtils.h"
50 #define SV_NAME "slp-vectorizer"
51 #define DEBUG_TYPE "SLP"
53 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
56 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
57 cl::desc("Only vectorize if you gain more than this "
61 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
62 cl::desc("Attempt to vectorize horizontal reductions"));
64 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
65 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
67 "Attempt to vectorize horizontal reductions feeding into a store"));
71 static const unsigned MinVecRegSize = 128;
73 static const unsigned RecursionMaxDepth = 12;
75 /// \returns the parent basic block if all of the instructions in \p VL
76 /// are in the same block or null otherwise.
77 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
78 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
81 BasicBlock *BB = I0->getParent();
82 for (int i = 1, e = VL.size(); i < e; i++) {
83 Instruction *I = dyn_cast<Instruction>(VL[i]);
87 if (BB != I->getParent())
93 /// \returns True if all of the values in \p VL are constants.
94 static bool allConstant(ArrayRef<Value *> VL) {
95 for (unsigned i = 0, e = VL.size(); i < e; ++i)
96 if (!isa<Constant>(VL[i]))
101 /// \returns True if all of the values in \p VL are identical.
102 static bool isSplat(ArrayRef<Value *> VL) {
103 for (unsigned i = 1, e = VL.size(); i < e; ++i)
109 ///\returns Opcode that can be clubbed with \p Op to create an alternate
110 /// sequence which can later be merged as a ShuffleVector instruction.
111 static unsigned getAltOpcode(unsigned Op) {
113 case Instruction::FAdd:
114 return Instruction::FSub;
115 case Instruction::FSub:
116 return Instruction::FAdd;
117 case Instruction::Add:
118 return Instruction::Sub;
119 case Instruction::Sub:
120 return Instruction::Add;
126 ///\returns bool representing if Opcode \p Op can be part
127 /// of an alternate sequence which can later be merged as
128 /// a ShuffleVector instruction.
129 static bool canCombineAsAltInst(unsigned Op) {
130 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
131 Op == Instruction::Sub || Op == Instruction::Add)
136 /// \returns ShuffleVector instruction if intructions in \p VL have
137 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
138 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
139 static unsigned isAltInst(ArrayRef<Value *> VL) {
140 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
141 unsigned Opcode = I0->getOpcode();
142 unsigned AltOpcode = getAltOpcode(Opcode);
143 for (int i = 1, e = VL.size(); i < e; i++) {
144 Instruction *I = dyn_cast<Instruction>(VL[i]);
145 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
148 return Instruction::ShuffleVector;
151 /// \returns The opcode if all of the Instructions in \p VL have the same
153 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
154 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
157 unsigned Opcode = I0->getOpcode();
158 for (int i = 1, e = VL.size(); i < e; i++) {
159 Instruction *I = dyn_cast<Instruction>(VL[i]);
160 if (!I || Opcode != I->getOpcode()) {
161 if (canCombineAsAltInst(Opcode) && i == 1)
162 return isAltInst(VL);
169 /// \returns \p I after propagating metadata from \p VL.
170 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
171 Instruction *I0 = cast<Instruction>(VL[0]);
172 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
173 I0->getAllMetadataOtherThanDebugLoc(Metadata);
175 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
176 unsigned Kind = Metadata[i].first;
177 MDNode *MD = Metadata[i].second;
179 for (int i = 1, e = VL.size(); MD && i != e; i++) {
180 Instruction *I = cast<Instruction>(VL[i]);
181 MDNode *IMD = I->getMetadata(Kind);
185 MD = nullptr; // Remove unknown metadata
187 case LLVMContext::MD_tbaa:
188 MD = MDNode::getMostGenericTBAA(MD, IMD);
190 case LLVMContext::MD_alias_scope:
191 case LLVMContext::MD_noalias:
192 MD = MDNode::intersect(MD, IMD);
194 case LLVMContext::MD_fpmath:
195 MD = MDNode::getMostGenericFPMath(MD, IMD);
199 I->setMetadata(Kind, MD);
204 /// \returns The type that all of the values in \p VL have or null if there
205 /// are different types.
206 static Type* getSameType(ArrayRef<Value *> VL) {
207 Type *Ty = VL[0]->getType();
208 for (int i = 1, e = VL.size(); i < e; i++)
209 if (VL[i]->getType() != Ty)
215 /// \returns True if the ExtractElement instructions in VL can be vectorized
216 /// to use the original vector.
217 static bool CanReuseExtract(ArrayRef<Value *> VL) {
218 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
219 // Check if all of the extracts come from the same vector and from the
222 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
223 Value *Vec = E0->getOperand(0);
225 // We have to extract from the same vector type.
226 unsigned NElts = Vec->getType()->getVectorNumElements();
228 if (NElts != VL.size())
231 // Check that all of the indices extract from the correct offset.
232 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
233 if (!CI || CI->getZExtValue())
236 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
237 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
238 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
240 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
247 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
248 SmallVectorImpl<Value *> &Left,
249 SmallVectorImpl<Value *> &Right) {
251 SmallVector<Value *, 16> OrigLeft, OrigRight;
253 bool AllSameOpcodeLeft = true;
254 bool AllSameOpcodeRight = true;
255 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
256 Instruction *I = cast<Instruction>(VL[i]);
257 Value *V0 = I->getOperand(0);
258 Value *V1 = I->getOperand(1);
260 OrigLeft.push_back(V0);
261 OrigRight.push_back(V1);
263 Instruction *I0 = dyn_cast<Instruction>(V0);
264 Instruction *I1 = dyn_cast<Instruction>(V1);
266 // Check whether all operands on one side have the same opcode. In this case
267 // we want to preserve the original order and not make things worse by
269 AllSameOpcodeLeft = I0;
270 AllSameOpcodeRight = I1;
272 if (i && AllSameOpcodeLeft) {
273 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
274 if(P0->getOpcode() != I0->getOpcode())
275 AllSameOpcodeLeft = false;
277 AllSameOpcodeLeft = false;
279 if (i && AllSameOpcodeRight) {
280 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
281 if(P1->getOpcode() != I1->getOpcode())
282 AllSameOpcodeRight = false;
284 AllSameOpcodeRight = false;
287 // Sort two opcodes. In the code below we try to preserve the ability to use
288 // broadcast of values instead of individual inserts.
295 // If we just sorted according to opcode we would leave the first line in
296 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
299 // Because vr2 and vr1 are from the same load we loose the opportunity of a
300 // broadcast for the packed right side in the backend: we have [vr1, vl2]
301 // instead of [vr1, vr2=vr1].
303 if(!i && I0->getOpcode() > I1->getOpcode()) {
306 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
307 // Try not to destroy a broad cast for no apparent benefit.
310 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
311 // Try preserve broadcasts.
314 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
315 // Try preserve broadcasts.
324 // One opcode, put the instruction on the right.
334 bool LeftBroadcast = isSplat(Left);
335 bool RightBroadcast = isSplat(Right);
337 // Don't reorder if the operands where good to begin with.
338 if (!(LeftBroadcast || RightBroadcast) &&
339 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
345 /// Bottom Up SLP Vectorizer.
348 typedef SmallVector<Value *, 8> ValueList;
349 typedef SmallVector<Instruction *, 16> InstrList;
350 typedef SmallPtrSet<Value *, 16> ValueSet;
351 typedef SmallVector<StoreInst *, 8> StoreList;
353 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
354 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
355 LoopInfo *Li, DominatorTree *Dt)
356 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0),
357 F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
358 Builder(Se->getContext()) {}
360 /// \brief Vectorize the tree that starts with the elements in \p VL.
361 /// Returns the vectorized root.
362 Value *vectorizeTree();
364 /// \returns the vectorization cost of the subtree that starts at \p VL.
365 /// A negative number means that this is profitable.
368 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
369 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
370 void buildTree(ArrayRef<Value *> Roots,
371 ArrayRef<Value *> UserIgnoreLst = None);
373 /// Clear the internal data structures that are created by 'buildTree'.
375 VectorizableTree.clear();
376 ScalarToTreeEntry.clear();
378 ExternalUses.clear();
379 NumLoadsWantToKeepOrder = 0;
380 NumLoadsWantToChangeOrder = 0;
381 for (auto &Iter : BlocksSchedules) {
382 BlockScheduling *BS = Iter.second.get();
387 /// \returns true if the memory operations A and B are consecutive.
388 bool isConsecutiveAccess(Value *A, Value *B);
390 /// \brief Perform LICM and CSE on the newly generated gather sequences.
391 void optimizeGatherSequence();
393 /// \returns true if it is benefitial to reverse the vector order.
394 bool shouldReorder() const {
395 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
401 /// \returns the cost of the vectorizable entry.
402 int getEntryCost(TreeEntry *E);
404 /// This is the recursive part of buildTree.
405 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
407 /// Vectorize a single entry in the tree.
408 Value *vectorizeTree(TreeEntry *E);
410 /// Vectorize a single entry in the tree, starting in \p VL.
411 Value *vectorizeTree(ArrayRef<Value *> VL);
413 /// \returns the pointer to the vectorized value if \p VL is already
414 /// vectorized, or NULL. They may happen in cycles.
415 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
417 /// \brief Take the pointer operand from the Load/Store instruction.
418 /// \returns NULL if this is not a valid Load/Store instruction.
419 static Value *getPointerOperand(Value *I);
421 /// \brief Take the address space operand from the Load/Store instruction.
422 /// \returns -1 if this is not a valid Load/Store instruction.
423 static unsigned getAddressSpaceOperand(Value *I);
425 /// \returns the scalarization cost for this type. Scalarization in this
426 /// context means the creation of vectors from a group of scalars.
427 int getGatherCost(Type *Ty);
429 /// \returns the scalarization cost for this list of values. Assuming that
430 /// this subtree gets vectorized, we may need to extract the values from the
431 /// roots. This method calculates the cost of extracting the values.
432 int getGatherCost(ArrayRef<Value *> VL);
434 /// \brief Set the Builder insert point to one after the last instruction in
436 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
438 /// \returns a vector from a collection of scalars in \p VL.
439 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
441 /// \returns whether the VectorizableTree is fully vectoriable and will
442 /// be beneficial even the tree height is tiny.
443 bool isFullyVectorizableTinyTree();
446 TreeEntry() : Scalars(), VectorizedValue(nullptr),
449 /// \returns true if the scalars in VL are equal to this entry.
450 bool isSame(ArrayRef<Value *> VL) const {
451 assert(VL.size() == Scalars.size() && "Invalid size");
452 return std::equal(VL.begin(), VL.end(), Scalars.begin());
455 /// A vector of scalars.
458 /// The Scalars are vectorized into this value. It is initialized to Null.
459 Value *VectorizedValue;
461 /// Do we need to gather this sequence ?
465 /// Create a new VectorizableTree entry.
466 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
467 VectorizableTree.push_back(TreeEntry());
468 int idx = VectorizableTree.size() - 1;
469 TreeEntry *Last = &VectorizableTree[idx];
470 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
471 Last->NeedToGather = !Vectorized;
473 for (int i = 0, e = VL.size(); i != e; ++i) {
474 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
475 ScalarToTreeEntry[VL[i]] = idx;
478 MustGather.insert(VL.begin(), VL.end());
483 /// -- Vectorization State --
484 /// Holds all of the tree entries.
485 std::vector<TreeEntry> VectorizableTree;
487 /// Maps a specific scalar to its tree entry.
488 SmallDenseMap<Value*, int> ScalarToTreeEntry;
490 /// A list of scalars that we found that we need to keep as scalars.
493 /// This POD struct describes one external user in the vectorized tree.
494 struct ExternalUser {
495 ExternalUser (Value *S, llvm::User *U, int L) :
496 Scalar(S), User(U), Lane(L){};
497 // Which scalar in our function.
499 // Which user that uses the scalar.
501 // Which lane does the scalar belong to.
504 typedef SmallVector<ExternalUser, 16> UserList;
506 /// A list of values that need to extracted out of the tree.
507 /// This list holds pairs of (Internal Scalar : External User).
508 UserList ExternalUses;
510 /// Holds all of the instructions that we gathered.
511 SetVector<Instruction *> GatherSeq;
512 /// A list of blocks that we are going to CSE.
513 SetVector<BasicBlock *> CSEBlocks;
515 /// Contains all scheduling relevant data for an instruction.
516 /// A ScheduleData either represents a single instruction or a member of an
517 /// instruction bundle (= a group of instructions which is combined into a
518 /// vector instruction).
519 struct ScheduleData {
521 // The initial value for the dependency counters. It means that the
522 // dependencies are not calculated yet.
523 enum { InvalidDeps = -1 };
526 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
527 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
528 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
529 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
531 void init(int BlockSchedulingRegionID) {
532 FirstInBundle = this;
533 NextInBundle = nullptr;
534 NextLoadStore = nullptr;
536 SchedulingRegionID = BlockSchedulingRegionID;
537 UnscheduledDepsInBundle = UnscheduledDeps;
541 /// Returns true if the dependency information has been calculated.
542 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
544 /// Returns true for single instructions and for bundle representatives
545 /// (= the head of a bundle).
546 bool isSchedulingEntity() const { return FirstInBundle == this; }
548 /// Returns true if it represents an instruction bundle and not only a
549 /// single instruction.
550 bool isPartOfBundle() const {
551 return NextInBundle != nullptr || FirstInBundle != this;
554 /// Returns true if it is ready for scheduling, i.e. it has no more
555 /// unscheduled depending instructions/bundles.
556 bool isReady() const {
557 assert(isSchedulingEntity() &&
558 "can't consider non-scheduling entity for ready list");
559 return UnscheduledDepsInBundle == 0 && !IsScheduled;
562 /// Modifies the number of unscheduled dependencies, also updating it for
563 /// the whole bundle.
564 int incrementUnscheduledDeps(int Incr) {
565 UnscheduledDeps += Incr;
566 return FirstInBundle->UnscheduledDepsInBundle += Incr;
569 /// Sets the number of unscheduled dependencies to the number of
571 void resetUnscheduledDeps() {
572 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
575 /// Clears all dependency information.
576 void clearDependencies() {
577 Dependencies = InvalidDeps;
578 resetUnscheduledDeps();
579 MemoryDependencies.clear();
582 void dump(raw_ostream &os) const {
583 if (!isSchedulingEntity()) {
585 } else if (NextInBundle) {
587 ScheduleData *SD = NextInBundle;
589 os << ';' << *SD->Inst;
590 SD = SD->NextInBundle;
600 /// Points to the head in an instruction bundle (and always to this for
601 /// single instructions).
602 ScheduleData *FirstInBundle;
604 /// Single linked list of all instructions in a bundle. Null if it is a
605 /// single instruction.
606 ScheduleData *NextInBundle;
608 /// Single linked list of all memory instructions (e.g. load, store, call)
609 /// in the block - until the end of the scheduling region.
610 ScheduleData *NextLoadStore;
612 /// The dependent memory instructions.
613 /// This list is derived on demand in calculateDependencies().
614 SmallVector<ScheduleData *, 4> MemoryDependencies;
616 /// This ScheduleData is in the current scheduling region if this matches
617 /// the current SchedulingRegionID of BlockScheduling.
618 int SchedulingRegionID;
620 /// Used for getting a "good" final ordering of instructions.
621 int SchedulingPriority;
623 /// The number of dependencies. Constitutes of the number of users of the
624 /// instruction plus the number of dependent memory instructions (if any).
625 /// This value is calculated on demand.
626 /// If InvalidDeps, the number of dependencies is not calculated yet.
630 /// The number of dependencies minus the number of dependencies of scheduled
631 /// instructions. As soon as this is zero, the instruction/bundle gets ready
633 /// Note that this is negative as long as Dependencies is not calculated.
636 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
637 /// single instructions.
638 int UnscheduledDepsInBundle;
640 /// True if this instruction is scheduled (or considered as scheduled in the
645 friend raw_ostream &operator<<(raw_ostream &os,
646 const BoUpSLP::ScheduleData &SD);
648 /// Contains all scheduling data for a basic block.
650 struct BlockScheduling {
652 BlockScheduling(BasicBlock *BB)
653 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
654 ScheduleStart(nullptr), ScheduleEnd(nullptr),
655 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
656 // Make sure that the initial SchedulingRegionID is greater than the
657 // initial SchedulingRegionID in ScheduleData (which is 0).
658 SchedulingRegionID(1) {}
662 ScheduleStart = nullptr;
663 ScheduleEnd = nullptr;
664 FirstLoadStoreInRegion = nullptr;
665 LastLoadStoreInRegion = nullptr;
667 // Make a new scheduling region, i.e. all existing ScheduleData is not
668 // in the new region yet.
669 ++SchedulingRegionID;
672 ScheduleData *getScheduleData(Value *V) {
673 ScheduleData *SD = ScheduleDataMap[V];
674 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
679 bool isInSchedulingRegion(ScheduleData *SD) {
680 return SD->SchedulingRegionID == SchedulingRegionID;
683 /// Marks an instruction as scheduled and puts all dependent ready
684 /// instructions into the ready-list.
685 template <typename ReadyListType>
686 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
687 SD->IsScheduled = true;
688 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
690 ScheduleData *BundleMember = SD;
691 while (BundleMember) {
692 // Handle the def-use chain dependencies.
693 for (Use &U : BundleMember->Inst->operands()) {
694 ScheduleData *OpDef = getScheduleData(U.get());
695 if (OpDef && OpDef->hasValidDependencies() &&
696 OpDef->incrementUnscheduledDeps(-1) == 0) {
697 // There are no more unscheduled dependencies after decrementing,
698 // so we can put the dependent instruction into the ready list.
699 ScheduleData *DepBundle = OpDef->FirstInBundle;
700 assert(!DepBundle->IsScheduled &&
701 "already scheduled bundle gets ready");
702 ReadyList.insert(DepBundle);
703 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
706 // Handle the memory dependencies.
707 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
708 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
709 // There are no more unscheduled dependencies after decrementing,
710 // so we can put the dependent instruction into the ready list.
711 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
712 assert(!DepBundle->IsScheduled &&
713 "already scheduled bundle gets ready");
714 ReadyList.insert(DepBundle);
715 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
718 BundleMember = BundleMember->NextInBundle;
722 /// Put all instructions into the ReadyList which are ready for scheduling.
723 template <typename ReadyListType>
724 void initialFillReadyList(ReadyListType &ReadyList) {
725 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
726 ScheduleData *SD = getScheduleData(I);
727 if (SD->isSchedulingEntity() && SD->isReady()) {
728 ReadyList.insert(SD);
729 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
734 /// Checks if a bundle of instructions can be scheduled, i.e. has no
735 /// cyclic dependencies. This is only a dry-run, no instructions are
736 /// actually moved at this stage.
737 bool tryScheduleBundle(ArrayRef<Value *> VL, AliasAnalysis *AA);
739 /// Un-bundles a group of instructions.
740 void cancelScheduling(ArrayRef<Value *> VL);
742 /// Extends the scheduling region so that V is inside the region.
743 void extendSchedulingRegion(Value *V);
745 /// Initialize the ScheduleData structures for new instructions in the
746 /// scheduling region.
747 void initScheduleData(Instruction *FromI, Instruction *ToI,
748 ScheduleData *PrevLoadStore,
749 ScheduleData *NextLoadStore);
751 /// Updates the dependency information of a bundle and of all instructions/
752 /// bundles which depend on the original bundle.
753 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
756 /// Sets all instruction in the scheduling region to un-scheduled.
757 void resetSchedule();
761 /// Simple memory allocation for ScheduleData.
762 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
764 /// The size of a ScheduleData array in ScheduleDataChunks.
767 /// The allocator position in the current chunk, which is the last entry
768 /// of ScheduleDataChunks.
771 /// Attaches ScheduleData to Instruction.
772 /// Note that the mapping survives during all vectorization iterations, i.e.
773 /// ScheduleData structures are recycled.
774 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
776 struct ReadyList : SmallVector<ScheduleData *, 8> {
777 void insert(ScheduleData *SD) { push_back(SD); }
780 /// The ready-list for scheduling (only used for the dry-run).
781 ReadyList ReadyInsts;
783 /// The first instruction of the scheduling region.
784 Instruction *ScheduleStart;
786 /// The first instruction _after_ the scheduling region.
787 Instruction *ScheduleEnd;
789 /// The first memory accessing instruction in the scheduling region
791 ScheduleData *FirstLoadStoreInRegion;
793 /// The last memory accessing instruction in the scheduling region
795 ScheduleData *LastLoadStoreInRegion;
797 /// The ID of the scheduling region. For a new vectorization iteration this
798 /// is incremented which "removes" all ScheduleData from the region.
799 int SchedulingRegionID;
802 /// Attaches the BlockScheduling structures to basic blocks.
803 DenseMap<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
805 /// Performs the "real" scheduling. Done before vectorization is actually
806 /// performed in a basic block.
807 void scheduleBlock(BasicBlock *BB);
809 /// List of users to ignore during scheduling and that don't need extracting.
810 ArrayRef<Value *> UserIgnoreList;
812 // Number of load-bundles, which contain consecutive loads.
813 int NumLoadsWantToKeepOrder;
815 // Number of load-bundles of size 2, which are consecutive loads if reversed.
816 int NumLoadsWantToChangeOrder;
818 // Analysis and block reference.
821 const DataLayout *DL;
822 TargetTransformInfo *TTI;
823 TargetLibraryInfo *TLI;
827 /// Instruction builder to construct the vectorized tree.
831 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
836 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
837 ArrayRef<Value *> UserIgnoreLst) {
839 UserIgnoreList = UserIgnoreLst;
840 if (!getSameType(Roots))
842 buildTree_rec(Roots, 0);
844 // Collect the values that we need to extract from the tree.
845 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
846 TreeEntry *Entry = &VectorizableTree[EIdx];
849 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
850 Value *Scalar = Entry->Scalars[Lane];
852 // No need to handle users of gathered values.
853 if (Entry->NeedToGather)
856 for (User *U : Scalar->users()) {
857 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
859 // Skip in-tree scalars that become vectors.
860 if (ScalarToTreeEntry.count(U)) {
861 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
863 int Idx = ScalarToTreeEntry[U]; (void) Idx;
864 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
867 Instruction *UserInst = dyn_cast<Instruction>(U);
871 // Ignore users in the user ignore list.
872 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
873 UserIgnoreList.end())
876 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
877 Lane << " from " << *Scalar << ".\n");
878 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
885 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
886 bool SameTy = getSameType(VL); (void)SameTy;
887 bool isAltShuffle = false;
888 assert(SameTy && "Invalid types!");
890 if (Depth == RecursionMaxDepth) {
891 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
892 newTreeEntry(VL, false);
896 // Don't handle vectors.
897 if (VL[0]->getType()->isVectorTy()) {
898 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
899 newTreeEntry(VL, false);
903 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
904 if (SI->getValueOperand()->getType()->isVectorTy()) {
905 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
906 newTreeEntry(VL, false);
909 unsigned Opcode = getSameOpcode(VL);
911 // Check that this shuffle vector refers to the alternate
912 // sequence of opcodes.
913 if (Opcode == Instruction::ShuffleVector) {
914 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
915 unsigned Op = I0->getOpcode();
916 if (Op != Instruction::ShuffleVector)
920 // If all of the operands are identical or constant we have a simple solution.
921 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
922 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
923 newTreeEntry(VL, false);
927 // We now know that this is a vector of instructions of the same type from
930 // Check if this is a duplicate of another entry.
931 if (ScalarToTreeEntry.count(VL[0])) {
932 int Idx = ScalarToTreeEntry[VL[0]];
933 TreeEntry *E = &VectorizableTree[Idx];
934 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
935 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
936 if (E->Scalars[i] != VL[i]) {
937 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
938 newTreeEntry(VL, false);
942 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
946 // Check that none of the instructions in the bundle are already in the tree.
947 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
948 if (ScalarToTreeEntry.count(VL[i])) {
949 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
950 ") is already in tree.\n");
951 newTreeEntry(VL, false);
956 // If any of the scalars appears in the table OR it is marked as a value that
957 // needs to stat scalar then we need to gather the scalars.
958 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
959 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
960 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
961 newTreeEntry(VL, false);
966 // Check that all of the users of the scalars that we want to vectorize are
968 Instruction *VL0 = cast<Instruction>(VL[0]);
969 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
971 // Check that every instructions appears once in this bundle.
972 for (unsigned i = 0, e = VL.size(); i < e; ++i)
973 for (unsigned j = i+1; j < e; ++j)
974 if (VL[i] == VL[j]) {
975 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
976 newTreeEntry(VL, false);
980 auto &BSRef = BlocksSchedules[BB];
982 BSRef = llvm::make_unique<BlockScheduling>(BB);
984 BlockScheduling &BS = *BSRef.get();
986 if (!BS.tryScheduleBundle(VL, AA)) {
987 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
988 BS.cancelScheduling(VL);
989 newTreeEntry(VL, false);
992 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
995 case Instruction::PHI: {
996 PHINode *PH = dyn_cast<PHINode>(VL0);
998 // Check for terminator values (e.g. invoke).
999 for (unsigned j = 0; j < VL.size(); ++j)
1000 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1001 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1002 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1004 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1005 BS.cancelScheduling(VL);
1006 newTreeEntry(VL, false);
1011 newTreeEntry(VL, true);
1012 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1014 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1016 // Prepare the operand vector.
1017 for (unsigned j = 0; j < VL.size(); ++j)
1018 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1019 PH->getIncomingBlock(i)));
1021 buildTree_rec(Operands, Depth + 1);
1025 case Instruction::ExtractElement: {
1026 bool Reuse = CanReuseExtract(VL);
1028 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1030 BS.cancelScheduling(VL);
1032 newTreeEntry(VL, Reuse);
1035 case Instruction::Load: {
1036 // Check if the loads are consecutive or of we need to swizzle them.
1037 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1038 LoadInst *L = cast<LoadInst>(VL[i]);
1039 if (!L->isSimple()) {
1040 BS.cancelScheduling(VL);
1041 newTreeEntry(VL, false);
1042 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1045 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1046 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1047 ++NumLoadsWantToChangeOrder;
1049 BS.cancelScheduling(VL);
1050 newTreeEntry(VL, false);
1051 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1055 ++NumLoadsWantToKeepOrder;
1056 newTreeEntry(VL, true);
1057 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1060 case Instruction::ZExt:
1061 case Instruction::SExt:
1062 case Instruction::FPToUI:
1063 case Instruction::FPToSI:
1064 case Instruction::FPExt:
1065 case Instruction::PtrToInt:
1066 case Instruction::IntToPtr:
1067 case Instruction::SIToFP:
1068 case Instruction::UIToFP:
1069 case Instruction::Trunc:
1070 case Instruction::FPTrunc:
1071 case Instruction::BitCast: {
1072 Type *SrcTy = VL0->getOperand(0)->getType();
1073 for (unsigned i = 0; i < VL.size(); ++i) {
1074 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1075 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1076 BS.cancelScheduling(VL);
1077 newTreeEntry(VL, false);
1078 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1082 newTreeEntry(VL, true);
1083 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1085 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1087 // Prepare the operand vector.
1088 for (unsigned j = 0; j < VL.size(); ++j)
1089 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1091 buildTree_rec(Operands, Depth+1);
1095 case Instruction::ICmp:
1096 case Instruction::FCmp: {
1097 // Check that all of the compares have the same predicate.
1098 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1099 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1100 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1101 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1102 if (Cmp->getPredicate() != P0 ||
1103 Cmp->getOperand(0)->getType() != ComparedTy) {
1104 BS.cancelScheduling(VL);
1105 newTreeEntry(VL, false);
1106 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1111 newTreeEntry(VL, true);
1112 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1114 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1116 // Prepare the operand vector.
1117 for (unsigned j = 0; j < VL.size(); ++j)
1118 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1120 buildTree_rec(Operands, Depth+1);
1124 case Instruction::Select:
1125 case Instruction::Add:
1126 case Instruction::FAdd:
1127 case Instruction::Sub:
1128 case Instruction::FSub:
1129 case Instruction::Mul:
1130 case Instruction::FMul:
1131 case Instruction::UDiv:
1132 case Instruction::SDiv:
1133 case Instruction::FDiv:
1134 case Instruction::URem:
1135 case Instruction::SRem:
1136 case Instruction::FRem:
1137 case Instruction::Shl:
1138 case Instruction::LShr:
1139 case Instruction::AShr:
1140 case Instruction::And:
1141 case Instruction::Or:
1142 case Instruction::Xor: {
1143 newTreeEntry(VL, true);
1144 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1146 // Sort operands of the instructions so that each side is more likely to
1147 // have the same opcode.
1148 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1149 ValueList Left, Right;
1150 reorderInputsAccordingToOpcode(VL, Left, Right);
1151 buildTree_rec(Left, Depth + 1);
1152 buildTree_rec(Right, Depth + 1);
1156 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1158 // Prepare the operand vector.
1159 for (unsigned j = 0; j < VL.size(); ++j)
1160 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1162 buildTree_rec(Operands, Depth+1);
1166 case Instruction::GetElementPtr: {
1167 // We don't combine GEPs with complicated (nested) indexing.
1168 for (unsigned j = 0; j < VL.size(); ++j) {
1169 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1170 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1171 BS.cancelScheduling(VL);
1172 newTreeEntry(VL, false);
1177 // We can't combine several GEPs into one vector if they operate on
1179 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1180 for (unsigned j = 0; j < VL.size(); ++j) {
1181 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1183 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1184 BS.cancelScheduling(VL);
1185 newTreeEntry(VL, false);
1190 // We don't combine GEPs with non-constant indexes.
1191 for (unsigned j = 0; j < VL.size(); ++j) {
1192 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1193 if (!isa<ConstantInt>(Op)) {
1195 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1196 BS.cancelScheduling(VL);
1197 newTreeEntry(VL, false);
1202 newTreeEntry(VL, true);
1203 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1204 for (unsigned i = 0, e = 2; i < e; ++i) {
1206 // Prepare the operand vector.
1207 for (unsigned j = 0; j < VL.size(); ++j)
1208 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1210 buildTree_rec(Operands, Depth + 1);
1214 case Instruction::Store: {
1215 // Check if the stores are consecutive or of we need to swizzle them.
1216 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1217 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1218 BS.cancelScheduling(VL);
1219 newTreeEntry(VL, false);
1220 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1224 newTreeEntry(VL, true);
1225 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1228 for (unsigned j = 0; j < VL.size(); ++j)
1229 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1231 buildTree_rec(Operands, Depth + 1);
1234 case Instruction::Call: {
1235 // Check if the calls are all to the same vectorizable intrinsic.
1236 CallInst *CI = cast<CallInst>(VL[0]);
1237 // Check if this is an Intrinsic call or something that can be
1238 // represented by an intrinsic call
1239 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1240 if (!isTriviallyVectorizable(ID)) {
1241 BS.cancelScheduling(VL);
1242 newTreeEntry(VL, false);
1243 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1246 Function *Int = CI->getCalledFunction();
1247 Value *A1I = nullptr;
1248 if (hasVectorInstrinsicScalarOpd(ID, 1))
1249 A1I = CI->getArgOperand(1);
1250 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1251 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1252 if (!CI2 || CI2->getCalledFunction() != Int ||
1253 getIntrinsicIDForCall(CI2, TLI) != ID) {
1254 BS.cancelScheduling(VL);
1255 newTreeEntry(VL, false);
1256 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1260 // ctlz,cttz and powi are special intrinsics whose second argument
1261 // should be same in order for them to be vectorized.
1262 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1263 Value *A1J = CI2->getArgOperand(1);
1265 BS.cancelScheduling(VL);
1266 newTreeEntry(VL, false);
1267 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1268 << " argument "<< A1I<<"!=" << A1J
1275 newTreeEntry(VL, true);
1276 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1278 // Prepare the operand vector.
1279 for (unsigned j = 0; j < VL.size(); ++j) {
1280 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1281 Operands.push_back(CI2->getArgOperand(i));
1283 buildTree_rec(Operands, Depth + 1);
1287 case Instruction::ShuffleVector: {
1288 // If this is not an alternate sequence of opcode like add-sub
1289 // then do not vectorize this instruction.
1290 if (!isAltShuffle) {
1291 BS.cancelScheduling(VL);
1292 newTreeEntry(VL, false);
1293 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1296 newTreeEntry(VL, true);
1297 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1298 for (unsigned i = 0, e = VL0->getNumOperands(); 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);
1309 BS.cancelScheduling(VL);
1310 newTreeEntry(VL, false);
1311 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1316 int BoUpSLP::getEntryCost(TreeEntry *E) {
1317 ArrayRef<Value*> VL = E->Scalars;
1319 Type *ScalarTy = VL[0]->getType();
1320 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1321 ScalarTy = SI->getValueOperand()->getType();
1322 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1324 if (E->NeedToGather) {
1325 if (allConstant(VL))
1328 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1330 return getGatherCost(E->Scalars);
1332 unsigned Opcode = getSameOpcode(VL);
1333 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1334 Instruction *VL0 = cast<Instruction>(VL[0]);
1336 case Instruction::PHI: {
1339 case Instruction::ExtractElement: {
1340 if (CanReuseExtract(VL)) {
1342 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1343 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1345 // Take credit for instruction that will become dead.
1347 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1351 return getGatherCost(VecTy);
1353 case Instruction::ZExt:
1354 case Instruction::SExt:
1355 case Instruction::FPToUI:
1356 case Instruction::FPToSI:
1357 case Instruction::FPExt:
1358 case Instruction::PtrToInt:
1359 case Instruction::IntToPtr:
1360 case Instruction::SIToFP:
1361 case Instruction::UIToFP:
1362 case Instruction::Trunc:
1363 case Instruction::FPTrunc:
1364 case Instruction::BitCast: {
1365 Type *SrcTy = VL0->getOperand(0)->getType();
1367 // Calculate the cost of this instruction.
1368 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1369 VL0->getType(), SrcTy);
1371 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1372 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1373 return VecCost - ScalarCost;
1375 case Instruction::FCmp:
1376 case Instruction::ICmp:
1377 case Instruction::Select:
1378 case Instruction::Add:
1379 case Instruction::FAdd:
1380 case Instruction::Sub:
1381 case Instruction::FSub:
1382 case Instruction::Mul:
1383 case Instruction::FMul:
1384 case Instruction::UDiv:
1385 case Instruction::SDiv:
1386 case Instruction::FDiv:
1387 case Instruction::URem:
1388 case Instruction::SRem:
1389 case Instruction::FRem:
1390 case Instruction::Shl:
1391 case Instruction::LShr:
1392 case Instruction::AShr:
1393 case Instruction::And:
1394 case Instruction::Or:
1395 case Instruction::Xor: {
1396 // Calculate the cost of this instruction.
1399 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1400 Opcode == Instruction::Select) {
1401 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1402 ScalarCost = VecTy->getNumElements() *
1403 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1404 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1406 // Certain instructions can be cheaper to vectorize if they have a
1407 // constant second vector operand.
1408 TargetTransformInfo::OperandValueKind Op1VK =
1409 TargetTransformInfo::OK_AnyValue;
1410 TargetTransformInfo::OperandValueKind Op2VK =
1411 TargetTransformInfo::OK_UniformConstantValue;
1413 // If all operands are exactly the same ConstantInt then set the
1414 // operand kind to OK_UniformConstantValue.
1415 // If instead not all operands are constants, then set the operand kind
1416 // to OK_AnyValue. If all operands are constants but not the same,
1417 // then set the operand kind to OK_NonUniformConstantValue.
1418 ConstantInt *CInt = nullptr;
1419 for (unsigned i = 0; i < VL.size(); ++i) {
1420 const Instruction *I = cast<Instruction>(VL[i]);
1421 if (!isa<ConstantInt>(I->getOperand(1))) {
1422 Op2VK = TargetTransformInfo::OK_AnyValue;
1426 CInt = cast<ConstantInt>(I->getOperand(1));
1429 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1430 CInt != cast<ConstantInt>(I->getOperand(1)))
1431 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1435 VecTy->getNumElements() *
1436 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1437 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1439 return VecCost - ScalarCost;
1441 case Instruction::GetElementPtr: {
1442 TargetTransformInfo::OperandValueKind Op1VK =
1443 TargetTransformInfo::OK_AnyValue;
1444 TargetTransformInfo::OperandValueKind Op2VK =
1445 TargetTransformInfo::OK_UniformConstantValue;
1448 VecTy->getNumElements() *
1449 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1451 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1453 return VecCost - ScalarCost;
1455 case Instruction::Load: {
1456 // Cost of wide load - cost of scalar loads.
1457 int ScalarLdCost = VecTy->getNumElements() *
1458 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1459 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1460 return VecLdCost - ScalarLdCost;
1462 case Instruction::Store: {
1463 // We know that we can merge the stores. Calculate the cost.
1464 int ScalarStCost = VecTy->getNumElements() *
1465 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1466 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1467 return VecStCost - ScalarStCost;
1469 case Instruction::Call: {
1470 CallInst *CI = cast<CallInst>(VL0);
1471 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1473 // Calculate the cost of the scalar and vector calls.
1474 SmallVector<Type*, 4> ScalarTys, VecTys;
1475 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1476 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1477 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1478 VecTy->getNumElements()));
1481 int ScalarCallCost = VecTy->getNumElements() *
1482 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1484 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1486 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1487 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1488 << " for " << *CI << "\n");
1490 return VecCallCost - ScalarCallCost;
1492 case Instruction::ShuffleVector: {
1493 TargetTransformInfo::OperandValueKind Op1VK =
1494 TargetTransformInfo::OK_AnyValue;
1495 TargetTransformInfo::OperandValueKind Op2VK =
1496 TargetTransformInfo::OK_AnyValue;
1499 for (unsigned i = 0; i < VL.size(); ++i) {
1500 Instruction *I = cast<Instruction>(VL[i]);
1504 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1506 // VecCost is equal to sum of the cost of creating 2 vectors
1507 // and the cost of creating shuffle.
1508 Instruction *I0 = cast<Instruction>(VL[0]);
1510 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1511 Instruction *I1 = cast<Instruction>(VL[1]);
1513 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1515 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1516 return VecCost - ScalarCost;
1519 llvm_unreachable("Unknown instruction");
1523 bool BoUpSLP::isFullyVectorizableTinyTree() {
1524 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1525 VectorizableTree.size() << " is fully vectorizable .\n");
1527 // We only handle trees of height 2.
1528 if (VectorizableTree.size() != 2)
1531 // Handle splat stores.
1532 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1535 // Gathering cost would be too much for tiny trees.
1536 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1542 int BoUpSLP::getTreeCost() {
1544 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1545 VectorizableTree.size() << ".\n");
1547 // We only vectorize tiny trees if it is fully vectorizable.
1548 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1549 if (!VectorizableTree.size()) {
1550 assert(!ExternalUses.size() && "We should not have any external users");
1555 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1557 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1558 int C = getEntryCost(&VectorizableTree[i]);
1559 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1560 << *VectorizableTree[i].Scalars[0] << " .\n");
1564 SmallSet<Value *, 16> ExtractCostCalculated;
1565 int ExtractCost = 0;
1566 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1568 // We only add extract cost once for the same scalar.
1569 if (!ExtractCostCalculated.insert(I->Scalar))
1572 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1573 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1577 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1578 return Cost + ExtractCost;
1581 int BoUpSLP::getGatherCost(Type *Ty) {
1583 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1584 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1588 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1589 // Find the type of the operands in VL.
1590 Type *ScalarTy = VL[0]->getType();
1591 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1592 ScalarTy = SI->getValueOperand()->getType();
1593 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1594 // Find the cost of inserting/extracting values from the vector.
1595 return getGatherCost(VecTy);
1598 Value *BoUpSLP::getPointerOperand(Value *I) {
1599 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1600 return LI->getPointerOperand();
1601 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1602 return SI->getPointerOperand();
1606 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1607 if (LoadInst *L = dyn_cast<LoadInst>(I))
1608 return L->getPointerAddressSpace();
1609 if (StoreInst *S = dyn_cast<StoreInst>(I))
1610 return S->getPointerAddressSpace();
1614 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1615 Value *PtrA = getPointerOperand(A);
1616 Value *PtrB = getPointerOperand(B);
1617 unsigned ASA = getAddressSpaceOperand(A);
1618 unsigned ASB = getAddressSpaceOperand(B);
1620 // Check that the address spaces match and that the pointers are valid.
1621 if (!PtrA || !PtrB || (ASA != ASB))
1624 // Make sure that A and B are different pointers of the same type.
1625 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1628 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1629 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1630 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1632 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1633 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1634 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1636 APInt OffsetDelta = OffsetB - OffsetA;
1638 // Check if they are based on the same pointer. That makes the offsets
1641 return OffsetDelta == Size;
1643 // Compute the necessary base pointer delta to have the necessary final delta
1644 // equal to the size.
1645 APInt BaseDelta = Size - OffsetDelta;
1647 // Otherwise compute the distance with SCEV between the base pointers.
1648 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1649 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1650 const SCEV *C = SE->getConstant(BaseDelta);
1651 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1652 return X == PtrSCEVB;
1655 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1656 Instruction *VL0 = cast<Instruction>(VL[0]);
1657 BasicBlock::iterator NextInst = VL0;
1659 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1660 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1663 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1664 Value *Vec = UndefValue::get(Ty);
1665 // Generate the 'InsertElement' instruction.
1666 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1667 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1668 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1669 GatherSeq.insert(Insrt);
1670 CSEBlocks.insert(Insrt->getParent());
1672 // Add to our 'need-to-extract' list.
1673 if (ScalarToTreeEntry.count(VL[i])) {
1674 int Idx = ScalarToTreeEntry[VL[i]];
1675 TreeEntry *E = &VectorizableTree[Idx];
1676 // Find which lane we need to extract.
1678 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1679 // Is this the lane of the scalar that we are looking for ?
1680 if (E->Scalars[Lane] == VL[i]) {
1685 assert(FoundLane >= 0 && "Could not find the correct lane");
1686 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1694 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1695 SmallDenseMap<Value*, int>::const_iterator Entry
1696 = ScalarToTreeEntry.find(VL[0]);
1697 if (Entry != ScalarToTreeEntry.end()) {
1698 int Idx = Entry->second;
1699 const TreeEntry *En = &VectorizableTree[Idx];
1700 if (En->isSame(VL) && En->VectorizedValue)
1701 return En->VectorizedValue;
1706 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1707 if (ScalarToTreeEntry.count(VL[0])) {
1708 int Idx = ScalarToTreeEntry[VL[0]];
1709 TreeEntry *E = &VectorizableTree[Idx];
1711 return vectorizeTree(E);
1714 Type *ScalarTy = VL[0]->getType();
1715 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1716 ScalarTy = SI->getValueOperand()->getType();
1717 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1719 return Gather(VL, VecTy);
1722 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1723 IRBuilder<>::InsertPointGuard Guard(Builder);
1725 if (E->VectorizedValue) {
1726 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1727 return E->VectorizedValue;
1730 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1731 Type *ScalarTy = VL0->getType();
1732 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1733 ScalarTy = SI->getValueOperand()->getType();
1734 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1736 if (E->NeedToGather) {
1737 setInsertPointAfterBundle(E->Scalars);
1738 return Gather(E->Scalars, VecTy);
1740 BasicBlock *BB = VL0->getParent();
1743 unsigned Opcode = getSameOpcode(E->Scalars);
1746 case Instruction::PHI: {
1747 PHINode *PH = dyn_cast<PHINode>(VL0);
1748 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1749 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1750 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1751 E->VectorizedValue = NewPhi;
1753 // PHINodes may have multiple entries from the same block. We want to
1754 // visit every block once.
1755 SmallSet<BasicBlock*, 4> VisitedBBs;
1757 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1759 BasicBlock *IBB = PH->getIncomingBlock(i);
1761 if (!VisitedBBs.insert(IBB)) {
1762 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1766 // Prepare the operand vector.
1767 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1768 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1769 getIncomingValueForBlock(IBB));
1771 Builder.SetInsertPoint(IBB->getTerminator());
1772 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1773 Value *Vec = vectorizeTree(Operands);
1774 NewPhi->addIncoming(Vec, IBB);
1777 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1778 "Invalid number of incoming values");
1782 case Instruction::ExtractElement: {
1783 if (CanReuseExtract(E->Scalars)) {
1784 Value *V = VL0->getOperand(0);
1785 E->VectorizedValue = V;
1788 return Gather(E->Scalars, VecTy);
1790 case Instruction::ZExt:
1791 case Instruction::SExt:
1792 case Instruction::FPToUI:
1793 case Instruction::FPToSI:
1794 case Instruction::FPExt:
1795 case Instruction::PtrToInt:
1796 case Instruction::IntToPtr:
1797 case Instruction::SIToFP:
1798 case Instruction::UIToFP:
1799 case Instruction::Trunc:
1800 case Instruction::FPTrunc:
1801 case Instruction::BitCast: {
1803 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1804 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1806 setInsertPointAfterBundle(E->Scalars);
1808 Value *InVec = vectorizeTree(INVL);
1810 if (Value *V = alreadyVectorized(E->Scalars))
1813 CastInst *CI = dyn_cast<CastInst>(VL0);
1814 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1815 E->VectorizedValue = V;
1816 ++NumVectorInstructions;
1819 case Instruction::FCmp:
1820 case Instruction::ICmp: {
1821 ValueList LHSV, RHSV;
1822 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1823 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1824 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1827 setInsertPointAfterBundle(E->Scalars);
1829 Value *L = vectorizeTree(LHSV);
1830 Value *R = vectorizeTree(RHSV);
1832 if (Value *V = alreadyVectorized(E->Scalars))
1835 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1837 if (Opcode == Instruction::FCmp)
1838 V = Builder.CreateFCmp(P0, L, R);
1840 V = Builder.CreateICmp(P0, L, R);
1842 E->VectorizedValue = V;
1843 ++NumVectorInstructions;
1846 case Instruction::Select: {
1847 ValueList TrueVec, FalseVec, CondVec;
1848 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1849 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1850 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1851 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1854 setInsertPointAfterBundle(E->Scalars);
1856 Value *Cond = vectorizeTree(CondVec);
1857 Value *True = vectorizeTree(TrueVec);
1858 Value *False = vectorizeTree(FalseVec);
1860 if (Value *V = alreadyVectorized(E->Scalars))
1863 Value *V = Builder.CreateSelect(Cond, True, False);
1864 E->VectorizedValue = V;
1865 ++NumVectorInstructions;
1868 case Instruction::Add:
1869 case Instruction::FAdd:
1870 case Instruction::Sub:
1871 case Instruction::FSub:
1872 case Instruction::Mul:
1873 case Instruction::FMul:
1874 case Instruction::UDiv:
1875 case Instruction::SDiv:
1876 case Instruction::FDiv:
1877 case Instruction::URem:
1878 case Instruction::SRem:
1879 case Instruction::FRem:
1880 case Instruction::Shl:
1881 case Instruction::LShr:
1882 case Instruction::AShr:
1883 case Instruction::And:
1884 case Instruction::Or:
1885 case Instruction::Xor: {
1886 ValueList LHSVL, RHSVL;
1887 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1888 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1890 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1891 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1892 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1895 setInsertPointAfterBundle(E->Scalars);
1897 Value *LHS = vectorizeTree(LHSVL);
1898 Value *RHS = vectorizeTree(RHSVL);
1900 if (LHS == RHS && isa<Instruction>(LHS)) {
1901 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1904 if (Value *V = alreadyVectorized(E->Scalars))
1907 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1908 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1909 E->VectorizedValue = V;
1910 ++NumVectorInstructions;
1912 if (Instruction *I = dyn_cast<Instruction>(V))
1913 return propagateMetadata(I, E->Scalars);
1917 case Instruction::Load: {
1918 // Loads are inserted at the head of the tree because we don't want to
1919 // sink them all the way down past store instructions.
1920 setInsertPointAfterBundle(E->Scalars);
1922 LoadInst *LI = cast<LoadInst>(VL0);
1923 unsigned AS = LI->getPointerAddressSpace();
1925 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1926 VecTy->getPointerTo(AS));
1927 unsigned Alignment = LI->getAlignment();
1928 LI = Builder.CreateLoad(VecPtr);
1930 Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
1931 LI->setAlignment(Alignment);
1932 E->VectorizedValue = LI;
1933 ++NumVectorInstructions;
1934 return propagateMetadata(LI, E->Scalars);
1936 case Instruction::Store: {
1937 StoreInst *SI = cast<StoreInst>(VL0);
1938 unsigned Alignment = SI->getAlignment();
1939 unsigned AS = SI->getPointerAddressSpace();
1942 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1943 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1945 setInsertPointAfterBundle(E->Scalars);
1947 Value *VecValue = vectorizeTree(ValueOp);
1948 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1949 VecTy->getPointerTo(AS));
1950 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1952 Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
1953 S->setAlignment(Alignment);
1954 E->VectorizedValue = S;
1955 ++NumVectorInstructions;
1956 return propagateMetadata(S, E->Scalars);
1958 case Instruction::GetElementPtr: {
1959 setInsertPointAfterBundle(E->Scalars);
1962 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1963 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
1965 Value *Op0 = vectorizeTree(Op0VL);
1967 std::vector<Value *> OpVecs;
1968 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
1971 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1972 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
1974 Value *OpVec = vectorizeTree(OpVL);
1975 OpVecs.push_back(OpVec);
1978 Value *V = Builder.CreateGEP(Op0, OpVecs);
1979 E->VectorizedValue = V;
1980 ++NumVectorInstructions;
1982 if (Instruction *I = dyn_cast<Instruction>(V))
1983 return propagateMetadata(I, E->Scalars);
1987 case Instruction::Call: {
1988 CallInst *CI = cast<CallInst>(VL0);
1989 setInsertPointAfterBundle(E->Scalars);
1991 Intrinsic::ID IID = Intrinsic::not_intrinsic;
1992 if (CI && (FI = CI->getCalledFunction())) {
1993 IID = (Intrinsic::ID) FI->getIntrinsicID();
1995 std::vector<Value *> OpVecs;
1996 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1998 // ctlz,cttz and powi are special intrinsics whose second argument is
1999 // a scalar. This argument should not be vectorized.
2000 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2001 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2002 OpVecs.push_back(CEI->getArgOperand(j));
2005 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2006 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2007 OpVL.push_back(CEI->getArgOperand(j));
2010 Value *OpVec = vectorizeTree(OpVL);
2011 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2012 OpVecs.push_back(OpVec);
2015 Module *M = F->getParent();
2016 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2017 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2018 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2019 Value *V = Builder.CreateCall(CF, OpVecs);
2020 E->VectorizedValue = V;
2021 ++NumVectorInstructions;
2024 case Instruction::ShuffleVector: {
2025 ValueList LHSVL, RHSVL;
2026 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2027 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2028 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2030 setInsertPointAfterBundle(E->Scalars);
2032 Value *LHS = vectorizeTree(LHSVL);
2033 Value *RHS = vectorizeTree(RHSVL);
2035 if (Value *V = alreadyVectorized(E->Scalars))
2038 // Create a vector of LHS op1 RHS
2039 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2040 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2042 // Create a vector of LHS op2 RHS
2043 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2044 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2045 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2047 // Create appropriate shuffle to take alternative operations from
2049 std::vector<Constant *> Mask(E->Scalars.size());
2050 unsigned e = E->Scalars.size();
2051 for (unsigned i = 0; i < e; ++i) {
2053 Mask[i] = Builder.getInt32(e + i);
2055 Mask[i] = Builder.getInt32(i);
2058 Value *ShuffleMask = ConstantVector::get(Mask);
2060 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2061 E->VectorizedValue = V;
2062 ++NumVectorInstructions;
2063 if (Instruction *I = dyn_cast<Instruction>(V))
2064 return propagateMetadata(I, E->Scalars);
2069 llvm_unreachable("unknown inst");
2074 Value *BoUpSLP::vectorizeTree() {
2075 Builder.SetInsertPoint(F->getEntryBlock().begin());
2076 vectorizeTree(&VectorizableTree[0]);
2078 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2080 // Extract all of the elements with the external uses.
2081 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2083 Value *Scalar = it->Scalar;
2084 llvm::User *User = it->User;
2086 // Skip users that we already RAUW. This happens when one instruction
2087 // has multiple uses of the same value.
2088 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2091 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2093 int Idx = ScalarToTreeEntry[Scalar];
2094 TreeEntry *E = &VectorizableTree[Idx];
2095 assert(!E->NeedToGather && "Extracting from a gather list");
2097 Value *Vec = E->VectorizedValue;
2098 assert(Vec && "Can't find vectorizable value");
2100 Value *Lane = Builder.getInt32(it->Lane);
2101 // Generate extracts for out-of-tree users.
2102 // Find the insertion point for the extractelement lane.
2103 if (isa<Instruction>(Vec)){
2104 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2105 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2106 if (PH->getIncomingValue(i) == Scalar) {
2107 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2108 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2109 CSEBlocks.insert(PH->getIncomingBlock(i));
2110 PH->setOperand(i, Ex);
2114 Builder.SetInsertPoint(cast<Instruction>(User));
2115 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2116 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2117 User->replaceUsesOfWith(Scalar, Ex);
2120 Builder.SetInsertPoint(F->getEntryBlock().begin());
2121 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2122 CSEBlocks.insert(&F->getEntryBlock());
2123 User->replaceUsesOfWith(Scalar, Ex);
2126 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2129 // For each vectorized value:
2130 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2131 TreeEntry *Entry = &VectorizableTree[EIdx];
2134 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2135 Value *Scalar = Entry->Scalars[Lane];
2136 // No need to handle users of gathered values.
2137 if (Entry->NeedToGather)
2140 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2142 Type *Ty = Scalar->getType();
2143 if (!Ty->isVoidTy()) {
2145 for (User *U : Scalar->users()) {
2146 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2148 assert((ScalarToTreeEntry.count(U) ||
2149 // It is legal to replace users in the ignorelist by undef.
2150 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2151 UserIgnoreList.end())) &&
2152 "Replacing out-of-tree value with undef");
2155 Value *Undef = UndefValue::get(Ty);
2156 Scalar->replaceAllUsesWith(Undef);
2158 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2159 cast<Instruction>(Scalar)->eraseFromParent();
2163 Builder.ClearInsertionPoint();
2165 return VectorizableTree[0].VectorizedValue;
2168 void BoUpSLP::optimizeGatherSequence() {
2169 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2170 << " gather sequences instructions.\n");
2171 // LICM InsertElementInst sequences.
2172 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2173 e = GatherSeq.end(); it != e; ++it) {
2174 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2179 // Check if this block is inside a loop.
2180 Loop *L = LI->getLoopFor(Insert->getParent());
2184 // Check if it has a preheader.
2185 BasicBlock *PreHeader = L->getLoopPreheader();
2189 // If the vector or the element that we insert into it are
2190 // instructions that are defined in this basic block then we can't
2191 // hoist this instruction.
2192 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2193 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2194 if (CurrVec && L->contains(CurrVec))
2196 if (NewElem && L->contains(NewElem))
2199 // We can hoist this instruction. Move it to the pre-header.
2200 Insert->moveBefore(PreHeader->getTerminator());
2203 // Make a list of all reachable blocks in our CSE queue.
2204 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2205 CSEWorkList.reserve(CSEBlocks.size());
2206 for (BasicBlock *BB : CSEBlocks)
2207 if (DomTreeNode *N = DT->getNode(BB)) {
2208 assert(DT->isReachableFromEntry(N));
2209 CSEWorkList.push_back(N);
2212 // Sort blocks by domination. This ensures we visit a block after all blocks
2213 // dominating it are visited.
2214 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2215 [this](const DomTreeNode *A, const DomTreeNode *B) {
2216 return DT->properlyDominates(A, B);
2219 // Perform O(N^2) search over the gather sequences and merge identical
2220 // instructions. TODO: We can further optimize this scan if we split the
2221 // instructions into different buckets based on the insert lane.
2222 SmallVector<Instruction *, 16> Visited;
2223 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2224 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2225 "Worklist not sorted properly!");
2226 BasicBlock *BB = (*I)->getBlock();
2227 // For all instructions in blocks containing gather sequences:
2228 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2229 Instruction *In = it++;
2230 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2233 // Check if we can replace this instruction with any of the
2234 // visited instructions.
2235 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2238 if (In->isIdenticalTo(*v) &&
2239 DT->dominates((*v)->getParent(), In->getParent())) {
2240 In->replaceAllUsesWith(*v);
2241 In->eraseFromParent();
2247 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2248 Visited.push_back(In);
2256 // Groups the instructions to a bundle (which is then a single scheduling entity)
2257 // and schedules instructions until the bundle gets ready.
2258 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2259 AliasAnalysis *AA) {
2260 if (isa<PHINode>(VL[0]))
2263 // Initialize the instruction bundle.
2264 Instruction *OldScheduleEnd = ScheduleEnd;
2265 ScheduleData *PrevInBundle = nullptr;
2266 ScheduleData *Bundle = nullptr;
2267 bool ReSchedule = false;
2268 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2269 for (Value *V : VL) {
2270 extendSchedulingRegion(V);
2271 ScheduleData *BundleMember = getScheduleData(V);
2272 assert(BundleMember &&
2273 "no ScheduleData for bundle member (maybe not in same basic block)");
2274 if (BundleMember->IsScheduled) {
2275 // A bundle member was scheduled as single instruction before and now
2276 // needs to be scheduled as part of the bundle. We just get rid of the
2277 // existing schedule.
2278 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2279 << " was already scheduled\n");
2282 assert(BundleMember->isSchedulingEntity() &&
2283 "bundle member already part of other bundle");
2285 PrevInBundle->NextInBundle = BundleMember;
2287 Bundle = BundleMember;
2289 BundleMember->UnscheduledDepsInBundle = 0;
2290 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2292 // Group the instructions to a bundle.
2293 BundleMember->FirstInBundle = Bundle;
2294 PrevInBundle = BundleMember;
2296 if (ScheduleEnd != OldScheduleEnd) {
2297 // The scheduling region got new instructions at the lower end (or it is a
2298 // new region for the first bundle). This makes it necessary to
2299 // recalculate all dependencies.
2300 // It is seldom that this needs to be done a second time after adding the
2301 // initial bundle to the region.
2302 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2303 ScheduleData *SD = getScheduleData(I);
2304 SD->clearDependencies();
2310 initialFillReadyList(ReadyInsts);
2313 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2314 << BB->getName() << "\n");
2316 calculateDependencies(Bundle, true, AA);
2318 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2319 // means that there are no cyclic dependencies and we can schedule it.
2320 // Note that's important that we don't "schedule" the bundle yet (see
2321 // cancelScheduling).
2322 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2324 ScheduleData *pickedSD = ReadyInsts.back();
2325 ReadyInsts.pop_back();
2327 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2328 schedule(pickedSD, ReadyInsts);
2331 return Bundle->isReady();
2334 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2335 if (isa<PHINode>(VL[0]))
2338 ScheduleData *Bundle = getScheduleData(VL[0]);
2339 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2340 assert(!Bundle->IsScheduled &&
2341 "Can't cancel bundle which is already scheduled");
2342 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2343 "tried to unbundle something which is not a bundle");
2345 // Un-bundle: make single instructions out of the bundle.
2346 ScheduleData *BundleMember = Bundle;
2347 while (BundleMember) {
2348 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2349 BundleMember->FirstInBundle = BundleMember;
2350 ScheduleData *Next = BundleMember->NextInBundle;
2351 BundleMember->NextInBundle = nullptr;
2352 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2353 if (BundleMember->UnscheduledDepsInBundle == 0) {
2354 ReadyInsts.insert(BundleMember);
2356 BundleMember = Next;
2360 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2361 if (getScheduleData(V))
2363 Instruction *I = dyn_cast<Instruction>(V);
2364 assert(I && "bundle member must be an instruction");
2365 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2366 if (!ScheduleStart) {
2367 // It's the first instruction in the new region.
2368 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2370 ScheduleEnd = I->getNextNode();
2371 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2372 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2375 // Search up and down at the same time, because we don't know if the new
2376 // instruction is above or below the existing scheduling region.
2377 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2378 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2379 BasicBlock::iterator DownIter(ScheduleEnd);
2380 BasicBlock::iterator LowerEnd = BB->end();
2382 if (UpIter != UpperEnd) {
2383 if (&*UpIter == I) {
2384 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2386 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2391 if (DownIter != LowerEnd) {
2392 if (&*DownIter == I) {
2393 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2395 ScheduleEnd = I->getNextNode();
2396 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2397 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2402 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2403 "instruction not found in block");
2407 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2409 ScheduleData *PrevLoadStore,
2410 ScheduleData *NextLoadStore) {
2411 ScheduleData *CurrentLoadStore = PrevLoadStore;
2412 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2413 ScheduleData *SD = ScheduleDataMap[I];
2415 // Allocate a new ScheduleData for the instruction.
2416 if (ChunkPos >= ChunkSize) {
2417 ScheduleDataChunks.push_back(
2418 llvm::make_unique<ScheduleData[]>(ChunkSize));
2421 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2422 ScheduleDataMap[I] = SD;
2425 assert(!isInSchedulingRegion(SD) &&
2426 "new ScheduleData already in scheduling region");
2427 SD->init(SchedulingRegionID);
2429 if (I->mayReadOrWriteMemory()) {
2430 // Update the linked list of memory accessing instructions.
2431 if (CurrentLoadStore) {
2432 CurrentLoadStore->NextLoadStore = SD;
2434 FirstLoadStoreInRegion = SD;
2436 CurrentLoadStore = SD;
2439 if (NextLoadStore) {
2440 if (CurrentLoadStore)
2441 CurrentLoadStore->NextLoadStore = NextLoadStore;
2443 LastLoadStoreInRegion = CurrentLoadStore;
2447 /// \returns the AA location that is being access by the instruction.
2448 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
2449 if (StoreInst *SI = dyn_cast<StoreInst>(I))
2450 return AA->getLocation(SI);
2451 if (LoadInst *LI = dyn_cast<LoadInst>(I))
2452 return AA->getLocation(LI);
2453 return AliasAnalysis::Location();
2456 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2457 bool InsertInReadyList,
2458 AliasAnalysis *AA) {
2459 assert(SD->isSchedulingEntity());
2461 SmallVector<ScheduleData *, 10> WorkList;
2462 WorkList.push_back(SD);
2464 while (!WorkList.empty()) {
2465 ScheduleData *SD = WorkList.back();
2466 WorkList.pop_back();
2468 ScheduleData *BundleMember = SD;
2469 while (BundleMember) {
2470 assert(isInSchedulingRegion(BundleMember));
2471 if (!BundleMember->hasValidDependencies()) {
2473 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2474 BundleMember->Dependencies = 0;
2475 BundleMember->resetUnscheduledDeps();
2477 // Handle def-use chain dependencies.
2478 for (User *U : BundleMember->Inst->users()) {
2479 if (isa<Instruction>(U)) {
2480 ScheduleData *UseSD = getScheduleData(U);
2481 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2482 BundleMember->Dependencies++;
2483 ScheduleData *DestBundle = UseSD->FirstInBundle;
2484 if (!DestBundle->IsScheduled) {
2485 BundleMember->incrementUnscheduledDeps(1);
2487 if (!DestBundle->hasValidDependencies()) {
2488 WorkList.push_back(DestBundle);
2492 // I'm not sure if this can ever happen. But we need to be safe.
2493 // This lets the instruction/bundle never be scheduled and eventally
2494 // disable vectorization.
2495 BundleMember->Dependencies++;
2496 BundleMember->incrementUnscheduledDeps(1);
2500 // Handle the memory dependencies.
2501 ScheduleData *DepDest = BundleMember->NextLoadStore;
2503 AliasAnalysis::Location SrcLoc = getLocation(BundleMember->Inst, AA);
2504 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2507 assert(isInSchedulingRegion(DepDest));
2508 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2509 AliasAnalysis::Location DstLoc = getLocation(DepDest->Inst, AA);
2510 if (!SrcLoc.Ptr || !DstLoc.Ptr || AA->alias(SrcLoc, DstLoc)) {
2511 DepDest->MemoryDependencies.push_back(BundleMember);
2512 BundleMember->Dependencies++;
2513 ScheduleData *DestBundle = DepDest->FirstInBundle;
2514 if (!DestBundle->IsScheduled) {
2515 BundleMember->incrementUnscheduledDeps(1);
2517 if (!DestBundle->hasValidDependencies()) {
2518 WorkList.push_back(DestBundle);
2522 DepDest = DepDest->NextLoadStore;
2526 BundleMember = BundleMember->NextInBundle;
2528 if (InsertInReadyList && SD->isReady()) {
2529 ReadyInsts.push_back(SD);
2530 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2535 void BoUpSLP::BlockScheduling::resetSchedule() {
2536 assert(ScheduleStart &&
2537 "tried to reset schedule on block which has not been scheduled");
2538 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2539 ScheduleData *SD = getScheduleData(I);
2540 assert(isInSchedulingRegion(SD));
2541 SD->IsScheduled = false;
2542 SD->resetUnscheduledDeps();
2547 void BoUpSLP::scheduleBlock(BasicBlock *BB) {
2548 DEBUG(dbgs() << "SLP: schedule block " << BB->getName() << "\n");
2550 BlockScheduling *BS = BlocksSchedules[BB].get();
2551 if (!BS || !BS->ScheduleStart)
2554 BS->resetSchedule();
2556 // For the real scheduling we use a more sophisticated ready-list: it is
2557 // sorted by the original instruction location. This lets the final schedule
2558 // be as close as possible to the original instruction order.
2559 struct ScheduleDataCompare {
2560 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2561 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2564 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2566 // Ensure that all depencency data is updated and fill the ready-list with
2567 // initial instructions.
2569 int NumToSchedule = 0;
2570 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2571 I = I->getNextNode()) {
2572 ScheduleData *SD = BS->getScheduleData(I);
2574 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2575 "scheduler and vectorizer have different opinion on what is a bundle");
2576 SD->FirstInBundle->SchedulingPriority = Idx++;
2577 if (SD->isSchedulingEntity()) {
2578 BS->calculateDependencies(SD, false, AA);
2582 BS->initialFillReadyList(ReadyInsts);
2584 Instruction *LastScheduledInst = BS->ScheduleEnd;
2586 // Do the "real" scheduling.
2587 while (!ReadyInsts.empty()) {
2588 ScheduleData *picked = *ReadyInsts.begin();
2589 ReadyInsts.erase(ReadyInsts.begin());
2591 // Move the scheduled instruction(s) to their dedicated places, if not
2593 ScheduleData *BundleMember = picked;
2594 while (BundleMember) {
2595 Instruction *pickedInst = BundleMember->Inst;
2596 if (LastScheduledInst->getNextNode() != pickedInst) {
2597 BB->getInstList().remove(pickedInst);
2598 BB->getInstList().insert(LastScheduledInst, pickedInst);
2600 LastScheduledInst = pickedInst;
2601 BundleMember = BundleMember->NextInBundle;
2604 BS->schedule(picked, ReadyInsts);
2607 assert(NumToSchedule == 0 && "could not schedule all instructions");
2609 // Avoid duplicate scheduling of the block.
2610 BS->ScheduleStart = nullptr;
2613 /// The SLPVectorizer Pass.
2614 struct SLPVectorizer : public FunctionPass {
2615 typedef SmallVector<StoreInst *, 8> StoreList;
2616 typedef MapVector<Value *, StoreList> StoreListMap;
2618 /// Pass identification, replacement for typeid
2621 explicit SLPVectorizer() : FunctionPass(ID) {
2622 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2625 ScalarEvolution *SE;
2626 const DataLayout *DL;
2627 TargetTransformInfo *TTI;
2628 TargetLibraryInfo *TLI;
2633 bool runOnFunction(Function &F) override {
2634 if (skipOptnoneFunction(F))
2637 SE = &getAnalysis<ScalarEvolution>();
2638 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2639 DL = DLP ? &DLP->getDataLayout() : nullptr;
2640 TTI = &getAnalysis<TargetTransformInfo>();
2641 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2642 AA = &getAnalysis<AliasAnalysis>();
2643 LI = &getAnalysis<LoopInfo>();
2644 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2647 bool Changed = false;
2649 // If the target claims to have no vector registers don't attempt
2651 if (!TTI->getNumberOfRegisters(true))
2654 // Must have DataLayout. We can't require it because some tests run w/o
2659 // Don't vectorize when the attribute NoImplicitFloat is used.
2660 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2663 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2665 // Use the bottom up slp vectorizer to construct chains that start with
2666 // store instructions.
2667 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2669 // Scan the blocks in the function in post order.
2670 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2671 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2672 BasicBlock *BB = *it;
2673 // Vectorize trees that end at stores.
2674 if (unsigned count = collectStores(BB, R)) {
2676 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2677 Changed |= vectorizeStoreChains(R);
2680 // Vectorize trees that end at reductions.
2681 Changed |= vectorizeChainsInBlock(BB, R);
2685 R.optimizeGatherSequence();
2686 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2687 DEBUG(verifyFunction(F));
2692 void getAnalysisUsage(AnalysisUsage &AU) const override {
2693 FunctionPass::getAnalysisUsage(AU);
2694 AU.addRequired<ScalarEvolution>();
2695 AU.addRequired<AliasAnalysis>();
2696 AU.addRequired<TargetTransformInfo>();
2697 AU.addRequired<LoopInfo>();
2698 AU.addRequired<DominatorTreeWrapperPass>();
2699 AU.addPreserved<LoopInfo>();
2700 AU.addPreserved<DominatorTreeWrapperPass>();
2701 AU.setPreservesCFG();
2706 /// \brief Collect memory references and sort them according to their base
2707 /// object. We sort the stores to their base objects to reduce the cost of the
2708 /// quadratic search on the stores. TODO: We can further reduce this cost
2709 /// if we flush the chain creation every time we run into a memory barrier.
2710 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2712 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2713 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2715 /// \brief Try to vectorize a list of operands.
2716 /// \@param BuildVector A list of users to ignore for the purpose of
2717 /// scheduling and that don't need extracting.
2718 /// \returns true if a value was vectorized.
2719 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2720 ArrayRef<Value *> BuildVector = None,
2721 bool allowReorder = false);
2723 /// \brief Try to vectorize a chain that may start at the operands of \V;
2724 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2726 /// \brief Vectorize the stores that were collected in StoreRefs.
2727 bool vectorizeStoreChains(BoUpSLP &R);
2729 /// \brief Scan the basic block and look for patterns that are likely to start
2730 /// a vectorization chain.
2731 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2733 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2736 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2739 StoreListMap StoreRefs;
2742 /// \brief Check that the Values in the slice in VL array are still existent in
2743 /// the WeakVH array.
2744 /// Vectorization of part of the VL array may cause later values in the VL array
2745 /// to become invalid. We track when this has happened in the WeakVH array.
2746 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2747 SmallVectorImpl<WeakVH> &VH,
2748 unsigned SliceBegin,
2749 unsigned SliceSize) {
2750 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2757 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2758 int CostThreshold, BoUpSLP &R) {
2759 unsigned ChainLen = Chain.size();
2760 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2762 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2763 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2764 unsigned VF = MinVecRegSize / Sz;
2766 if (!isPowerOf2_32(Sz) || VF < 2)
2769 // Keep track of values that were deleted by vectorizing in the loop below.
2770 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2772 bool Changed = false;
2773 // Look for profitable vectorizable trees at all offsets, starting at zero.
2774 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2778 // Check that a previous iteration of this loop did not delete the Value.
2779 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2782 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2784 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2786 R.buildTree(Operands);
2788 int Cost = R.getTreeCost();
2790 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2791 if (Cost < CostThreshold) {
2792 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2795 // Move to the next bundle.
2804 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2805 int costThreshold, BoUpSLP &R) {
2806 SetVector<Value *> Heads, Tails;
2807 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2809 // We may run into multiple chains that merge into a single chain. We mark the
2810 // stores that we vectorized so that we don't visit the same store twice.
2811 BoUpSLP::ValueSet VectorizedStores;
2812 bool Changed = false;
2814 // Do a quadratic search on all of the given stores and find
2815 // all of the pairs of stores that follow each other.
2816 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2817 for (unsigned j = 0; j < e; ++j) {
2821 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2822 Tails.insert(Stores[j]);
2823 Heads.insert(Stores[i]);
2824 ConsecutiveChain[Stores[i]] = Stores[j];
2829 // For stores that start but don't end a link in the chain:
2830 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2832 if (Tails.count(*it))
2835 // We found a store instr that starts a chain. Now follow the chain and try
2837 BoUpSLP::ValueList Operands;
2839 // Collect the chain into a list.
2840 while (Tails.count(I) || Heads.count(I)) {
2841 if (VectorizedStores.count(I))
2843 Operands.push_back(I);
2844 // Move to the next value in the chain.
2845 I = ConsecutiveChain[I];
2848 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2850 // Mark the vectorized stores so that we don't vectorize them again.
2852 VectorizedStores.insert(Operands.begin(), Operands.end());
2853 Changed |= Vectorized;
2860 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2863 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2864 StoreInst *SI = dyn_cast<StoreInst>(it);
2868 // Don't touch volatile stores.
2869 if (!SI->isSimple())
2872 // Check that the pointer points to scalars.
2873 Type *Ty = SI->getValueOperand()->getType();
2874 if (Ty->isAggregateType() || Ty->isVectorTy())
2877 // Find the base pointer.
2878 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2880 // Save the store locations.
2881 StoreRefs[Ptr].push_back(SI);
2887 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2890 Value *VL[] = { A, B };
2891 return tryToVectorizeList(VL, R, None, true);
2894 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2895 ArrayRef<Value *> BuildVector,
2896 bool allowReorder) {
2900 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2902 // Check that all of the parts are scalar instructions of the same type.
2903 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2907 unsigned Opcode0 = I0->getOpcode();
2909 Type *Ty0 = I0->getType();
2910 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2911 unsigned VF = MinVecRegSize / Sz;
2913 for (int i = 0, e = VL.size(); i < e; ++i) {
2914 Type *Ty = VL[i]->getType();
2915 if (Ty->isAggregateType() || Ty->isVectorTy())
2917 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2918 if (!Inst || Inst->getOpcode() != Opcode0)
2922 bool Changed = false;
2924 // Keep track of values that were deleted by vectorizing in the loop below.
2925 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2927 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2928 unsigned OpsWidth = 0;
2935 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2938 // Check that a previous iteration of this loop did not delete the Value.
2939 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2942 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2944 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2946 ArrayRef<Value *> BuildVectorSlice;
2947 if (!BuildVector.empty())
2948 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2950 R.buildTree(Ops, BuildVectorSlice);
2951 // TODO: check if we can allow reordering also for other cases than
2952 // tryToVectorizePair()
2953 if (allowReorder && R.shouldReorder()) {
2954 assert(Ops.size() == 2);
2955 assert(BuildVectorSlice.empty());
2956 Value *ReorderedOps[] = { Ops[1], Ops[0] };
2957 R.buildTree(ReorderedOps, None);
2959 int Cost = R.getTreeCost();
2961 if (Cost < -SLPCostThreshold) {
2962 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2963 Value *VectorizedRoot = R.vectorizeTree();
2965 // Reconstruct the build vector by extracting the vectorized root. This
2966 // way we handle the case where some elements of the vector are undefined.
2967 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2968 if (!BuildVectorSlice.empty()) {
2969 // The insert point is the last build vector instruction. The vectorized
2970 // root will precede it. This guarantees that we get an instruction. The
2971 // vectorized tree could have been constant folded.
2972 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2973 unsigned VecIdx = 0;
2974 for (auto &V : BuildVectorSlice) {
2975 IRBuilder<true, NoFolder> Builder(
2976 ++BasicBlock::iterator(InsertAfter));
2977 InsertElementInst *IE = cast<InsertElementInst>(V);
2978 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2979 VectorizedRoot, Builder.getInt32(VecIdx++)));
2980 IE->setOperand(1, Extract);
2981 IE->removeFromParent();
2982 IE->insertAfter(Extract);
2986 // Move to the next bundle.
2995 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2999 // Try to vectorize V.
3000 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3003 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3004 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3006 if (B && B->hasOneUse()) {
3007 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3008 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3009 if (tryToVectorizePair(A, B0, R)) {
3013 if (tryToVectorizePair(A, B1, R)) {
3020 if (A && A->hasOneUse()) {
3021 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3022 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3023 if (tryToVectorizePair(A0, B, R)) {
3027 if (tryToVectorizePair(A1, B, R)) {
3035 /// \brief Generate a shuffle mask to be used in a reduction tree.
3037 /// \param VecLen The length of the vector to be reduced.
3038 /// \param NumEltsToRdx The number of elements that should be reduced in the
3040 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3041 /// reduction. A pairwise reduction will generate a mask of
3042 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3043 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3044 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3045 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3046 bool IsPairwise, bool IsLeft,
3047 IRBuilder<> &Builder) {
3048 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3050 SmallVector<Constant *, 32> ShuffleMask(
3051 VecLen, UndefValue::get(Builder.getInt32Ty()));
3054 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3055 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3056 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3058 // Move the upper half of the vector to the lower half.
3059 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3060 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3062 return ConstantVector::get(ShuffleMask);
3066 /// Model horizontal reductions.
3068 /// A horizontal reduction is a tree of reduction operations (currently add and
3069 /// fadd) that has operations that can be put into a vector as its leaf.
3070 /// For example, this tree:
3077 /// This tree has "mul" as its reduced values and "+" as its reduction
3078 /// operations. A reduction might be feeding into a store or a binary operation
3093 class HorizontalReduction {
3094 SmallVector<Value *, 16> ReductionOps;
3095 SmallVector<Value *, 32> ReducedVals;
3097 BinaryOperator *ReductionRoot;
3098 PHINode *ReductionPHI;
3100 /// The opcode of the reduction.
3101 unsigned ReductionOpcode;
3102 /// The opcode of the values we perform a reduction on.
3103 unsigned ReducedValueOpcode;
3104 /// The width of one full horizontal reduction operation.
3105 unsigned ReduxWidth;
3106 /// Should we model this reduction as a pairwise reduction tree or a tree that
3107 /// splits the vector in halves and adds those halves.
3108 bool IsPairwiseReduction;
3111 HorizontalReduction()
3112 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3113 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3115 /// \brief Try to find a reduction tree.
3116 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3117 const DataLayout *DL) {
3119 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3120 "Thi phi needs to use the binary operator");
3122 // We could have a initial reductions that is not an add.
3123 // r *= v1 + v2 + v3 + v4
3124 // In such a case start looking for a tree rooted in the first '+'.
3126 if (B->getOperand(0) == Phi) {
3128 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3129 } else if (B->getOperand(1) == Phi) {
3131 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3138 Type *Ty = B->getType();
3139 if (Ty->isVectorTy())
3142 ReductionOpcode = B->getOpcode();
3143 ReducedValueOpcode = 0;
3144 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3151 // We currently only support adds.
3152 if (ReductionOpcode != Instruction::Add &&
3153 ReductionOpcode != Instruction::FAdd)
3156 // Post order traverse the reduction tree starting at B. We only handle true
3157 // trees containing only binary operators.
3158 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3159 Stack.push_back(std::make_pair(B, 0));
3160 while (!Stack.empty()) {
3161 BinaryOperator *TreeN = Stack.back().first;
3162 unsigned EdgeToVist = Stack.back().second++;
3163 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3165 // Only handle trees in the current basic block.
3166 if (TreeN->getParent() != B->getParent())
3169 // Each tree node needs to have one user except for the ultimate
3171 if (!TreeN->hasOneUse() && TreeN != B)
3175 if (EdgeToVist == 2 || IsReducedValue) {
3176 if (IsReducedValue) {
3177 // Make sure that the opcodes of the operations that we are going to
3179 if (!ReducedValueOpcode)
3180 ReducedValueOpcode = TreeN->getOpcode();
3181 else if (ReducedValueOpcode != TreeN->getOpcode())
3183 ReducedVals.push_back(TreeN);
3185 // We need to be able to reassociate the adds.
3186 if (!TreeN->isAssociative())
3188 ReductionOps.push_back(TreeN);
3195 // Visit left or right.
3196 Value *NextV = TreeN->getOperand(EdgeToVist);
3197 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3199 Stack.push_back(std::make_pair(Next, 0));
3200 else if (NextV != Phi)
3206 /// \brief Attempt to vectorize the tree found by
3207 /// matchAssociativeReduction.
3208 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3209 if (ReducedVals.empty())
3212 unsigned NumReducedVals = ReducedVals.size();
3213 if (NumReducedVals < ReduxWidth)
3216 Value *VectorizedTree = nullptr;
3217 IRBuilder<> Builder(ReductionRoot);
3218 FastMathFlags Unsafe;
3219 Unsafe.setUnsafeAlgebra();
3220 Builder.SetFastMathFlags(Unsafe);
3223 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3224 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
3225 V.buildTree(ValsToReduce, ReductionOps);
3228 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3229 if (Cost >= -SLPCostThreshold)
3232 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3235 // Vectorize a tree.
3236 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3237 Value *VectorizedRoot = V.vectorizeTree();
3239 // Emit a reduction.
3240 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3241 if (VectorizedTree) {
3242 Builder.SetCurrentDebugLocation(Loc);
3243 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3244 ReducedSubTree, "bin.rdx");
3246 VectorizedTree = ReducedSubTree;
3249 if (VectorizedTree) {
3250 // Finish the reduction.
3251 for (; i < NumReducedVals; ++i) {
3252 Builder.SetCurrentDebugLocation(
3253 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3254 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3259 assert(ReductionRoot && "Need a reduction operation");
3260 ReductionRoot->setOperand(0, VectorizedTree);
3261 ReductionRoot->setOperand(1, ReductionPHI);
3263 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3265 return VectorizedTree != nullptr;
3270 /// \brief Calcuate the cost of a reduction.
3271 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3272 Type *ScalarTy = FirstReducedVal->getType();
3273 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3275 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3276 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3278 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3279 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3281 int ScalarReduxCost =
3282 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3284 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3285 << " for reduction that starts with " << *FirstReducedVal
3287 << (IsPairwiseReduction ? "pairwise" : "splitting")
3288 << " reduction)\n");
3290 return VecReduxCost - ScalarReduxCost;
3293 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3294 Value *R, const Twine &Name = "") {
3295 if (Opcode == Instruction::FAdd)
3296 return Builder.CreateFAdd(L, R, Name);
3297 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3300 /// \brief Emit a horizontal reduction of the vectorized value.
3301 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3302 assert(VectorizedValue && "Need to have a vectorized tree node");
3303 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
3304 assert(isPowerOf2_32(ReduxWidth) &&
3305 "We only handle power-of-two reductions for now");
3307 Value *TmpVec = ValToReduce;
3308 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3309 if (IsPairwiseReduction) {
3311 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3313 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3315 Value *LeftShuf = Builder.CreateShuffleVector(
3316 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3317 Value *RightShuf = Builder.CreateShuffleVector(
3318 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3320 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3324 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3325 Value *Shuf = Builder.CreateShuffleVector(
3326 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3327 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3331 // The result is in the first element of the vector.
3332 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3336 /// \brief Recognize construction of vectors like
3337 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3338 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3339 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3340 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3342 /// Returns true if it matches
3344 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3345 SmallVectorImpl<Value *> &BuildVector,
3346 SmallVectorImpl<Value *> &BuildVectorOpds) {
3347 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3350 InsertElementInst *IE = FirstInsertElem;
3352 BuildVector.push_back(IE);
3353 BuildVectorOpds.push_back(IE->getOperand(1));
3355 if (IE->use_empty())
3358 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3362 // If this isn't the final use, make sure the next insertelement is the only
3363 // use. It's OK if the final constructed vector is used multiple times
3364 if (!IE->hasOneUse())
3373 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3374 return V->getType() < V2->getType();
3377 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3378 bool Changed = false;
3379 SmallVector<Value *, 4> Incoming;
3380 SmallSet<Value *, 16> VisitedInstrs;
3382 bool HaveVectorizedPhiNodes = true;
3383 while (HaveVectorizedPhiNodes) {
3384 HaveVectorizedPhiNodes = false;
3386 // Collect the incoming values from the PHIs.
3388 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3390 PHINode *P = dyn_cast<PHINode>(instr);
3394 if (!VisitedInstrs.count(P))
3395 Incoming.push_back(P);
3399 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3401 // Try to vectorize elements base on their type.
3402 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3406 // Look for the next elements with the same type.
3407 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3408 while (SameTypeIt != E &&
3409 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3410 VisitedInstrs.insert(*SameTypeIt);
3414 // Try to vectorize them.
3415 unsigned NumElts = (SameTypeIt - IncIt);
3416 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3418 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
3419 // Success start over because instructions might have been changed.
3420 HaveVectorizedPhiNodes = true;
3425 // Start over at the next instruction of a different type (or the end).
3430 VisitedInstrs.clear();
3432 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3433 // We may go through BB multiple times so skip the one we have checked.
3434 if (!VisitedInstrs.insert(it))
3437 if (isa<DbgInfoIntrinsic>(it))
3440 // Try to vectorize reductions that use PHINodes.
3441 if (PHINode *P = dyn_cast<PHINode>(it)) {
3442 // Check that the PHI is a reduction PHI.
3443 if (P->getNumIncomingValues() != 2)
3446 (P->getIncomingBlock(0) == BB
3447 ? (P->getIncomingValue(0))
3448 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3450 // Check if this is a Binary Operator.
3451 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3455 // Try to match and vectorize a horizontal reduction.
3456 HorizontalReduction HorRdx;
3457 if (ShouldVectorizeHor &&
3458 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3459 HorRdx.tryToReduce(R, TTI)) {
3466 Value *Inst = BI->getOperand(0);
3468 Inst = BI->getOperand(1);
3470 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3471 // We would like to start over since some instructions are deleted
3472 // and the iterator may become invalid value.
3482 // Try to vectorize horizontal reductions feeding into a store.
3483 if (ShouldStartVectorizeHorAtStore)
3484 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3485 if (BinaryOperator *BinOp =
3486 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3487 HorizontalReduction HorRdx;
3488 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3489 HorRdx.tryToReduce(R, TTI)) ||
3490 tryToVectorize(BinOp, R))) {
3498 // Try to vectorize trees that start at compare instructions.
3499 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3500 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3502 // We would like to start over since some instructions are deleted
3503 // and the iterator may become invalid value.
3509 for (int i = 0; i < 2; ++i) {
3510 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3511 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3513 // We would like to start over since some instructions are deleted
3514 // and the iterator may become invalid value.
3523 // Try to vectorize trees that start at insertelement instructions.
3524 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3525 SmallVector<Value *, 16> BuildVector;
3526 SmallVector<Value *, 16> BuildVectorOpds;
3527 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3530 // Vectorize starting with the build vector operands ignoring the
3531 // BuildVector instructions for the purpose of scheduling and user
3533 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3546 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3547 bool Changed = false;
3548 // Attempt to sort and vectorize each of the store-groups.
3549 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3551 if (it->second.size() < 2)
3554 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3555 << it->second.size() << ".\n");
3557 // Process the stores in chunks of 16.
3558 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3559 unsigned Len = std::min<unsigned>(CE - CI, 16);
3560 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
3561 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
3567 } // end anonymous namespace
3569 char SLPVectorizer::ID = 0;
3570 static const char lv_name[] = "SLP Vectorizer";
3571 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3572 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3573 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3574 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3575 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3576 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3579 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }