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 cost incurred by unwanted spills and fills, caused by
365 /// holding live values over call sites.
368 /// \returns the vectorization cost of the subtree that starts at \p VL.
369 /// A negative number means that this is profitable.
372 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
373 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
374 void buildTree(ArrayRef<Value *> Roots,
375 ArrayRef<Value *> UserIgnoreLst = None);
377 /// Clear the internal data structures that are created by 'buildTree'.
379 VectorizableTree.clear();
380 ScalarToTreeEntry.clear();
382 ExternalUses.clear();
383 NumLoadsWantToKeepOrder = 0;
384 NumLoadsWantToChangeOrder = 0;
385 for (auto &Iter : BlocksSchedules) {
386 BlockScheduling *BS = Iter.second.get();
391 /// \returns true if the memory operations A and B are consecutive.
392 bool isConsecutiveAccess(Value *A, Value *B);
394 /// \brief Perform LICM and CSE on the newly generated gather sequences.
395 void optimizeGatherSequence();
397 /// \returns true if it is benefitial to reverse the vector order.
398 bool shouldReorder() const {
399 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
405 /// \returns the cost of the vectorizable entry.
406 int getEntryCost(TreeEntry *E);
408 /// This is the recursive part of buildTree.
409 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
411 /// Vectorize a single entry in the tree.
412 Value *vectorizeTree(TreeEntry *E);
414 /// Vectorize a single entry in the tree, starting in \p VL.
415 Value *vectorizeTree(ArrayRef<Value *> VL);
417 /// \returns the pointer to the vectorized value if \p VL is already
418 /// vectorized, or NULL. They may happen in cycles.
419 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
421 /// \brief Take the pointer operand from the Load/Store instruction.
422 /// \returns NULL if this is not a valid Load/Store instruction.
423 static Value *getPointerOperand(Value *I);
425 /// \brief Take the address space operand from the Load/Store instruction.
426 /// \returns -1 if this is not a valid Load/Store instruction.
427 static unsigned getAddressSpaceOperand(Value *I);
429 /// \returns the scalarization cost for this type. Scalarization in this
430 /// context means the creation of vectors from a group of scalars.
431 int getGatherCost(Type *Ty);
433 /// \returns the scalarization cost for this list of values. Assuming that
434 /// this subtree gets vectorized, we may need to extract the values from the
435 /// roots. This method calculates the cost of extracting the values.
436 int getGatherCost(ArrayRef<Value *> VL);
438 /// \brief Set the Builder insert point to one after the last instruction in
440 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
442 /// \returns a vector from a collection of scalars in \p VL.
443 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
445 /// \returns whether the VectorizableTree is fully vectoriable and will
446 /// be beneficial even the tree height is tiny.
447 bool isFullyVectorizableTinyTree();
450 TreeEntry() : Scalars(), VectorizedValue(nullptr),
453 /// \returns true if the scalars in VL are equal to this entry.
454 bool isSame(ArrayRef<Value *> VL) const {
455 assert(VL.size() == Scalars.size() && "Invalid size");
456 return std::equal(VL.begin(), VL.end(), Scalars.begin());
459 /// A vector of scalars.
462 /// The Scalars are vectorized into this value. It is initialized to Null.
463 Value *VectorizedValue;
465 /// Do we need to gather this sequence ?
469 /// Create a new VectorizableTree entry.
470 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
471 VectorizableTree.push_back(TreeEntry());
472 int idx = VectorizableTree.size() - 1;
473 TreeEntry *Last = &VectorizableTree[idx];
474 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
475 Last->NeedToGather = !Vectorized;
477 for (int i = 0, e = VL.size(); i != e; ++i) {
478 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
479 ScalarToTreeEntry[VL[i]] = idx;
482 MustGather.insert(VL.begin(), VL.end());
487 /// -- Vectorization State --
488 /// Holds all of the tree entries.
489 std::vector<TreeEntry> VectorizableTree;
491 /// Maps a specific scalar to its tree entry.
492 SmallDenseMap<Value*, int> ScalarToTreeEntry;
494 /// A list of scalars that we found that we need to keep as scalars.
497 /// This POD struct describes one external user in the vectorized tree.
498 struct ExternalUser {
499 ExternalUser (Value *S, llvm::User *U, int L) :
500 Scalar(S), User(U), Lane(L){};
501 // Which scalar in our function.
503 // Which user that uses the scalar.
505 // Which lane does the scalar belong to.
508 typedef SmallVector<ExternalUser, 16> UserList;
510 /// A list of values that need to extracted out of the tree.
511 /// This list holds pairs of (Internal Scalar : External User).
512 UserList ExternalUses;
514 /// Holds all of the instructions that we gathered.
515 SetVector<Instruction *> GatherSeq;
516 /// A list of blocks that we are going to CSE.
517 SetVector<BasicBlock *> CSEBlocks;
519 /// Contains all scheduling relevant data for an instruction.
520 /// A ScheduleData either represents a single instruction or a member of an
521 /// instruction bundle (= a group of instructions which is combined into a
522 /// vector instruction).
523 struct ScheduleData {
525 // The initial value for the dependency counters. It means that the
526 // dependencies are not calculated yet.
527 enum { InvalidDeps = -1 };
530 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
531 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
532 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
533 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
535 void init(int BlockSchedulingRegionID) {
536 FirstInBundle = this;
537 NextInBundle = nullptr;
538 NextLoadStore = nullptr;
540 SchedulingRegionID = BlockSchedulingRegionID;
541 UnscheduledDepsInBundle = UnscheduledDeps;
545 /// Returns true if the dependency information has been calculated.
546 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
548 /// Returns true for single instructions and for bundle representatives
549 /// (= the head of a bundle).
550 bool isSchedulingEntity() const { return FirstInBundle == this; }
552 /// Returns true if it represents an instruction bundle and not only a
553 /// single instruction.
554 bool isPartOfBundle() const {
555 return NextInBundle != nullptr || FirstInBundle != this;
558 /// Returns true if it is ready for scheduling, i.e. it has no more
559 /// unscheduled depending instructions/bundles.
560 bool isReady() const {
561 assert(isSchedulingEntity() &&
562 "can't consider non-scheduling entity for ready list");
563 return UnscheduledDepsInBundle == 0 && !IsScheduled;
566 /// Modifies the number of unscheduled dependencies, also updating it for
567 /// the whole bundle.
568 int incrementUnscheduledDeps(int Incr) {
569 UnscheduledDeps += Incr;
570 return FirstInBundle->UnscheduledDepsInBundle += Incr;
573 /// Sets the number of unscheduled dependencies to the number of
575 void resetUnscheduledDeps() {
576 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
579 /// Clears all dependency information.
580 void clearDependencies() {
581 Dependencies = InvalidDeps;
582 resetUnscheduledDeps();
583 MemoryDependencies.clear();
586 void dump(raw_ostream &os) const {
587 if (!isSchedulingEntity()) {
589 } else if (NextInBundle) {
591 ScheduleData *SD = NextInBundle;
593 os << ';' << *SD->Inst;
594 SD = SD->NextInBundle;
604 /// Points to the head in an instruction bundle (and always to this for
605 /// single instructions).
606 ScheduleData *FirstInBundle;
608 /// Single linked list of all instructions in a bundle. Null if it is a
609 /// single instruction.
610 ScheduleData *NextInBundle;
612 /// Single linked list of all memory instructions (e.g. load, store, call)
613 /// in the block - until the end of the scheduling region.
614 ScheduleData *NextLoadStore;
616 /// The dependent memory instructions.
617 /// This list is derived on demand in calculateDependencies().
618 SmallVector<ScheduleData *, 4> MemoryDependencies;
620 /// This ScheduleData is in the current scheduling region if this matches
621 /// the current SchedulingRegionID of BlockScheduling.
622 int SchedulingRegionID;
624 /// Used for getting a "good" final ordering of instructions.
625 int SchedulingPriority;
627 /// The number of dependencies. Constitutes of the number of users of the
628 /// instruction plus the number of dependent memory instructions (if any).
629 /// This value is calculated on demand.
630 /// If InvalidDeps, the number of dependencies is not calculated yet.
634 /// The number of dependencies minus the number of dependencies of scheduled
635 /// instructions. As soon as this is zero, the instruction/bundle gets ready
637 /// Note that this is negative as long as Dependencies is not calculated.
640 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
641 /// single instructions.
642 int UnscheduledDepsInBundle;
644 /// True if this instruction is scheduled (or considered as scheduled in the
650 friend raw_ostream &operator<<(raw_ostream &os,
651 const BoUpSLP::ScheduleData &SD);
654 /// Contains all scheduling data for a basic block.
656 struct BlockScheduling {
658 BlockScheduling(BasicBlock *BB)
659 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
660 ScheduleStart(nullptr), ScheduleEnd(nullptr),
661 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
662 // Make sure that the initial SchedulingRegionID is greater than the
663 // initial SchedulingRegionID in ScheduleData (which is 0).
664 SchedulingRegionID(1) {}
668 ScheduleStart = nullptr;
669 ScheduleEnd = nullptr;
670 FirstLoadStoreInRegion = nullptr;
671 LastLoadStoreInRegion = nullptr;
673 // Make a new scheduling region, i.e. all existing ScheduleData is not
674 // in the new region yet.
675 ++SchedulingRegionID;
678 ScheduleData *getScheduleData(Value *V) {
679 ScheduleData *SD = ScheduleDataMap[V];
680 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
685 bool isInSchedulingRegion(ScheduleData *SD) {
686 return SD->SchedulingRegionID == SchedulingRegionID;
689 /// Marks an instruction as scheduled and puts all dependent ready
690 /// instructions into the ready-list.
691 template <typename ReadyListType>
692 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
693 SD->IsScheduled = true;
694 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
696 ScheduleData *BundleMember = SD;
697 while (BundleMember) {
698 // Handle the def-use chain dependencies.
699 for (Use &U : BundleMember->Inst->operands()) {
700 ScheduleData *OpDef = getScheduleData(U.get());
701 if (OpDef && OpDef->hasValidDependencies() &&
702 OpDef->incrementUnscheduledDeps(-1) == 0) {
703 // There are no more unscheduled dependencies after decrementing,
704 // so we can put the dependent instruction into the ready list.
705 ScheduleData *DepBundle = OpDef->FirstInBundle;
706 assert(!DepBundle->IsScheduled &&
707 "already scheduled bundle gets ready");
708 ReadyList.insert(DepBundle);
709 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
712 // Handle the memory dependencies.
713 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
714 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
715 // There are no more unscheduled dependencies after decrementing,
716 // so we can put the dependent instruction into the ready list.
717 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
718 assert(!DepBundle->IsScheduled &&
719 "already scheduled bundle gets ready");
720 ReadyList.insert(DepBundle);
721 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
724 BundleMember = BundleMember->NextInBundle;
728 /// Put all instructions into the ReadyList which are ready for scheduling.
729 template <typename ReadyListType>
730 void initialFillReadyList(ReadyListType &ReadyList) {
731 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
732 ScheduleData *SD = getScheduleData(I);
733 if (SD->isSchedulingEntity() && SD->isReady()) {
734 ReadyList.insert(SD);
735 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
740 /// Checks if a bundle of instructions can be scheduled, i.e. has no
741 /// cyclic dependencies. This is only a dry-run, no instructions are
742 /// actually moved at this stage.
743 bool tryScheduleBundle(ArrayRef<Value *> VL, AliasAnalysis *AA);
745 /// Un-bundles a group of instructions.
746 void cancelScheduling(ArrayRef<Value *> VL);
748 /// Extends the scheduling region so that V is inside the region.
749 void extendSchedulingRegion(Value *V);
751 /// Initialize the ScheduleData structures for new instructions in the
752 /// scheduling region.
753 void initScheduleData(Instruction *FromI, Instruction *ToI,
754 ScheduleData *PrevLoadStore,
755 ScheduleData *NextLoadStore);
757 /// Updates the dependency information of a bundle and of all instructions/
758 /// bundles which depend on the original bundle.
759 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
762 /// Sets all instruction in the scheduling region to un-scheduled.
763 void resetSchedule();
767 /// Simple memory allocation for ScheduleData.
768 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
770 /// The size of a ScheduleData array in ScheduleDataChunks.
773 /// The allocator position in the current chunk, which is the last entry
774 /// of ScheduleDataChunks.
777 /// Attaches ScheduleData to Instruction.
778 /// Note that the mapping survives during all vectorization iterations, i.e.
779 /// ScheduleData structures are recycled.
780 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
782 struct ReadyList : SmallVector<ScheduleData *, 8> {
783 void insert(ScheduleData *SD) { push_back(SD); }
786 /// The ready-list for scheduling (only used for the dry-run).
787 ReadyList ReadyInsts;
789 /// The first instruction of the scheduling region.
790 Instruction *ScheduleStart;
792 /// The first instruction _after_ the scheduling region.
793 Instruction *ScheduleEnd;
795 /// The first memory accessing instruction in the scheduling region
797 ScheduleData *FirstLoadStoreInRegion;
799 /// The last memory accessing instruction in the scheduling region
801 ScheduleData *LastLoadStoreInRegion;
803 /// The ID of the scheduling region. For a new vectorization iteration this
804 /// is incremented which "removes" all ScheduleData from the region.
805 int SchedulingRegionID;
808 /// Attaches the BlockScheduling structures to basic blocks.
809 DenseMap<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
811 /// Performs the "real" scheduling. Done before vectorization is actually
812 /// performed in a basic block.
813 void scheduleBlock(BlockScheduling *BS);
815 /// List of users to ignore during scheduling and that don't need extracting.
816 ArrayRef<Value *> UserIgnoreList;
818 // Number of load-bundles, which contain consecutive loads.
819 int NumLoadsWantToKeepOrder;
821 // Number of load-bundles of size 2, which are consecutive loads if reversed.
822 int NumLoadsWantToChangeOrder;
824 // Analysis and block reference.
827 const DataLayout *DL;
828 TargetTransformInfo *TTI;
829 TargetLibraryInfo *TLI;
833 /// Instruction builder to construct the vectorized tree.
838 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
844 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
845 ArrayRef<Value *> UserIgnoreLst) {
847 UserIgnoreList = UserIgnoreLst;
848 if (!getSameType(Roots))
850 buildTree_rec(Roots, 0);
852 // Collect the values that we need to extract from the tree.
853 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
854 TreeEntry *Entry = &VectorizableTree[EIdx];
857 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
858 Value *Scalar = Entry->Scalars[Lane];
860 // No need to handle users of gathered values.
861 if (Entry->NeedToGather)
864 for (User *U : Scalar->users()) {
865 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
867 // Skip in-tree scalars that become vectors.
868 if (ScalarToTreeEntry.count(U)) {
869 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
871 int Idx = ScalarToTreeEntry[U]; (void) Idx;
872 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
875 Instruction *UserInst = dyn_cast<Instruction>(U);
879 // Ignore users in the user ignore list.
880 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
881 UserIgnoreList.end())
884 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
885 Lane << " from " << *Scalar << ".\n");
886 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
893 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
894 bool SameTy = getSameType(VL); (void)SameTy;
895 bool isAltShuffle = false;
896 assert(SameTy && "Invalid types!");
898 if (Depth == RecursionMaxDepth) {
899 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
900 newTreeEntry(VL, false);
904 // Don't handle vectors.
905 if (VL[0]->getType()->isVectorTy()) {
906 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
907 newTreeEntry(VL, false);
911 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
912 if (SI->getValueOperand()->getType()->isVectorTy()) {
913 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
914 newTreeEntry(VL, false);
917 unsigned Opcode = getSameOpcode(VL);
919 // Check that this shuffle vector refers to the alternate
920 // sequence of opcodes.
921 if (Opcode == Instruction::ShuffleVector) {
922 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
923 unsigned Op = I0->getOpcode();
924 if (Op != Instruction::ShuffleVector)
928 // If all of the operands are identical or constant we have a simple solution.
929 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
930 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
931 newTreeEntry(VL, false);
935 // We now know that this is a vector of instructions of the same type from
938 // Check if this is a duplicate of another entry.
939 if (ScalarToTreeEntry.count(VL[0])) {
940 int Idx = ScalarToTreeEntry[VL[0]];
941 TreeEntry *E = &VectorizableTree[Idx];
942 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
943 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
944 if (E->Scalars[i] != VL[i]) {
945 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
946 newTreeEntry(VL, false);
950 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
954 // Check that none of the instructions in the bundle are already in the tree.
955 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
956 if (ScalarToTreeEntry.count(VL[i])) {
957 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
958 ") is already in tree.\n");
959 newTreeEntry(VL, false);
964 // If any of the scalars appears in the table OR it is marked as a value that
965 // needs to stat scalar then we need to gather the scalars.
966 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
967 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
968 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
969 newTreeEntry(VL, false);
974 // Check that all of the users of the scalars that we want to vectorize are
976 Instruction *VL0 = cast<Instruction>(VL[0]);
977 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
979 // Check that every instructions appears once in this bundle.
980 for (unsigned i = 0, e = VL.size(); i < e; ++i)
981 for (unsigned j = i+1; j < e; ++j)
982 if (VL[i] == VL[j]) {
983 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
984 newTreeEntry(VL, false);
988 auto &BSRef = BlocksSchedules[BB];
990 BSRef = llvm::make_unique<BlockScheduling>(BB);
992 BlockScheduling &BS = *BSRef.get();
994 if (!BS.tryScheduleBundle(VL, AA)) {
995 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
996 BS.cancelScheduling(VL);
997 newTreeEntry(VL, false);
1000 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1003 case Instruction::PHI: {
1004 PHINode *PH = dyn_cast<PHINode>(VL0);
1006 // Check for terminator values (e.g. invoke).
1007 for (unsigned j = 0; j < VL.size(); ++j)
1008 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1009 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1010 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1012 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1013 BS.cancelScheduling(VL);
1014 newTreeEntry(VL, false);
1019 newTreeEntry(VL, true);
1020 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1022 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1024 // Prepare the operand vector.
1025 for (unsigned j = 0; j < VL.size(); ++j)
1026 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1027 PH->getIncomingBlock(i)));
1029 buildTree_rec(Operands, Depth + 1);
1033 case Instruction::ExtractElement: {
1034 bool Reuse = CanReuseExtract(VL);
1036 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1038 BS.cancelScheduling(VL);
1040 newTreeEntry(VL, Reuse);
1043 case Instruction::Load: {
1044 // Check if the loads are consecutive or of we need to swizzle them.
1045 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1046 LoadInst *L = cast<LoadInst>(VL[i]);
1047 if (!L->isSimple()) {
1048 BS.cancelScheduling(VL);
1049 newTreeEntry(VL, false);
1050 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1053 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1054 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1055 ++NumLoadsWantToChangeOrder;
1057 BS.cancelScheduling(VL);
1058 newTreeEntry(VL, false);
1059 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1063 ++NumLoadsWantToKeepOrder;
1064 newTreeEntry(VL, true);
1065 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1068 case Instruction::ZExt:
1069 case Instruction::SExt:
1070 case Instruction::FPToUI:
1071 case Instruction::FPToSI:
1072 case Instruction::FPExt:
1073 case Instruction::PtrToInt:
1074 case Instruction::IntToPtr:
1075 case Instruction::SIToFP:
1076 case Instruction::UIToFP:
1077 case Instruction::Trunc:
1078 case Instruction::FPTrunc:
1079 case Instruction::BitCast: {
1080 Type *SrcTy = VL0->getOperand(0)->getType();
1081 for (unsigned i = 0; i < VL.size(); ++i) {
1082 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1083 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1084 BS.cancelScheduling(VL);
1085 newTreeEntry(VL, false);
1086 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1090 newTreeEntry(VL, true);
1091 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1093 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1095 // Prepare the operand vector.
1096 for (unsigned j = 0; j < VL.size(); ++j)
1097 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1099 buildTree_rec(Operands, Depth+1);
1103 case Instruction::ICmp:
1104 case Instruction::FCmp: {
1105 // Check that all of the compares have the same predicate.
1106 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1107 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1108 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1109 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1110 if (Cmp->getPredicate() != P0 ||
1111 Cmp->getOperand(0)->getType() != ComparedTy) {
1112 BS.cancelScheduling(VL);
1113 newTreeEntry(VL, false);
1114 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1119 newTreeEntry(VL, true);
1120 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1122 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1124 // Prepare the operand vector.
1125 for (unsigned j = 0; j < VL.size(); ++j)
1126 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1128 buildTree_rec(Operands, Depth+1);
1132 case Instruction::Select:
1133 case Instruction::Add:
1134 case Instruction::FAdd:
1135 case Instruction::Sub:
1136 case Instruction::FSub:
1137 case Instruction::Mul:
1138 case Instruction::FMul:
1139 case Instruction::UDiv:
1140 case Instruction::SDiv:
1141 case Instruction::FDiv:
1142 case Instruction::URem:
1143 case Instruction::SRem:
1144 case Instruction::FRem:
1145 case Instruction::Shl:
1146 case Instruction::LShr:
1147 case Instruction::AShr:
1148 case Instruction::And:
1149 case Instruction::Or:
1150 case Instruction::Xor: {
1151 newTreeEntry(VL, true);
1152 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1154 // Sort operands of the instructions so that each side is more likely to
1155 // have the same opcode.
1156 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1157 ValueList Left, Right;
1158 reorderInputsAccordingToOpcode(VL, Left, Right);
1159 buildTree_rec(Left, Depth + 1);
1160 buildTree_rec(Right, Depth + 1);
1164 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1166 // Prepare the operand vector.
1167 for (unsigned j = 0; j < VL.size(); ++j)
1168 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1170 buildTree_rec(Operands, Depth+1);
1174 case Instruction::GetElementPtr: {
1175 // We don't combine GEPs with complicated (nested) indexing.
1176 for (unsigned j = 0; j < VL.size(); ++j) {
1177 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1178 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1179 BS.cancelScheduling(VL);
1180 newTreeEntry(VL, false);
1185 // We can't combine several GEPs into one vector if they operate on
1187 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1188 for (unsigned j = 0; j < VL.size(); ++j) {
1189 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1191 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1192 BS.cancelScheduling(VL);
1193 newTreeEntry(VL, false);
1198 // We don't combine GEPs with non-constant indexes.
1199 for (unsigned j = 0; j < VL.size(); ++j) {
1200 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1201 if (!isa<ConstantInt>(Op)) {
1203 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1204 BS.cancelScheduling(VL);
1205 newTreeEntry(VL, false);
1210 newTreeEntry(VL, true);
1211 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1212 for (unsigned i = 0, e = 2; i < e; ++i) {
1214 // Prepare the operand vector.
1215 for (unsigned j = 0; j < VL.size(); ++j)
1216 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1218 buildTree_rec(Operands, Depth + 1);
1222 case Instruction::Store: {
1223 // Check if the stores are consecutive or of we need to swizzle them.
1224 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1225 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1226 BS.cancelScheduling(VL);
1227 newTreeEntry(VL, false);
1228 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1232 newTreeEntry(VL, true);
1233 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1236 for (unsigned j = 0; j < VL.size(); ++j)
1237 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1239 buildTree_rec(Operands, Depth + 1);
1242 case Instruction::Call: {
1243 // Check if the calls are all to the same vectorizable intrinsic.
1244 CallInst *CI = cast<CallInst>(VL[0]);
1245 // Check if this is an Intrinsic call or something that can be
1246 // represented by an intrinsic call
1247 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1248 if (!isTriviallyVectorizable(ID)) {
1249 BS.cancelScheduling(VL);
1250 newTreeEntry(VL, false);
1251 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1254 Function *Int = CI->getCalledFunction();
1255 Value *A1I = nullptr;
1256 if (hasVectorInstrinsicScalarOpd(ID, 1))
1257 A1I = CI->getArgOperand(1);
1258 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1259 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1260 if (!CI2 || CI2->getCalledFunction() != Int ||
1261 getIntrinsicIDForCall(CI2, TLI) != ID) {
1262 BS.cancelScheduling(VL);
1263 newTreeEntry(VL, false);
1264 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1268 // ctlz,cttz and powi are special intrinsics whose second argument
1269 // should be same in order for them to be vectorized.
1270 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1271 Value *A1J = CI2->getArgOperand(1);
1273 BS.cancelScheduling(VL);
1274 newTreeEntry(VL, false);
1275 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1276 << " argument "<< A1I<<"!=" << A1J
1283 newTreeEntry(VL, true);
1284 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1286 // Prepare the operand vector.
1287 for (unsigned j = 0; j < VL.size(); ++j) {
1288 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1289 Operands.push_back(CI2->getArgOperand(i));
1291 buildTree_rec(Operands, Depth + 1);
1295 case Instruction::ShuffleVector: {
1296 // If this is not an alternate sequence of opcode like add-sub
1297 // then do not vectorize this instruction.
1298 if (!isAltShuffle) {
1299 BS.cancelScheduling(VL);
1300 newTreeEntry(VL, false);
1301 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1304 newTreeEntry(VL, true);
1305 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1306 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1308 // Prepare the operand vector.
1309 for (unsigned j = 0; j < VL.size(); ++j)
1310 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1312 buildTree_rec(Operands, Depth + 1);
1317 BS.cancelScheduling(VL);
1318 newTreeEntry(VL, false);
1319 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1324 int BoUpSLP::getEntryCost(TreeEntry *E) {
1325 ArrayRef<Value*> VL = E->Scalars;
1327 Type *ScalarTy = VL[0]->getType();
1328 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1329 ScalarTy = SI->getValueOperand()->getType();
1330 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1332 if (E->NeedToGather) {
1333 if (allConstant(VL))
1336 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1338 return getGatherCost(E->Scalars);
1340 unsigned Opcode = getSameOpcode(VL);
1341 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1342 Instruction *VL0 = cast<Instruction>(VL[0]);
1344 case Instruction::PHI: {
1347 case Instruction::ExtractElement: {
1348 if (CanReuseExtract(VL)) {
1350 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1351 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1353 // Take credit for instruction that will become dead.
1355 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1359 return getGatherCost(VecTy);
1361 case Instruction::ZExt:
1362 case Instruction::SExt:
1363 case Instruction::FPToUI:
1364 case Instruction::FPToSI:
1365 case Instruction::FPExt:
1366 case Instruction::PtrToInt:
1367 case Instruction::IntToPtr:
1368 case Instruction::SIToFP:
1369 case Instruction::UIToFP:
1370 case Instruction::Trunc:
1371 case Instruction::FPTrunc:
1372 case Instruction::BitCast: {
1373 Type *SrcTy = VL0->getOperand(0)->getType();
1375 // Calculate the cost of this instruction.
1376 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1377 VL0->getType(), SrcTy);
1379 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1380 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1381 return VecCost - ScalarCost;
1383 case Instruction::FCmp:
1384 case Instruction::ICmp:
1385 case Instruction::Select:
1386 case Instruction::Add:
1387 case Instruction::FAdd:
1388 case Instruction::Sub:
1389 case Instruction::FSub:
1390 case Instruction::Mul:
1391 case Instruction::FMul:
1392 case Instruction::UDiv:
1393 case Instruction::SDiv:
1394 case Instruction::FDiv:
1395 case Instruction::URem:
1396 case Instruction::SRem:
1397 case Instruction::FRem:
1398 case Instruction::Shl:
1399 case Instruction::LShr:
1400 case Instruction::AShr:
1401 case Instruction::And:
1402 case Instruction::Or:
1403 case Instruction::Xor: {
1404 // Calculate the cost of this instruction.
1407 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1408 Opcode == Instruction::Select) {
1409 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1410 ScalarCost = VecTy->getNumElements() *
1411 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1412 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1414 // Certain instructions can be cheaper to vectorize if they have a
1415 // constant second vector operand.
1416 TargetTransformInfo::OperandValueKind Op1VK =
1417 TargetTransformInfo::OK_AnyValue;
1418 TargetTransformInfo::OperandValueKind Op2VK =
1419 TargetTransformInfo::OK_UniformConstantValue;
1421 // If all operands are exactly the same ConstantInt then set the
1422 // operand kind to OK_UniformConstantValue.
1423 // If instead not all operands are constants, then set the operand kind
1424 // to OK_AnyValue. If all operands are constants but not the same,
1425 // then set the operand kind to OK_NonUniformConstantValue.
1426 ConstantInt *CInt = nullptr;
1427 for (unsigned i = 0; i < VL.size(); ++i) {
1428 const Instruction *I = cast<Instruction>(VL[i]);
1429 if (!isa<ConstantInt>(I->getOperand(1))) {
1430 Op2VK = TargetTransformInfo::OK_AnyValue;
1434 CInt = cast<ConstantInt>(I->getOperand(1));
1437 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1438 CInt != cast<ConstantInt>(I->getOperand(1)))
1439 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1443 VecTy->getNumElements() *
1444 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1445 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1447 return VecCost - ScalarCost;
1449 case Instruction::GetElementPtr: {
1450 TargetTransformInfo::OperandValueKind Op1VK =
1451 TargetTransformInfo::OK_AnyValue;
1452 TargetTransformInfo::OperandValueKind Op2VK =
1453 TargetTransformInfo::OK_UniformConstantValue;
1456 VecTy->getNumElements() *
1457 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1459 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1461 return VecCost - ScalarCost;
1463 case Instruction::Load: {
1464 // Cost of wide load - cost of scalar loads.
1465 int ScalarLdCost = VecTy->getNumElements() *
1466 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1467 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1468 return VecLdCost - ScalarLdCost;
1470 case Instruction::Store: {
1471 // We know that we can merge the stores. Calculate the cost.
1472 int ScalarStCost = VecTy->getNumElements() *
1473 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1474 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1475 return VecStCost - ScalarStCost;
1477 case Instruction::Call: {
1478 CallInst *CI = cast<CallInst>(VL0);
1479 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1481 // Calculate the cost of the scalar and vector calls.
1482 SmallVector<Type*, 4> ScalarTys, VecTys;
1483 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1484 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1485 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1486 VecTy->getNumElements()));
1489 int ScalarCallCost = VecTy->getNumElements() *
1490 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1492 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1494 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1495 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1496 << " for " << *CI << "\n");
1498 return VecCallCost - ScalarCallCost;
1500 case Instruction::ShuffleVector: {
1501 TargetTransformInfo::OperandValueKind Op1VK =
1502 TargetTransformInfo::OK_AnyValue;
1503 TargetTransformInfo::OperandValueKind Op2VK =
1504 TargetTransformInfo::OK_AnyValue;
1507 for (unsigned i = 0; i < VL.size(); ++i) {
1508 Instruction *I = cast<Instruction>(VL[i]);
1512 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1514 // VecCost is equal to sum of the cost of creating 2 vectors
1515 // and the cost of creating shuffle.
1516 Instruction *I0 = cast<Instruction>(VL[0]);
1518 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1519 Instruction *I1 = cast<Instruction>(VL[1]);
1521 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1523 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1524 return VecCost - ScalarCost;
1527 llvm_unreachable("Unknown instruction");
1531 bool BoUpSLP::isFullyVectorizableTinyTree() {
1532 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1533 VectorizableTree.size() << " is fully vectorizable .\n");
1535 // We only handle trees of height 2.
1536 if (VectorizableTree.size() != 2)
1539 // Handle splat stores.
1540 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1543 // Gathering cost would be too much for tiny trees.
1544 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1550 int BoUpSLP::getSpillCost() {
1551 // Walk from the bottom of the tree to the top, tracking which values are
1552 // live. When we see a call instruction that is not part of our tree,
1553 // query TTI to see if there is a cost to keeping values live over it
1554 // (for example, if spills and fills are required).
1555 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1558 SmallPtrSet<Instruction*, 4> LiveValues;
1559 Instruction *PrevInst = nullptr;
1561 for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1562 Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1572 dbgs() << "SLP: #LV: " << LiveValues.size();
1573 for (auto *X : LiveValues)
1574 dbgs() << " " << X->getName();
1575 dbgs() << ", Looking at ";
1579 // Update LiveValues.
1580 LiveValues.erase(PrevInst);
1581 for (auto &J : PrevInst->operands()) {
1582 if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1583 LiveValues.insert(cast<Instruction>(&*J));
1586 // Now find the sequence of instructions between PrevInst and Inst.
1587 BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1589 while (InstIt != PrevInstIt) {
1590 if (PrevInstIt == PrevInst->getParent()->rend()) {
1591 PrevInstIt = Inst->getParent()->rbegin();
1595 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1596 SmallVector<Type*, 4> V;
1597 for (auto *II : LiveValues)
1598 V.push_back(VectorType::get(II->getType(), BundleWidth));
1599 Cost += TTI->getCostOfKeepingLiveOverCall(V);
1608 DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1612 int BoUpSLP::getTreeCost() {
1614 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1615 VectorizableTree.size() << ".\n");
1617 // We only vectorize tiny trees if it is fully vectorizable.
1618 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1619 if (!VectorizableTree.size()) {
1620 assert(!ExternalUses.size() && "We should not have any external users");
1625 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1627 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1628 int C = getEntryCost(&VectorizableTree[i]);
1629 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1630 << *VectorizableTree[i].Scalars[0] << " .\n");
1634 SmallSet<Value *, 16> ExtractCostCalculated;
1635 int ExtractCost = 0;
1636 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1638 // We only add extract cost once for the same scalar.
1639 if (!ExtractCostCalculated.insert(I->Scalar))
1642 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1643 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1647 Cost += getSpillCost();
1649 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1650 return Cost + ExtractCost;
1653 int BoUpSLP::getGatherCost(Type *Ty) {
1655 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1656 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1660 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1661 // Find the type of the operands in VL.
1662 Type *ScalarTy = VL[0]->getType();
1663 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1664 ScalarTy = SI->getValueOperand()->getType();
1665 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1666 // Find the cost of inserting/extracting values from the vector.
1667 return getGatherCost(VecTy);
1670 Value *BoUpSLP::getPointerOperand(Value *I) {
1671 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1672 return LI->getPointerOperand();
1673 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1674 return SI->getPointerOperand();
1678 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1679 if (LoadInst *L = dyn_cast<LoadInst>(I))
1680 return L->getPointerAddressSpace();
1681 if (StoreInst *S = dyn_cast<StoreInst>(I))
1682 return S->getPointerAddressSpace();
1686 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1687 Value *PtrA = getPointerOperand(A);
1688 Value *PtrB = getPointerOperand(B);
1689 unsigned ASA = getAddressSpaceOperand(A);
1690 unsigned ASB = getAddressSpaceOperand(B);
1692 // Check that the address spaces match and that the pointers are valid.
1693 if (!PtrA || !PtrB || (ASA != ASB))
1696 // Make sure that A and B are different pointers of the same type.
1697 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1700 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1701 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1702 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1704 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1705 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1706 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1708 APInt OffsetDelta = OffsetB - OffsetA;
1710 // Check if they are based on the same pointer. That makes the offsets
1713 return OffsetDelta == Size;
1715 // Compute the necessary base pointer delta to have the necessary final delta
1716 // equal to the size.
1717 APInt BaseDelta = Size - OffsetDelta;
1719 // Otherwise compute the distance with SCEV between the base pointers.
1720 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1721 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1722 const SCEV *C = SE->getConstant(BaseDelta);
1723 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1724 return X == PtrSCEVB;
1727 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1728 Instruction *VL0 = cast<Instruction>(VL[0]);
1729 BasicBlock::iterator NextInst = VL0;
1731 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1732 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1735 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1736 Value *Vec = UndefValue::get(Ty);
1737 // Generate the 'InsertElement' instruction.
1738 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1739 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1740 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1741 GatherSeq.insert(Insrt);
1742 CSEBlocks.insert(Insrt->getParent());
1744 // Add to our 'need-to-extract' list.
1745 if (ScalarToTreeEntry.count(VL[i])) {
1746 int Idx = ScalarToTreeEntry[VL[i]];
1747 TreeEntry *E = &VectorizableTree[Idx];
1748 // Find which lane we need to extract.
1750 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1751 // Is this the lane of the scalar that we are looking for ?
1752 if (E->Scalars[Lane] == VL[i]) {
1757 assert(FoundLane >= 0 && "Could not find the correct lane");
1758 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1766 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1767 SmallDenseMap<Value*, int>::const_iterator Entry
1768 = ScalarToTreeEntry.find(VL[0]);
1769 if (Entry != ScalarToTreeEntry.end()) {
1770 int Idx = Entry->second;
1771 const TreeEntry *En = &VectorizableTree[Idx];
1772 if (En->isSame(VL) && En->VectorizedValue)
1773 return En->VectorizedValue;
1778 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1779 if (ScalarToTreeEntry.count(VL[0])) {
1780 int Idx = ScalarToTreeEntry[VL[0]];
1781 TreeEntry *E = &VectorizableTree[Idx];
1783 return vectorizeTree(E);
1786 Type *ScalarTy = VL[0]->getType();
1787 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1788 ScalarTy = SI->getValueOperand()->getType();
1789 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1791 return Gather(VL, VecTy);
1794 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1795 IRBuilder<>::InsertPointGuard Guard(Builder);
1797 if (E->VectorizedValue) {
1798 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1799 return E->VectorizedValue;
1802 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1803 Type *ScalarTy = VL0->getType();
1804 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1805 ScalarTy = SI->getValueOperand()->getType();
1806 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1808 if (E->NeedToGather) {
1809 setInsertPointAfterBundle(E->Scalars);
1810 return Gather(E->Scalars, VecTy);
1813 unsigned Opcode = getSameOpcode(E->Scalars);
1816 case Instruction::PHI: {
1817 PHINode *PH = dyn_cast<PHINode>(VL0);
1818 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1819 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1820 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1821 E->VectorizedValue = NewPhi;
1823 // PHINodes may have multiple entries from the same block. We want to
1824 // visit every block once.
1825 SmallSet<BasicBlock*, 4> VisitedBBs;
1827 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1829 BasicBlock *IBB = PH->getIncomingBlock(i);
1831 if (!VisitedBBs.insert(IBB)) {
1832 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1836 // Prepare the operand vector.
1837 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1838 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1839 getIncomingValueForBlock(IBB));
1841 Builder.SetInsertPoint(IBB->getTerminator());
1842 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1843 Value *Vec = vectorizeTree(Operands);
1844 NewPhi->addIncoming(Vec, IBB);
1847 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1848 "Invalid number of incoming values");
1852 case Instruction::ExtractElement: {
1853 if (CanReuseExtract(E->Scalars)) {
1854 Value *V = VL0->getOperand(0);
1855 E->VectorizedValue = V;
1858 return Gather(E->Scalars, VecTy);
1860 case Instruction::ZExt:
1861 case Instruction::SExt:
1862 case Instruction::FPToUI:
1863 case Instruction::FPToSI:
1864 case Instruction::FPExt:
1865 case Instruction::PtrToInt:
1866 case Instruction::IntToPtr:
1867 case Instruction::SIToFP:
1868 case Instruction::UIToFP:
1869 case Instruction::Trunc:
1870 case Instruction::FPTrunc:
1871 case Instruction::BitCast: {
1873 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1874 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1876 setInsertPointAfterBundle(E->Scalars);
1878 Value *InVec = vectorizeTree(INVL);
1880 if (Value *V = alreadyVectorized(E->Scalars))
1883 CastInst *CI = dyn_cast<CastInst>(VL0);
1884 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1885 E->VectorizedValue = V;
1886 ++NumVectorInstructions;
1889 case Instruction::FCmp:
1890 case Instruction::ICmp: {
1891 ValueList LHSV, RHSV;
1892 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1893 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1894 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1897 setInsertPointAfterBundle(E->Scalars);
1899 Value *L = vectorizeTree(LHSV);
1900 Value *R = vectorizeTree(RHSV);
1902 if (Value *V = alreadyVectorized(E->Scalars))
1905 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1907 if (Opcode == Instruction::FCmp)
1908 V = Builder.CreateFCmp(P0, L, R);
1910 V = Builder.CreateICmp(P0, L, R);
1912 E->VectorizedValue = V;
1913 ++NumVectorInstructions;
1916 case Instruction::Select: {
1917 ValueList TrueVec, FalseVec, CondVec;
1918 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1919 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1920 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1921 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1924 setInsertPointAfterBundle(E->Scalars);
1926 Value *Cond = vectorizeTree(CondVec);
1927 Value *True = vectorizeTree(TrueVec);
1928 Value *False = vectorizeTree(FalseVec);
1930 if (Value *V = alreadyVectorized(E->Scalars))
1933 Value *V = Builder.CreateSelect(Cond, True, False);
1934 E->VectorizedValue = V;
1935 ++NumVectorInstructions;
1938 case Instruction::Add:
1939 case Instruction::FAdd:
1940 case Instruction::Sub:
1941 case Instruction::FSub:
1942 case Instruction::Mul:
1943 case Instruction::FMul:
1944 case Instruction::UDiv:
1945 case Instruction::SDiv:
1946 case Instruction::FDiv:
1947 case Instruction::URem:
1948 case Instruction::SRem:
1949 case Instruction::FRem:
1950 case Instruction::Shl:
1951 case Instruction::LShr:
1952 case Instruction::AShr:
1953 case Instruction::And:
1954 case Instruction::Or:
1955 case Instruction::Xor: {
1956 ValueList LHSVL, RHSVL;
1957 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1958 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1960 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1961 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1962 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1965 setInsertPointAfterBundle(E->Scalars);
1967 Value *LHS = vectorizeTree(LHSVL);
1968 Value *RHS = vectorizeTree(RHSVL);
1970 if (LHS == RHS && isa<Instruction>(LHS)) {
1971 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1974 if (Value *V = alreadyVectorized(E->Scalars))
1977 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1978 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1979 E->VectorizedValue = V;
1980 ++NumVectorInstructions;
1982 if (Instruction *I = dyn_cast<Instruction>(V))
1983 return propagateMetadata(I, E->Scalars);
1987 case Instruction::Load: {
1988 // Loads are inserted at the head of the tree because we don't want to
1989 // sink them all the way down past store instructions.
1990 setInsertPointAfterBundle(E->Scalars);
1992 LoadInst *LI = cast<LoadInst>(VL0);
1993 unsigned AS = LI->getPointerAddressSpace();
1995 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1996 VecTy->getPointerTo(AS));
1997 unsigned Alignment = LI->getAlignment();
1998 LI = Builder.CreateLoad(VecPtr);
2000 Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
2001 LI->setAlignment(Alignment);
2002 E->VectorizedValue = LI;
2003 ++NumVectorInstructions;
2004 return propagateMetadata(LI, E->Scalars);
2006 case Instruction::Store: {
2007 StoreInst *SI = cast<StoreInst>(VL0);
2008 unsigned Alignment = SI->getAlignment();
2009 unsigned AS = SI->getPointerAddressSpace();
2012 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2013 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2015 setInsertPointAfterBundle(E->Scalars);
2017 Value *VecValue = vectorizeTree(ValueOp);
2018 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2019 VecTy->getPointerTo(AS));
2020 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2022 Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
2023 S->setAlignment(Alignment);
2024 E->VectorizedValue = S;
2025 ++NumVectorInstructions;
2026 return propagateMetadata(S, E->Scalars);
2028 case Instruction::GetElementPtr: {
2029 setInsertPointAfterBundle(E->Scalars);
2032 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2033 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2035 Value *Op0 = vectorizeTree(Op0VL);
2037 std::vector<Value *> OpVecs;
2038 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2041 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2042 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2044 Value *OpVec = vectorizeTree(OpVL);
2045 OpVecs.push_back(OpVec);
2048 Value *V = Builder.CreateGEP(Op0, OpVecs);
2049 E->VectorizedValue = V;
2050 ++NumVectorInstructions;
2052 if (Instruction *I = dyn_cast<Instruction>(V))
2053 return propagateMetadata(I, E->Scalars);
2057 case Instruction::Call: {
2058 CallInst *CI = cast<CallInst>(VL0);
2059 setInsertPointAfterBundle(E->Scalars);
2061 Intrinsic::ID IID = Intrinsic::not_intrinsic;
2062 if (CI && (FI = CI->getCalledFunction())) {
2063 IID = (Intrinsic::ID) FI->getIntrinsicID();
2065 std::vector<Value *> OpVecs;
2066 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2068 // ctlz,cttz and powi are special intrinsics whose second argument is
2069 // a scalar. This argument should not be vectorized.
2070 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2071 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2072 OpVecs.push_back(CEI->getArgOperand(j));
2075 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2076 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2077 OpVL.push_back(CEI->getArgOperand(j));
2080 Value *OpVec = vectorizeTree(OpVL);
2081 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2082 OpVecs.push_back(OpVec);
2085 Module *M = F->getParent();
2086 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2087 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2088 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2089 Value *V = Builder.CreateCall(CF, OpVecs);
2090 E->VectorizedValue = V;
2091 ++NumVectorInstructions;
2094 case Instruction::ShuffleVector: {
2095 ValueList LHSVL, RHSVL;
2096 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2097 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2098 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2100 setInsertPointAfterBundle(E->Scalars);
2102 Value *LHS = vectorizeTree(LHSVL);
2103 Value *RHS = vectorizeTree(RHSVL);
2105 if (Value *V = alreadyVectorized(E->Scalars))
2108 // Create a vector of LHS op1 RHS
2109 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2110 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2112 // Create a vector of LHS op2 RHS
2113 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2114 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2115 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2117 // Create appropriate shuffle to take alternative operations from
2119 std::vector<Constant *> Mask(E->Scalars.size());
2120 unsigned e = E->Scalars.size();
2121 for (unsigned i = 0; i < e; ++i) {
2123 Mask[i] = Builder.getInt32(e + i);
2125 Mask[i] = Builder.getInt32(i);
2128 Value *ShuffleMask = ConstantVector::get(Mask);
2130 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2131 E->VectorizedValue = V;
2132 ++NumVectorInstructions;
2133 if (Instruction *I = dyn_cast<Instruction>(V))
2134 return propagateMetadata(I, E->Scalars);
2139 llvm_unreachable("unknown inst");
2144 Value *BoUpSLP::vectorizeTree() {
2146 // All blocks must be scheduled before any instructions are inserted.
2147 for (auto &BSIter : BlocksSchedules) {
2148 scheduleBlock(BSIter.second.get());
2151 Builder.SetInsertPoint(F->getEntryBlock().begin());
2152 vectorizeTree(&VectorizableTree[0]);
2154 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2156 // Extract all of the elements with the external uses.
2157 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2159 Value *Scalar = it->Scalar;
2160 llvm::User *User = it->User;
2162 // Skip users that we already RAUW. This happens when one instruction
2163 // has multiple uses of the same value.
2164 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2167 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2169 int Idx = ScalarToTreeEntry[Scalar];
2170 TreeEntry *E = &VectorizableTree[Idx];
2171 assert(!E->NeedToGather && "Extracting from a gather list");
2173 Value *Vec = E->VectorizedValue;
2174 assert(Vec && "Can't find vectorizable value");
2176 Value *Lane = Builder.getInt32(it->Lane);
2177 // Generate extracts for out-of-tree users.
2178 // Find the insertion point for the extractelement lane.
2179 if (isa<Instruction>(Vec)){
2180 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2181 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2182 if (PH->getIncomingValue(i) == Scalar) {
2183 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2184 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2185 CSEBlocks.insert(PH->getIncomingBlock(i));
2186 PH->setOperand(i, Ex);
2190 Builder.SetInsertPoint(cast<Instruction>(User));
2191 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2192 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2193 User->replaceUsesOfWith(Scalar, Ex);
2196 Builder.SetInsertPoint(F->getEntryBlock().begin());
2197 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2198 CSEBlocks.insert(&F->getEntryBlock());
2199 User->replaceUsesOfWith(Scalar, Ex);
2202 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2205 // For each vectorized value:
2206 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2207 TreeEntry *Entry = &VectorizableTree[EIdx];
2210 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2211 Value *Scalar = Entry->Scalars[Lane];
2212 // No need to handle users of gathered values.
2213 if (Entry->NeedToGather)
2216 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2218 Type *Ty = Scalar->getType();
2219 if (!Ty->isVoidTy()) {
2221 for (User *U : Scalar->users()) {
2222 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2224 assert((ScalarToTreeEntry.count(U) ||
2225 // It is legal to replace users in the ignorelist by undef.
2226 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2227 UserIgnoreList.end())) &&
2228 "Replacing out-of-tree value with undef");
2231 Value *Undef = UndefValue::get(Ty);
2232 Scalar->replaceAllUsesWith(Undef);
2234 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2235 cast<Instruction>(Scalar)->eraseFromParent();
2239 Builder.ClearInsertionPoint();
2241 return VectorizableTree[0].VectorizedValue;
2244 void BoUpSLP::optimizeGatherSequence() {
2245 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2246 << " gather sequences instructions.\n");
2247 // LICM InsertElementInst sequences.
2248 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2249 e = GatherSeq.end(); it != e; ++it) {
2250 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2255 // Check if this block is inside a loop.
2256 Loop *L = LI->getLoopFor(Insert->getParent());
2260 // Check if it has a preheader.
2261 BasicBlock *PreHeader = L->getLoopPreheader();
2265 // If the vector or the element that we insert into it are
2266 // instructions that are defined in this basic block then we can't
2267 // hoist this instruction.
2268 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2269 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2270 if (CurrVec && L->contains(CurrVec))
2272 if (NewElem && L->contains(NewElem))
2275 // We can hoist this instruction. Move it to the pre-header.
2276 Insert->moveBefore(PreHeader->getTerminator());
2279 // Make a list of all reachable blocks in our CSE queue.
2280 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2281 CSEWorkList.reserve(CSEBlocks.size());
2282 for (BasicBlock *BB : CSEBlocks)
2283 if (DomTreeNode *N = DT->getNode(BB)) {
2284 assert(DT->isReachableFromEntry(N));
2285 CSEWorkList.push_back(N);
2288 // Sort blocks by domination. This ensures we visit a block after all blocks
2289 // dominating it are visited.
2290 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2291 [this](const DomTreeNode *A, const DomTreeNode *B) {
2292 return DT->properlyDominates(A, B);
2295 // Perform O(N^2) search over the gather sequences and merge identical
2296 // instructions. TODO: We can further optimize this scan if we split the
2297 // instructions into different buckets based on the insert lane.
2298 SmallVector<Instruction *, 16> Visited;
2299 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2300 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2301 "Worklist not sorted properly!");
2302 BasicBlock *BB = (*I)->getBlock();
2303 // For all instructions in blocks containing gather sequences:
2304 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2305 Instruction *In = it++;
2306 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2309 // Check if we can replace this instruction with any of the
2310 // visited instructions.
2311 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2314 if (In->isIdenticalTo(*v) &&
2315 DT->dominates((*v)->getParent(), In->getParent())) {
2316 In->replaceAllUsesWith(*v);
2317 In->eraseFromParent();
2323 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2324 Visited.push_back(In);
2332 // Groups the instructions to a bundle (which is then a single scheduling entity)
2333 // and schedules instructions until the bundle gets ready.
2334 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2335 AliasAnalysis *AA) {
2336 if (isa<PHINode>(VL[0]))
2339 // Initialize the instruction bundle.
2340 Instruction *OldScheduleEnd = ScheduleEnd;
2341 ScheduleData *PrevInBundle = nullptr;
2342 ScheduleData *Bundle = nullptr;
2343 bool ReSchedule = false;
2344 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2345 for (Value *V : VL) {
2346 extendSchedulingRegion(V);
2347 ScheduleData *BundleMember = getScheduleData(V);
2348 assert(BundleMember &&
2349 "no ScheduleData for bundle member (maybe not in same basic block)");
2350 if (BundleMember->IsScheduled) {
2351 // A bundle member was scheduled as single instruction before and now
2352 // needs to be scheduled as part of the bundle. We just get rid of the
2353 // existing schedule.
2354 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2355 << " was already scheduled\n");
2358 assert(BundleMember->isSchedulingEntity() &&
2359 "bundle member already part of other bundle");
2361 PrevInBundle->NextInBundle = BundleMember;
2363 Bundle = BundleMember;
2365 BundleMember->UnscheduledDepsInBundle = 0;
2366 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2368 // Group the instructions to a bundle.
2369 BundleMember->FirstInBundle = Bundle;
2370 PrevInBundle = BundleMember;
2372 if (ScheduleEnd != OldScheduleEnd) {
2373 // The scheduling region got new instructions at the lower end (or it is a
2374 // new region for the first bundle). This makes it necessary to
2375 // recalculate all dependencies.
2376 // It is seldom that this needs to be done a second time after adding the
2377 // initial bundle to the region.
2378 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2379 ScheduleData *SD = getScheduleData(I);
2380 SD->clearDependencies();
2386 initialFillReadyList(ReadyInsts);
2389 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2390 << BB->getName() << "\n");
2392 calculateDependencies(Bundle, true, AA);
2394 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2395 // means that there are no cyclic dependencies and we can schedule it.
2396 // Note that's important that we don't "schedule" the bundle yet (see
2397 // cancelScheduling).
2398 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2400 ScheduleData *pickedSD = ReadyInsts.back();
2401 ReadyInsts.pop_back();
2403 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2404 schedule(pickedSD, ReadyInsts);
2407 return Bundle->isReady();
2410 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2411 if (isa<PHINode>(VL[0]))
2414 ScheduleData *Bundle = getScheduleData(VL[0]);
2415 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2416 assert(!Bundle->IsScheduled &&
2417 "Can't cancel bundle which is already scheduled");
2418 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2419 "tried to unbundle something which is not a bundle");
2421 // Un-bundle: make single instructions out of the bundle.
2422 ScheduleData *BundleMember = Bundle;
2423 while (BundleMember) {
2424 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2425 BundleMember->FirstInBundle = BundleMember;
2426 ScheduleData *Next = BundleMember->NextInBundle;
2427 BundleMember->NextInBundle = nullptr;
2428 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2429 if (BundleMember->UnscheduledDepsInBundle == 0) {
2430 ReadyInsts.insert(BundleMember);
2432 BundleMember = Next;
2436 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2437 if (getScheduleData(V))
2439 Instruction *I = dyn_cast<Instruction>(V);
2440 assert(I && "bundle member must be an instruction");
2441 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2442 if (!ScheduleStart) {
2443 // It's the first instruction in the new region.
2444 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2446 ScheduleEnd = I->getNextNode();
2447 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2448 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2451 // Search up and down at the same time, because we don't know if the new
2452 // instruction is above or below the existing scheduling region.
2453 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2454 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2455 BasicBlock::iterator DownIter(ScheduleEnd);
2456 BasicBlock::iterator LowerEnd = BB->end();
2458 if (UpIter != UpperEnd) {
2459 if (&*UpIter == I) {
2460 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2462 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2467 if (DownIter != LowerEnd) {
2468 if (&*DownIter == I) {
2469 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2471 ScheduleEnd = I->getNextNode();
2472 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2473 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2478 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2479 "instruction not found in block");
2483 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2485 ScheduleData *PrevLoadStore,
2486 ScheduleData *NextLoadStore) {
2487 ScheduleData *CurrentLoadStore = PrevLoadStore;
2488 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2489 ScheduleData *SD = ScheduleDataMap[I];
2491 // Allocate a new ScheduleData for the instruction.
2492 if (ChunkPos >= ChunkSize) {
2493 ScheduleDataChunks.push_back(
2494 llvm::make_unique<ScheduleData[]>(ChunkSize));
2497 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2498 ScheduleDataMap[I] = SD;
2501 assert(!isInSchedulingRegion(SD) &&
2502 "new ScheduleData already in scheduling region");
2503 SD->init(SchedulingRegionID);
2505 if (I->mayReadOrWriteMemory()) {
2506 // Update the linked list of memory accessing instructions.
2507 if (CurrentLoadStore) {
2508 CurrentLoadStore->NextLoadStore = SD;
2510 FirstLoadStoreInRegion = SD;
2512 CurrentLoadStore = SD;
2515 if (NextLoadStore) {
2516 if (CurrentLoadStore)
2517 CurrentLoadStore->NextLoadStore = NextLoadStore;
2519 LastLoadStoreInRegion = CurrentLoadStore;
2523 /// \returns the AA location that is being access by the instruction.
2524 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
2525 if (StoreInst *SI = dyn_cast<StoreInst>(I))
2526 return AA->getLocation(SI);
2527 if (LoadInst *LI = dyn_cast<LoadInst>(I))
2528 return AA->getLocation(LI);
2529 return AliasAnalysis::Location();
2532 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2533 bool InsertInReadyList,
2534 AliasAnalysis *AA) {
2535 assert(SD->isSchedulingEntity());
2537 SmallVector<ScheduleData *, 10> WorkList;
2538 WorkList.push_back(SD);
2540 while (!WorkList.empty()) {
2541 ScheduleData *SD = WorkList.back();
2542 WorkList.pop_back();
2544 ScheduleData *BundleMember = SD;
2545 while (BundleMember) {
2546 assert(isInSchedulingRegion(BundleMember));
2547 if (!BundleMember->hasValidDependencies()) {
2549 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2550 BundleMember->Dependencies = 0;
2551 BundleMember->resetUnscheduledDeps();
2553 // Handle def-use chain dependencies.
2554 for (User *U : BundleMember->Inst->users()) {
2555 if (isa<Instruction>(U)) {
2556 ScheduleData *UseSD = getScheduleData(U);
2557 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2558 BundleMember->Dependencies++;
2559 ScheduleData *DestBundle = UseSD->FirstInBundle;
2560 if (!DestBundle->IsScheduled) {
2561 BundleMember->incrementUnscheduledDeps(1);
2563 if (!DestBundle->hasValidDependencies()) {
2564 WorkList.push_back(DestBundle);
2568 // I'm not sure if this can ever happen. But we need to be safe.
2569 // This lets the instruction/bundle never be scheduled and eventally
2570 // disable vectorization.
2571 BundleMember->Dependencies++;
2572 BundleMember->incrementUnscheduledDeps(1);
2576 // Handle the memory dependencies.
2577 ScheduleData *DepDest = BundleMember->NextLoadStore;
2579 AliasAnalysis::Location SrcLoc = getLocation(BundleMember->Inst, AA);
2580 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2583 assert(isInSchedulingRegion(DepDest));
2584 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2585 AliasAnalysis::Location DstLoc = getLocation(DepDest->Inst, AA);
2586 if (!SrcLoc.Ptr || !DstLoc.Ptr || AA->alias(SrcLoc, DstLoc)) {
2587 DepDest->MemoryDependencies.push_back(BundleMember);
2588 BundleMember->Dependencies++;
2589 ScheduleData *DestBundle = DepDest->FirstInBundle;
2590 if (!DestBundle->IsScheduled) {
2591 BundleMember->incrementUnscheduledDeps(1);
2593 if (!DestBundle->hasValidDependencies()) {
2594 WorkList.push_back(DestBundle);
2598 DepDest = DepDest->NextLoadStore;
2602 BundleMember = BundleMember->NextInBundle;
2604 if (InsertInReadyList && SD->isReady()) {
2605 ReadyInsts.push_back(SD);
2606 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2611 void BoUpSLP::BlockScheduling::resetSchedule() {
2612 assert(ScheduleStart &&
2613 "tried to reset schedule on block which has not been scheduled");
2614 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2615 ScheduleData *SD = getScheduleData(I);
2616 assert(isInSchedulingRegion(SD));
2617 SD->IsScheduled = false;
2618 SD->resetUnscheduledDeps();
2623 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2625 if (!BS->ScheduleStart)
2628 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2630 BS->resetSchedule();
2632 // For the real scheduling we use a more sophisticated ready-list: it is
2633 // sorted by the original instruction location. This lets the final schedule
2634 // be as close as possible to the original instruction order.
2635 struct ScheduleDataCompare {
2636 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2637 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2640 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2642 // Ensure that all depencency data is updated and fill the ready-list with
2643 // initial instructions.
2645 int NumToSchedule = 0;
2646 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2647 I = I->getNextNode()) {
2648 ScheduleData *SD = BS->getScheduleData(I);
2650 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2651 "scheduler and vectorizer have different opinion on what is a bundle");
2652 SD->FirstInBundle->SchedulingPriority = Idx++;
2653 if (SD->isSchedulingEntity()) {
2654 BS->calculateDependencies(SD, false, AA);
2658 BS->initialFillReadyList(ReadyInsts);
2660 Instruction *LastScheduledInst = BS->ScheduleEnd;
2662 // Do the "real" scheduling.
2663 while (!ReadyInsts.empty()) {
2664 ScheduleData *picked = *ReadyInsts.begin();
2665 ReadyInsts.erase(ReadyInsts.begin());
2667 // Move the scheduled instruction(s) to their dedicated places, if not
2669 ScheduleData *BundleMember = picked;
2670 while (BundleMember) {
2671 Instruction *pickedInst = BundleMember->Inst;
2672 if (LastScheduledInst->getNextNode() != pickedInst) {
2673 BS->BB->getInstList().remove(pickedInst);
2674 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2676 LastScheduledInst = pickedInst;
2677 BundleMember = BundleMember->NextInBundle;
2680 BS->schedule(picked, ReadyInsts);
2683 assert(NumToSchedule == 0 && "could not schedule all instructions");
2685 // Avoid duplicate scheduling of the block.
2686 BS->ScheduleStart = nullptr;
2689 /// The SLPVectorizer Pass.
2690 struct SLPVectorizer : public FunctionPass {
2691 typedef SmallVector<StoreInst *, 8> StoreList;
2692 typedef MapVector<Value *, StoreList> StoreListMap;
2694 /// Pass identification, replacement for typeid
2697 explicit SLPVectorizer() : FunctionPass(ID) {
2698 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2701 ScalarEvolution *SE;
2702 const DataLayout *DL;
2703 TargetTransformInfo *TTI;
2704 TargetLibraryInfo *TLI;
2709 bool runOnFunction(Function &F) override {
2710 if (skipOptnoneFunction(F))
2713 SE = &getAnalysis<ScalarEvolution>();
2714 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2715 DL = DLP ? &DLP->getDataLayout() : nullptr;
2716 TTI = &getAnalysis<TargetTransformInfo>();
2717 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2718 AA = &getAnalysis<AliasAnalysis>();
2719 LI = &getAnalysis<LoopInfo>();
2720 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2723 bool Changed = false;
2725 // If the target claims to have no vector registers don't attempt
2727 if (!TTI->getNumberOfRegisters(true))
2730 // Must have DataLayout. We can't require it because some tests run w/o
2735 // Don't vectorize when the attribute NoImplicitFloat is used.
2736 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2739 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2741 // Use the bottom up slp vectorizer to construct chains that start with
2742 // store instructions.
2743 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2745 // Scan the blocks in the function in post order.
2746 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2747 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2748 BasicBlock *BB = *it;
2749 // Vectorize trees that end at stores.
2750 if (unsigned count = collectStores(BB, R)) {
2752 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2753 Changed |= vectorizeStoreChains(R);
2756 // Vectorize trees that end at reductions.
2757 Changed |= vectorizeChainsInBlock(BB, R);
2761 R.optimizeGatherSequence();
2762 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2763 DEBUG(verifyFunction(F));
2768 void getAnalysisUsage(AnalysisUsage &AU) const override {
2769 FunctionPass::getAnalysisUsage(AU);
2770 AU.addRequired<ScalarEvolution>();
2771 AU.addRequired<AliasAnalysis>();
2772 AU.addRequired<TargetTransformInfo>();
2773 AU.addRequired<LoopInfo>();
2774 AU.addRequired<DominatorTreeWrapperPass>();
2775 AU.addPreserved<LoopInfo>();
2776 AU.addPreserved<DominatorTreeWrapperPass>();
2777 AU.setPreservesCFG();
2782 /// \brief Collect memory references and sort them according to their base
2783 /// object. We sort the stores to their base objects to reduce the cost of the
2784 /// quadratic search on the stores. TODO: We can further reduce this cost
2785 /// if we flush the chain creation every time we run into a memory barrier.
2786 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2788 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2789 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2791 /// \brief Try to vectorize a list of operands.
2792 /// \@param BuildVector A list of users to ignore for the purpose of
2793 /// scheduling and that don't need extracting.
2794 /// \returns true if a value was vectorized.
2795 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2796 ArrayRef<Value *> BuildVector = None,
2797 bool allowReorder = false);
2799 /// \brief Try to vectorize a chain that may start at the operands of \V;
2800 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2802 /// \brief Vectorize the stores that were collected in StoreRefs.
2803 bool vectorizeStoreChains(BoUpSLP &R);
2805 /// \brief Scan the basic block and look for patterns that are likely to start
2806 /// a vectorization chain.
2807 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2809 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2812 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2815 StoreListMap StoreRefs;
2818 /// \brief Check that the Values in the slice in VL array are still existent in
2819 /// the WeakVH array.
2820 /// Vectorization of part of the VL array may cause later values in the VL array
2821 /// to become invalid. We track when this has happened in the WeakVH array.
2822 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2823 SmallVectorImpl<WeakVH> &VH,
2824 unsigned SliceBegin,
2825 unsigned SliceSize) {
2826 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2833 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2834 int CostThreshold, BoUpSLP &R) {
2835 unsigned ChainLen = Chain.size();
2836 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2838 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2839 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2840 unsigned VF = MinVecRegSize / Sz;
2842 if (!isPowerOf2_32(Sz) || VF < 2)
2845 // Keep track of values that were deleted by vectorizing in the loop below.
2846 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2848 bool Changed = false;
2849 // Look for profitable vectorizable trees at all offsets, starting at zero.
2850 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2854 // Check that a previous iteration of this loop did not delete the Value.
2855 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2858 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2860 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2862 R.buildTree(Operands);
2864 int Cost = R.getTreeCost();
2866 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2867 if (Cost < CostThreshold) {
2868 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2871 // Move to the next bundle.
2880 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2881 int costThreshold, BoUpSLP &R) {
2882 SetVector<Value *> Heads, Tails;
2883 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2885 // We may run into multiple chains that merge into a single chain. We mark the
2886 // stores that we vectorized so that we don't visit the same store twice.
2887 BoUpSLP::ValueSet VectorizedStores;
2888 bool Changed = false;
2890 // Do a quadratic search on all of the given stores and find
2891 // all of the pairs of stores that follow each other.
2892 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2893 for (unsigned j = 0; j < e; ++j) {
2897 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2898 Tails.insert(Stores[j]);
2899 Heads.insert(Stores[i]);
2900 ConsecutiveChain[Stores[i]] = Stores[j];
2905 // For stores that start but don't end a link in the chain:
2906 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2908 if (Tails.count(*it))
2911 // We found a store instr that starts a chain. Now follow the chain and try
2913 BoUpSLP::ValueList Operands;
2915 // Collect the chain into a list.
2916 while (Tails.count(I) || Heads.count(I)) {
2917 if (VectorizedStores.count(I))
2919 Operands.push_back(I);
2920 // Move to the next value in the chain.
2921 I = ConsecutiveChain[I];
2924 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2926 // Mark the vectorized stores so that we don't vectorize them again.
2928 VectorizedStores.insert(Operands.begin(), Operands.end());
2929 Changed |= Vectorized;
2936 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2939 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2940 StoreInst *SI = dyn_cast<StoreInst>(it);
2944 // Don't touch volatile stores.
2945 if (!SI->isSimple())
2948 // Check that the pointer points to scalars.
2949 Type *Ty = SI->getValueOperand()->getType();
2950 if (Ty->isAggregateType() || Ty->isVectorTy())
2953 // Find the base pointer.
2954 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2956 // Save the store locations.
2957 StoreRefs[Ptr].push_back(SI);
2963 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2966 Value *VL[] = { A, B };
2967 return tryToVectorizeList(VL, R, None, true);
2970 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2971 ArrayRef<Value *> BuildVector,
2972 bool allowReorder) {
2976 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2978 // Check that all of the parts are scalar instructions of the same type.
2979 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2983 unsigned Opcode0 = I0->getOpcode();
2985 Type *Ty0 = I0->getType();
2986 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2987 unsigned VF = MinVecRegSize / Sz;
2989 for (int i = 0, e = VL.size(); i < e; ++i) {
2990 Type *Ty = VL[i]->getType();
2991 if (Ty->isAggregateType() || Ty->isVectorTy())
2993 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2994 if (!Inst || Inst->getOpcode() != Opcode0)
2998 bool Changed = false;
3000 // Keep track of values that were deleted by vectorizing in the loop below.
3001 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3003 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3004 unsigned OpsWidth = 0;
3011 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3014 // Check that a previous iteration of this loop did not delete the Value.
3015 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3018 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3020 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3022 ArrayRef<Value *> BuildVectorSlice;
3023 if (!BuildVector.empty())
3024 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3026 R.buildTree(Ops, BuildVectorSlice);
3027 // TODO: check if we can allow reordering also for other cases than
3028 // tryToVectorizePair()
3029 if (allowReorder && R.shouldReorder()) {
3030 assert(Ops.size() == 2);
3031 assert(BuildVectorSlice.empty());
3032 Value *ReorderedOps[] = { Ops[1], Ops[0] };
3033 R.buildTree(ReorderedOps, None);
3035 int Cost = R.getTreeCost();
3037 if (Cost < -SLPCostThreshold) {
3038 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3039 Value *VectorizedRoot = R.vectorizeTree();
3041 // Reconstruct the build vector by extracting the vectorized root. This
3042 // way we handle the case where some elements of the vector are undefined.
3043 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3044 if (!BuildVectorSlice.empty()) {
3045 // The insert point is the last build vector instruction. The vectorized
3046 // root will precede it. This guarantees that we get an instruction. The
3047 // vectorized tree could have been constant folded.
3048 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3049 unsigned VecIdx = 0;
3050 for (auto &V : BuildVectorSlice) {
3051 IRBuilder<true, NoFolder> Builder(
3052 ++BasicBlock::iterator(InsertAfter));
3053 InsertElementInst *IE = cast<InsertElementInst>(V);
3054 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3055 VectorizedRoot, Builder.getInt32(VecIdx++)));
3056 IE->setOperand(1, Extract);
3057 IE->removeFromParent();
3058 IE->insertAfter(Extract);
3062 // Move to the next bundle.
3071 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3075 // Try to vectorize V.
3076 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3079 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3080 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3082 if (B && B->hasOneUse()) {
3083 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3084 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3085 if (tryToVectorizePair(A, B0, R)) {
3089 if (tryToVectorizePair(A, B1, R)) {
3096 if (A && A->hasOneUse()) {
3097 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3098 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3099 if (tryToVectorizePair(A0, B, R)) {
3103 if (tryToVectorizePair(A1, B, R)) {
3111 /// \brief Generate a shuffle mask to be used in a reduction tree.
3113 /// \param VecLen The length of the vector to be reduced.
3114 /// \param NumEltsToRdx The number of elements that should be reduced in the
3116 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3117 /// reduction. A pairwise reduction will generate a mask of
3118 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3119 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3120 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3121 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3122 bool IsPairwise, bool IsLeft,
3123 IRBuilder<> &Builder) {
3124 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3126 SmallVector<Constant *, 32> ShuffleMask(
3127 VecLen, UndefValue::get(Builder.getInt32Ty()));
3130 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3131 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3132 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3134 // Move the upper half of the vector to the lower half.
3135 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3136 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3138 return ConstantVector::get(ShuffleMask);
3142 /// Model horizontal reductions.
3144 /// A horizontal reduction is a tree of reduction operations (currently add and
3145 /// fadd) that has operations that can be put into a vector as its leaf.
3146 /// For example, this tree:
3153 /// This tree has "mul" as its reduced values and "+" as its reduction
3154 /// operations. A reduction might be feeding into a store or a binary operation
3169 class HorizontalReduction {
3170 SmallVector<Value *, 16> ReductionOps;
3171 SmallVector<Value *, 32> ReducedVals;
3173 BinaryOperator *ReductionRoot;
3174 PHINode *ReductionPHI;
3176 /// The opcode of the reduction.
3177 unsigned ReductionOpcode;
3178 /// The opcode of the values we perform a reduction on.
3179 unsigned ReducedValueOpcode;
3180 /// The width of one full horizontal reduction operation.
3181 unsigned ReduxWidth;
3182 /// Should we model this reduction as a pairwise reduction tree or a tree that
3183 /// splits the vector in halves and adds those halves.
3184 bool IsPairwiseReduction;
3187 HorizontalReduction()
3188 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3189 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3191 /// \brief Try to find a reduction tree.
3192 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3193 const DataLayout *DL) {
3195 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3196 "Thi phi needs to use the binary operator");
3198 // We could have a initial reductions that is not an add.
3199 // r *= v1 + v2 + v3 + v4
3200 // In such a case start looking for a tree rooted in the first '+'.
3202 if (B->getOperand(0) == Phi) {
3204 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3205 } else if (B->getOperand(1) == Phi) {
3207 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3214 Type *Ty = B->getType();
3215 if (Ty->isVectorTy())
3218 ReductionOpcode = B->getOpcode();
3219 ReducedValueOpcode = 0;
3220 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3227 // We currently only support adds.
3228 if (ReductionOpcode != Instruction::Add &&
3229 ReductionOpcode != Instruction::FAdd)
3232 // Post order traverse the reduction tree starting at B. We only handle true
3233 // trees containing only binary operators.
3234 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3235 Stack.push_back(std::make_pair(B, 0));
3236 while (!Stack.empty()) {
3237 BinaryOperator *TreeN = Stack.back().first;
3238 unsigned EdgeToVist = Stack.back().second++;
3239 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3241 // Only handle trees in the current basic block.
3242 if (TreeN->getParent() != B->getParent())
3245 // Each tree node needs to have one user except for the ultimate
3247 if (!TreeN->hasOneUse() && TreeN != B)
3251 if (EdgeToVist == 2 || IsReducedValue) {
3252 if (IsReducedValue) {
3253 // Make sure that the opcodes of the operations that we are going to
3255 if (!ReducedValueOpcode)
3256 ReducedValueOpcode = TreeN->getOpcode();
3257 else if (ReducedValueOpcode != TreeN->getOpcode())
3259 ReducedVals.push_back(TreeN);
3261 // We need to be able to reassociate the adds.
3262 if (!TreeN->isAssociative())
3264 ReductionOps.push_back(TreeN);
3271 // Visit left or right.
3272 Value *NextV = TreeN->getOperand(EdgeToVist);
3273 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3275 Stack.push_back(std::make_pair(Next, 0));
3276 else if (NextV != Phi)
3282 /// \brief Attempt to vectorize the tree found by
3283 /// matchAssociativeReduction.
3284 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3285 if (ReducedVals.empty())
3288 unsigned NumReducedVals = ReducedVals.size();
3289 if (NumReducedVals < ReduxWidth)
3292 Value *VectorizedTree = nullptr;
3293 IRBuilder<> Builder(ReductionRoot);
3294 FastMathFlags Unsafe;
3295 Unsafe.setUnsafeAlgebra();
3296 Builder.SetFastMathFlags(Unsafe);
3299 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3300 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
3301 V.buildTree(ValsToReduce, ReductionOps);
3304 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3305 if (Cost >= -SLPCostThreshold)
3308 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3311 // Vectorize a tree.
3312 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3313 Value *VectorizedRoot = V.vectorizeTree();
3315 // Emit a reduction.
3316 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3317 if (VectorizedTree) {
3318 Builder.SetCurrentDebugLocation(Loc);
3319 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3320 ReducedSubTree, "bin.rdx");
3322 VectorizedTree = ReducedSubTree;
3325 if (VectorizedTree) {
3326 // Finish the reduction.
3327 for (; i < NumReducedVals; ++i) {
3328 Builder.SetCurrentDebugLocation(
3329 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3330 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3335 assert(ReductionRoot && "Need a reduction operation");
3336 ReductionRoot->setOperand(0, VectorizedTree);
3337 ReductionRoot->setOperand(1, ReductionPHI);
3339 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3341 return VectorizedTree != nullptr;
3346 /// \brief Calcuate the cost of a reduction.
3347 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3348 Type *ScalarTy = FirstReducedVal->getType();
3349 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3351 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3352 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3354 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3355 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3357 int ScalarReduxCost =
3358 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3360 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3361 << " for reduction that starts with " << *FirstReducedVal
3363 << (IsPairwiseReduction ? "pairwise" : "splitting")
3364 << " reduction)\n");
3366 return VecReduxCost - ScalarReduxCost;
3369 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3370 Value *R, const Twine &Name = "") {
3371 if (Opcode == Instruction::FAdd)
3372 return Builder.CreateFAdd(L, R, Name);
3373 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3376 /// \brief Emit a horizontal reduction of the vectorized value.
3377 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3378 assert(VectorizedValue && "Need to have a vectorized tree node");
3379 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
3380 assert(isPowerOf2_32(ReduxWidth) &&
3381 "We only handle power-of-two reductions for now");
3383 Value *TmpVec = ValToReduce;
3384 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3385 if (IsPairwiseReduction) {
3387 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3389 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3391 Value *LeftShuf = Builder.CreateShuffleVector(
3392 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3393 Value *RightShuf = Builder.CreateShuffleVector(
3394 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3396 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3400 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3401 Value *Shuf = Builder.CreateShuffleVector(
3402 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3403 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3407 // The result is in the first element of the vector.
3408 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3412 /// \brief Recognize construction of vectors like
3413 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3414 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3415 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3416 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3418 /// Returns true if it matches
3420 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3421 SmallVectorImpl<Value *> &BuildVector,
3422 SmallVectorImpl<Value *> &BuildVectorOpds) {
3423 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3426 InsertElementInst *IE = FirstInsertElem;
3428 BuildVector.push_back(IE);
3429 BuildVectorOpds.push_back(IE->getOperand(1));
3431 if (IE->use_empty())
3434 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3438 // If this isn't the final use, make sure the next insertelement is the only
3439 // use. It's OK if the final constructed vector is used multiple times
3440 if (!IE->hasOneUse())
3449 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3450 return V->getType() < V2->getType();
3453 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3454 bool Changed = false;
3455 SmallVector<Value *, 4> Incoming;
3456 SmallSet<Value *, 16> VisitedInstrs;
3458 bool HaveVectorizedPhiNodes = true;
3459 while (HaveVectorizedPhiNodes) {
3460 HaveVectorizedPhiNodes = false;
3462 // Collect the incoming values from the PHIs.
3464 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3466 PHINode *P = dyn_cast<PHINode>(instr);
3470 if (!VisitedInstrs.count(P))
3471 Incoming.push_back(P);
3475 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3477 // Try to vectorize elements base on their type.
3478 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3482 // Look for the next elements with the same type.
3483 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3484 while (SameTypeIt != E &&
3485 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3486 VisitedInstrs.insert(*SameTypeIt);
3490 // Try to vectorize them.
3491 unsigned NumElts = (SameTypeIt - IncIt);
3492 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3494 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
3495 // Success start over because instructions might have been changed.
3496 HaveVectorizedPhiNodes = true;
3501 // Start over at the next instruction of a different type (or the end).
3506 VisitedInstrs.clear();
3508 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3509 // We may go through BB multiple times so skip the one we have checked.
3510 if (!VisitedInstrs.insert(it))
3513 if (isa<DbgInfoIntrinsic>(it))
3516 // Try to vectorize reductions that use PHINodes.
3517 if (PHINode *P = dyn_cast<PHINode>(it)) {
3518 // Check that the PHI is a reduction PHI.
3519 if (P->getNumIncomingValues() != 2)
3522 (P->getIncomingBlock(0) == BB
3523 ? (P->getIncomingValue(0))
3524 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3526 // Check if this is a Binary Operator.
3527 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3531 // Try to match and vectorize a horizontal reduction.
3532 HorizontalReduction HorRdx;
3533 if (ShouldVectorizeHor &&
3534 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3535 HorRdx.tryToReduce(R, TTI)) {
3542 Value *Inst = BI->getOperand(0);
3544 Inst = BI->getOperand(1);
3546 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3547 // We would like to start over since some instructions are deleted
3548 // and the iterator may become invalid value.
3558 // Try to vectorize horizontal reductions feeding into a store.
3559 if (ShouldStartVectorizeHorAtStore)
3560 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3561 if (BinaryOperator *BinOp =
3562 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3563 HorizontalReduction HorRdx;
3564 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3565 HorRdx.tryToReduce(R, TTI)) ||
3566 tryToVectorize(BinOp, R))) {
3574 // Try to vectorize trees that start at compare instructions.
3575 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3576 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3578 // We would like to start over since some instructions are deleted
3579 // and the iterator may become invalid value.
3585 for (int i = 0; i < 2; ++i) {
3586 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3587 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3589 // We would like to start over since some instructions are deleted
3590 // and the iterator may become invalid value.
3599 // Try to vectorize trees that start at insertelement instructions.
3600 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3601 SmallVector<Value *, 16> BuildVector;
3602 SmallVector<Value *, 16> BuildVectorOpds;
3603 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3606 // Vectorize starting with the build vector operands ignoring the
3607 // BuildVector instructions for the purpose of scheduling and user
3609 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3622 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3623 bool Changed = false;
3624 // Attempt to sort and vectorize each of the store-groups.
3625 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3627 if (it->second.size() < 2)
3630 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3631 << it->second.size() << ".\n");
3633 // Process the stores in chunks of 16.
3634 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3635 unsigned Len = std::min<unsigned>(CE - CI, 16);
3636 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
3637 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
3643 } // end anonymous namespace
3645 char SLPVectorizer::ID = 0;
3646 static const char lv_name[] = "SLP Vectorizer";
3647 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3648 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3649 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3650 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3651 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3652 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3655 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }