1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/NoFolder.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/Utils/VectorUtils.h"
50 #define SV_NAME "slp-vectorizer"
51 #define DEBUG_TYPE "SLP"
53 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
56 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
57 cl::desc("Only vectorize if you gain more than this "
61 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
62 cl::desc("Attempt to vectorize horizontal reductions"));
64 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
65 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
67 "Attempt to vectorize horizontal reductions feeding into a store"));
71 static const unsigned MinVecRegSize = 128;
73 static const unsigned RecursionMaxDepth = 12;
75 /// \returns the parent basic block if all of the instructions in \p VL
76 /// are in the same block or null otherwise.
77 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
78 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
81 BasicBlock *BB = I0->getParent();
82 for (int i = 1, e = VL.size(); i < e; i++) {
83 Instruction *I = dyn_cast<Instruction>(VL[i]);
87 if (BB != I->getParent())
93 /// \returns True if all of the values in \p VL are constants.
94 static bool allConstant(ArrayRef<Value *> VL) {
95 for (unsigned i = 0, e = VL.size(); i < e; ++i)
96 if (!isa<Constant>(VL[i]))
101 /// \returns True if all of the values in \p VL are identical.
102 static bool isSplat(ArrayRef<Value *> VL) {
103 for (unsigned i = 1, e = VL.size(); i < e; ++i)
109 ///\returns Opcode that can be clubbed with \p Op to create an alternate
110 /// sequence which can later be merged as a ShuffleVector instruction.
111 static unsigned getAltOpcode(unsigned Op) {
113 case Instruction::FAdd:
114 return Instruction::FSub;
115 case Instruction::FSub:
116 return Instruction::FAdd;
117 case Instruction::Add:
118 return Instruction::Sub;
119 case Instruction::Sub:
120 return Instruction::Add;
126 ///\returns bool representing if Opcode \p Op can be part
127 /// of an alternate sequence which can later be merged as
128 /// a ShuffleVector instruction.
129 static bool canCombineAsAltInst(unsigned Op) {
130 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
131 Op == Instruction::Sub || Op == Instruction::Add)
136 /// \returns ShuffleVector instruction if intructions in \p VL have
137 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
138 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
139 static unsigned isAltInst(ArrayRef<Value *> VL) {
140 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
141 unsigned Opcode = I0->getOpcode();
142 unsigned AltOpcode = getAltOpcode(Opcode);
143 for (int i = 1, e = VL.size(); i < e; i++) {
144 Instruction *I = dyn_cast<Instruction>(VL[i]);
145 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
148 return Instruction::ShuffleVector;
151 /// \returns The opcode if all of the Instructions in \p VL have the same
153 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
154 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
157 unsigned Opcode = I0->getOpcode();
158 for (int i = 1, e = VL.size(); i < e; i++) {
159 Instruction *I = dyn_cast<Instruction>(VL[i]);
160 if (!I || Opcode != I->getOpcode()) {
161 if (canCombineAsAltInst(Opcode) && i == 1)
162 return isAltInst(VL);
169 /// \returns \p I after propagating metadata from \p VL.
170 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
171 Instruction *I0 = cast<Instruction>(VL[0]);
172 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
173 I0->getAllMetadataOtherThanDebugLoc(Metadata);
175 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
176 unsigned Kind = Metadata[i].first;
177 MDNode *MD = Metadata[i].second;
179 for (int i = 1, e = VL.size(); MD && i != e; i++) {
180 Instruction *I = cast<Instruction>(VL[i]);
181 MDNode *IMD = I->getMetadata(Kind);
185 MD = nullptr; // Remove unknown metadata
187 case LLVMContext::MD_tbaa:
188 MD = MDNode::getMostGenericTBAA(MD, IMD);
190 case LLVMContext::MD_alias_scope:
191 case LLVMContext::MD_noalias:
192 MD = MDNode::intersect(MD, IMD);
194 case LLVMContext::MD_fpmath:
195 MD = MDNode::getMostGenericFPMath(MD, IMD);
199 I->setMetadata(Kind, MD);
204 /// \returns The type that all of the values in \p VL have or null if there
205 /// are different types.
206 static Type* getSameType(ArrayRef<Value *> VL) {
207 Type *Ty = VL[0]->getType();
208 for (int i = 1, e = VL.size(); i < e; i++)
209 if (VL[i]->getType() != Ty)
215 /// \returns True if the ExtractElement instructions in VL can be vectorized
216 /// to use the original vector.
217 static bool CanReuseExtract(ArrayRef<Value *> VL) {
218 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
219 // Check if all of the extracts come from the same vector and from the
222 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
223 Value *Vec = E0->getOperand(0);
225 // We have to extract from the same vector type.
226 unsigned NElts = Vec->getType()->getVectorNumElements();
228 if (NElts != VL.size())
231 // Check that all of the indices extract from the correct offset.
232 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
233 if (!CI || CI->getZExtValue())
236 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
237 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
238 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
240 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
247 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
248 SmallVectorImpl<Value *> &Left,
249 SmallVectorImpl<Value *> &Right) {
251 SmallVector<Value *, 16> OrigLeft, OrigRight;
253 bool AllSameOpcodeLeft = true;
254 bool AllSameOpcodeRight = true;
255 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
256 Instruction *I = cast<Instruction>(VL[i]);
257 Value *V0 = I->getOperand(0);
258 Value *V1 = I->getOperand(1);
260 OrigLeft.push_back(V0);
261 OrigRight.push_back(V1);
263 Instruction *I0 = dyn_cast<Instruction>(V0);
264 Instruction *I1 = dyn_cast<Instruction>(V1);
266 // Check whether all operands on one side have the same opcode. In this case
267 // we want to preserve the original order and not make things worse by
269 AllSameOpcodeLeft = I0;
270 AllSameOpcodeRight = I1;
272 if (i && AllSameOpcodeLeft) {
273 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
274 if(P0->getOpcode() != I0->getOpcode())
275 AllSameOpcodeLeft = false;
277 AllSameOpcodeLeft = false;
279 if (i && AllSameOpcodeRight) {
280 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
281 if(P1->getOpcode() != I1->getOpcode())
282 AllSameOpcodeRight = false;
284 AllSameOpcodeRight = false;
287 // Sort two opcodes. In the code below we try to preserve the ability to use
288 // broadcast of values instead of individual inserts.
295 // If we just sorted according to opcode we would leave the first line in
296 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
299 // Because vr2 and vr1 are from the same load we loose the opportunity of a
300 // broadcast for the packed right side in the backend: we have [vr1, vl2]
301 // instead of [vr1, vr2=vr1].
303 if(!i && I0->getOpcode() > I1->getOpcode()) {
306 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
307 // Try not to destroy a broad cast for no apparent benefit.
310 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
311 // Try preserve broadcasts.
314 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
315 // Try preserve broadcasts.
324 // One opcode, put the instruction on the right.
334 bool LeftBroadcast = isSplat(Left);
335 bool RightBroadcast = isSplat(Right);
337 // Don't reorder if the operands where good to begin with.
338 if (!(LeftBroadcast || RightBroadcast) &&
339 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
345 /// Bottom Up SLP Vectorizer.
348 typedef SmallVector<Value *, 8> ValueList;
349 typedef SmallVector<Instruction *, 16> InstrList;
350 typedef SmallPtrSet<Value *, 16> ValueSet;
351 typedef SmallVector<StoreInst *, 8> StoreList;
353 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
354 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
355 LoopInfo *Li, DominatorTree *Dt)
356 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0),
357 F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
358 Builder(Se->getContext()) {}
360 /// \brief Vectorize the tree that starts with the elements in \p VL.
361 /// Returns the vectorized root.
362 Value *vectorizeTree();
364 /// \returns the vectorization cost of the subtree that starts at \p VL.
365 /// A negative number means that this is profitable.
368 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
369 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
370 void buildTree(ArrayRef<Value *> Roots,
371 ArrayRef<Value *> UserIgnoreLst = None);
373 /// Clear the internal data structures that are created by 'buildTree'.
375 VectorizableTree.clear();
376 ScalarToTreeEntry.clear();
378 ExternalUses.clear();
379 NumLoadsWantToKeepOrder = 0;
380 NumLoadsWantToChangeOrder = 0;
381 for (auto &Iter : BlocksSchedules) {
382 BlockScheduling *BS = Iter.second.get();
387 /// \returns true if the memory operations A and B are consecutive.
388 bool isConsecutiveAccess(Value *A, Value *B);
390 /// \brief Perform LICM and CSE on the newly generated gather sequences.
391 void optimizeGatherSequence();
393 /// \returns true if it is benefitial to reverse the vector order.
394 bool shouldReorder() const {
395 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
401 /// \returns the cost of the vectorizable entry.
402 int getEntryCost(TreeEntry *E);
404 /// This is the recursive part of buildTree.
405 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
407 /// Vectorize a single entry in the tree.
408 Value *vectorizeTree(TreeEntry *E);
410 /// Vectorize a single entry in the tree, starting in \p VL.
411 Value *vectorizeTree(ArrayRef<Value *> VL);
413 /// \returns the pointer to the vectorized value if \p VL is already
414 /// vectorized, or NULL. They may happen in cycles.
415 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
417 /// \brief Take the pointer operand from the Load/Store instruction.
418 /// \returns NULL if this is not a valid Load/Store instruction.
419 static Value *getPointerOperand(Value *I);
421 /// \brief Take the address space operand from the Load/Store instruction.
422 /// \returns -1 if this is not a valid Load/Store instruction.
423 static unsigned getAddressSpaceOperand(Value *I);
425 /// \returns the scalarization cost for this type. Scalarization in this
426 /// context means the creation of vectors from a group of scalars.
427 int getGatherCost(Type *Ty);
429 /// \returns the scalarization cost for this list of values. Assuming that
430 /// this subtree gets vectorized, we may need to extract the values from the
431 /// roots. This method calculates the cost of extracting the values.
432 int getGatherCost(ArrayRef<Value *> VL);
434 /// \brief Set the Builder insert point to one after the last instruction in
436 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
438 /// \returns a vector from a collection of scalars in \p VL.
439 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
441 /// \returns whether the VectorizableTree is fully vectoriable and will
442 /// be beneficial even the tree height is tiny.
443 bool isFullyVectorizableTinyTree();
446 TreeEntry() : Scalars(), VectorizedValue(nullptr),
449 /// \returns true if the scalars in VL are equal to this entry.
450 bool isSame(ArrayRef<Value *> VL) const {
451 assert(VL.size() == Scalars.size() && "Invalid size");
452 return std::equal(VL.begin(), VL.end(), Scalars.begin());
455 /// A vector of scalars.
458 /// The Scalars are vectorized into this value. It is initialized to Null.
459 Value *VectorizedValue;
461 /// Do we need to gather this sequence ?
465 /// Create a new VectorizableTree entry.
466 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
467 VectorizableTree.push_back(TreeEntry());
468 int idx = VectorizableTree.size() - 1;
469 TreeEntry *Last = &VectorizableTree[idx];
470 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
471 Last->NeedToGather = !Vectorized;
473 for (int i = 0, e = VL.size(); i != e; ++i) {
474 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
475 ScalarToTreeEntry[VL[i]] = idx;
478 MustGather.insert(VL.begin(), VL.end());
483 /// -- Vectorization State --
484 /// Holds all of the tree entries.
485 std::vector<TreeEntry> VectorizableTree;
487 /// Maps a specific scalar to its tree entry.
488 SmallDenseMap<Value*, int> ScalarToTreeEntry;
490 /// A list of scalars that we found that we need to keep as scalars.
493 /// This POD struct describes one external user in the vectorized tree.
494 struct ExternalUser {
495 ExternalUser (Value *S, llvm::User *U, int L) :
496 Scalar(S), User(U), Lane(L){};
497 // Which scalar in our function.
499 // Which user that uses the scalar.
501 // Which lane does the scalar belong to.
504 typedef SmallVector<ExternalUser, 16> UserList;
506 /// A list of values that need to extracted out of the tree.
507 /// This list holds pairs of (Internal Scalar : External User).
508 UserList ExternalUses;
510 /// Holds all of the instructions that we gathered.
511 SetVector<Instruction *> GatherSeq;
512 /// A list of blocks that we are going to CSE.
513 SetVector<BasicBlock *> CSEBlocks;
515 /// Contains all scheduling relevant data for an instruction.
516 /// A ScheduleData either represents a single instruction or a member of an
517 /// instruction bundle (= a group of instructions which is combined into a
518 /// vector instruction).
519 struct ScheduleData {
521 // The initial value for the dependency counters. It means that the
522 // dependencies are not calculated yet.
523 enum { InvalidDeps = -1 };
526 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
527 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
528 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
529 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
531 void init(int BlockSchedulingRegionID) {
532 FirstInBundle = this;
533 NextInBundle = nullptr;
534 NextLoadStore = nullptr;
536 SchedulingRegionID = BlockSchedulingRegionID;
537 UnscheduledDepsInBundle = UnscheduledDeps;
541 /// Returns true if the dependency information has been calculated.
542 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
544 /// Returns true for single instructions and for bundle representatives
545 /// (= the head of a bundle).
546 bool isSchedulingEntity() const { return FirstInBundle == this; }
548 /// Returns true if it represents an instruction bundle and not only a
549 /// single instruction.
550 bool isPartOfBundle() const {
551 return NextInBundle != nullptr || FirstInBundle != this;
554 /// Returns true if it is ready for scheduling, i.e. it has no more
555 /// unscheduled depending instructions/bundles.
556 bool isReady() const {
557 assert(isSchedulingEntity() &&
558 "can't consider non-scheduling entity for ready list");
559 return UnscheduledDepsInBundle == 0 && !IsScheduled;
562 /// Modifies the number of unscheduled dependencies, also updating it for
563 /// the whole bundle.
564 int incrementUnscheduledDeps(int Incr) {
565 UnscheduledDeps += Incr;
566 return FirstInBundle->UnscheduledDepsInBundle += Incr;
569 /// Sets the number of unscheduled dependencies to the number of
571 void resetUnscheduledDeps() {
572 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
575 /// Clears all dependency information.
576 void clearDependencies() {
577 Dependencies = InvalidDeps;
578 resetUnscheduledDeps();
579 MemoryDependencies.clear();
582 void dump(raw_ostream &os) const {
583 if (!isSchedulingEntity()) {
585 } else if (NextInBundle) {
587 ScheduleData *SD = NextInBundle;
589 os << ';' << *SD->Inst;
590 SD = SD->NextInBundle;
600 /// Points to the head in an instruction bundle (and always to this for
601 /// single instructions).
602 ScheduleData *FirstInBundle;
604 /// Single linked list of all instructions in a bundle. Null if it is a
605 /// single instruction.
606 ScheduleData *NextInBundle;
608 /// Single linked list of all memory instructions (e.g. load, store, call)
609 /// in the block - until the end of the scheduling region.
610 ScheduleData *NextLoadStore;
612 /// The dependent memory instructions.
613 /// This list is derived on demand in calculateDependencies().
614 SmallVector<ScheduleData *, 4> MemoryDependencies;
616 /// This ScheduleData is in the current scheduling region if this matches
617 /// the current SchedulingRegionID of BlockScheduling.
618 int SchedulingRegionID;
620 /// Used for getting a "good" final ordering of instructions.
621 int SchedulingPriority;
623 /// The number of dependencies. Constitutes of the number of users of the
624 /// instruction plus the number of dependent memory instructions (if any).
625 /// This value is calculated on demand.
626 /// If InvalidDeps, the number of dependencies is not calculated yet.
630 /// The number of dependencies minus the number of dependencies of scheduled
631 /// instructions. As soon as this is zero, the instruction/bundle gets ready
633 /// Note that this is negative as long as Dependencies is not calculated.
636 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
637 /// single instructions.
638 int UnscheduledDepsInBundle;
640 /// True if this instruction is scheduled (or considered as scheduled in the
646 friend raw_ostream &operator<<(raw_ostream &os,
647 const BoUpSLP::ScheduleData &SD);
650 /// Contains all scheduling data for a basic block.
652 struct BlockScheduling {
654 BlockScheduling(BasicBlock *BB)
655 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
656 ScheduleStart(nullptr), ScheduleEnd(nullptr),
657 FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
658 // Make sure that the initial SchedulingRegionID is greater than the
659 // initial SchedulingRegionID in ScheduleData (which is 0).
660 SchedulingRegionID(1) {}
664 ScheduleStart = nullptr;
665 ScheduleEnd = nullptr;
666 FirstLoadStoreInRegion = nullptr;
667 LastLoadStoreInRegion = nullptr;
669 // Make a new scheduling region, i.e. all existing ScheduleData is not
670 // in the new region yet.
671 ++SchedulingRegionID;
674 ScheduleData *getScheduleData(Value *V) {
675 ScheduleData *SD = ScheduleDataMap[V];
676 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
681 bool isInSchedulingRegion(ScheduleData *SD) {
682 return SD->SchedulingRegionID == SchedulingRegionID;
685 /// Marks an instruction as scheduled and puts all dependent ready
686 /// instructions into the ready-list.
687 template <typename ReadyListType>
688 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
689 SD->IsScheduled = true;
690 DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
692 ScheduleData *BundleMember = SD;
693 while (BundleMember) {
694 // Handle the def-use chain dependencies.
695 for (Use &U : BundleMember->Inst->operands()) {
696 ScheduleData *OpDef = getScheduleData(U.get());
697 if (OpDef && OpDef->hasValidDependencies() &&
698 OpDef->incrementUnscheduledDeps(-1) == 0) {
699 // There are no more unscheduled dependencies after decrementing,
700 // so we can put the dependent instruction into the ready list.
701 ScheduleData *DepBundle = OpDef->FirstInBundle;
702 assert(!DepBundle->IsScheduled &&
703 "already scheduled bundle gets ready");
704 ReadyList.insert(DepBundle);
705 DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
708 // Handle the memory dependencies.
709 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
710 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
711 // There are no more unscheduled dependencies after decrementing,
712 // so we can put the dependent instruction into the ready list.
713 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
714 assert(!DepBundle->IsScheduled &&
715 "already scheduled bundle gets ready");
716 ReadyList.insert(DepBundle);
717 DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
720 BundleMember = BundleMember->NextInBundle;
724 /// Put all instructions into the ReadyList which are ready for scheduling.
725 template <typename ReadyListType>
726 void initialFillReadyList(ReadyListType &ReadyList) {
727 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
728 ScheduleData *SD = getScheduleData(I);
729 if (SD->isSchedulingEntity() && SD->isReady()) {
730 ReadyList.insert(SD);
731 DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
736 /// Checks if a bundle of instructions can be scheduled, i.e. has no
737 /// cyclic dependencies. This is only a dry-run, no instructions are
738 /// actually moved at this stage.
739 bool tryScheduleBundle(ArrayRef<Value *> VL, AliasAnalysis *AA);
741 /// Un-bundles a group of instructions.
742 void cancelScheduling(ArrayRef<Value *> VL);
744 /// Extends the scheduling region so that V is inside the region.
745 void extendSchedulingRegion(Value *V);
747 /// Initialize the ScheduleData structures for new instructions in the
748 /// scheduling region.
749 void initScheduleData(Instruction *FromI, Instruction *ToI,
750 ScheduleData *PrevLoadStore,
751 ScheduleData *NextLoadStore);
753 /// Updates the dependency information of a bundle and of all instructions/
754 /// bundles which depend on the original bundle.
755 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
758 /// Sets all instruction in the scheduling region to un-scheduled.
759 void resetSchedule();
763 /// Simple memory allocation for ScheduleData.
764 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
766 /// The size of a ScheduleData array in ScheduleDataChunks.
769 /// The allocator position in the current chunk, which is the last entry
770 /// of ScheduleDataChunks.
773 /// Attaches ScheduleData to Instruction.
774 /// Note that the mapping survives during all vectorization iterations, i.e.
775 /// ScheduleData structures are recycled.
776 DenseMap<Value *, ScheduleData *> ScheduleDataMap;
778 struct ReadyList : SmallVector<ScheduleData *, 8> {
779 void insert(ScheduleData *SD) { push_back(SD); }
782 /// The ready-list for scheduling (only used for the dry-run).
783 ReadyList ReadyInsts;
785 /// The first instruction of the scheduling region.
786 Instruction *ScheduleStart;
788 /// The first instruction _after_ the scheduling region.
789 Instruction *ScheduleEnd;
791 /// The first memory accessing instruction in the scheduling region
793 ScheduleData *FirstLoadStoreInRegion;
795 /// The last memory accessing instruction in the scheduling region
797 ScheduleData *LastLoadStoreInRegion;
799 /// The ID of the scheduling region. For a new vectorization iteration this
800 /// is incremented which "removes" all ScheduleData from the region.
801 int SchedulingRegionID;
804 /// Attaches the BlockScheduling structures to basic blocks.
805 DenseMap<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
807 /// Performs the "real" scheduling. Done before vectorization is actually
808 /// performed in a basic block.
809 void scheduleBlock(BlockScheduling *BS);
811 /// List of users to ignore during scheduling and that don't need extracting.
812 ArrayRef<Value *> UserIgnoreList;
814 // Number of load-bundles, which contain consecutive loads.
815 int NumLoadsWantToKeepOrder;
817 // Number of load-bundles of size 2, which are consecutive loads if reversed.
818 int NumLoadsWantToChangeOrder;
820 // Analysis and block reference.
823 const DataLayout *DL;
824 TargetTransformInfo *TTI;
825 TargetLibraryInfo *TLI;
829 /// Instruction builder to construct the vectorized tree.
834 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
840 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
841 ArrayRef<Value *> UserIgnoreLst) {
843 UserIgnoreList = UserIgnoreLst;
844 if (!getSameType(Roots))
846 buildTree_rec(Roots, 0);
848 // Collect the values that we need to extract from the tree.
849 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
850 TreeEntry *Entry = &VectorizableTree[EIdx];
853 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
854 Value *Scalar = Entry->Scalars[Lane];
856 // No need to handle users of gathered values.
857 if (Entry->NeedToGather)
860 for (User *U : Scalar->users()) {
861 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
863 // Skip in-tree scalars that become vectors.
864 if (ScalarToTreeEntry.count(U)) {
865 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
867 int Idx = ScalarToTreeEntry[U]; (void) Idx;
868 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
871 Instruction *UserInst = dyn_cast<Instruction>(U);
875 // Ignore users in the user ignore list.
876 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
877 UserIgnoreList.end())
880 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
881 Lane << " from " << *Scalar << ".\n");
882 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
889 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
890 bool SameTy = getSameType(VL); (void)SameTy;
891 bool isAltShuffle = false;
892 assert(SameTy && "Invalid types!");
894 if (Depth == RecursionMaxDepth) {
895 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
896 newTreeEntry(VL, false);
900 // Don't handle vectors.
901 if (VL[0]->getType()->isVectorTy()) {
902 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
903 newTreeEntry(VL, false);
907 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
908 if (SI->getValueOperand()->getType()->isVectorTy()) {
909 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
910 newTreeEntry(VL, false);
913 unsigned Opcode = getSameOpcode(VL);
915 // Check that this shuffle vector refers to the alternate
916 // sequence of opcodes.
917 if (Opcode == Instruction::ShuffleVector) {
918 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
919 unsigned Op = I0->getOpcode();
920 if (Op != Instruction::ShuffleVector)
924 // If all of the operands are identical or constant we have a simple solution.
925 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
926 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
927 newTreeEntry(VL, false);
931 // We now know that this is a vector of instructions of the same type from
934 // Check if this is a duplicate of another entry.
935 if (ScalarToTreeEntry.count(VL[0])) {
936 int Idx = ScalarToTreeEntry[VL[0]];
937 TreeEntry *E = &VectorizableTree[Idx];
938 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
939 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
940 if (E->Scalars[i] != VL[i]) {
941 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
942 newTreeEntry(VL, false);
946 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
950 // Check that none of the instructions in the bundle are already in the tree.
951 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
952 if (ScalarToTreeEntry.count(VL[i])) {
953 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
954 ") is already in tree.\n");
955 newTreeEntry(VL, false);
960 // If any of the scalars appears in the table OR it is marked as a value that
961 // needs to stat scalar then we need to gather the scalars.
962 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
963 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
964 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
965 newTreeEntry(VL, false);
970 // Check that all of the users of the scalars that we want to vectorize are
972 Instruction *VL0 = cast<Instruction>(VL[0]);
973 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
975 // Check that every instructions appears once in this bundle.
976 for (unsigned i = 0, e = VL.size(); i < e; ++i)
977 for (unsigned j = i+1; j < e; ++j)
978 if (VL[i] == VL[j]) {
979 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
980 newTreeEntry(VL, false);
984 auto &BSRef = BlocksSchedules[BB];
986 BSRef = llvm::make_unique<BlockScheduling>(BB);
988 BlockScheduling &BS = *BSRef.get();
990 if (!BS.tryScheduleBundle(VL, AA)) {
991 DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
992 BS.cancelScheduling(VL);
993 newTreeEntry(VL, false);
996 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
999 case Instruction::PHI: {
1000 PHINode *PH = dyn_cast<PHINode>(VL0);
1002 // Check for terminator values (e.g. invoke).
1003 for (unsigned j = 0; j < VL.size(); ++j)
1004 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1005 TerminatorInst *Term = dyn_cast<TerminatorInst>(
1006 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1008 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1009 BS.cancelScheduling(VL);
1010 newTreeEntry(VL, false);
1015 newTreeEntry(VL, true);
1016 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1018 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1020 // Prepare the operand vector.
1021 for (unsigned j = 0; j < VL.size(); ++j)
1022 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1023 PH->getIncomingBlock(i)));
1025 buildTree_rec(Operands, Depth + 1);
1029 case Instruction::ExtractElement: {
1030 bool Reuse = CanReuseExtract(VL);
1032 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1034 BS.cancelScheduling(VL);
1036 newTreeEntry(VL, Reuse);
1039 case Instruction::Load: {
1040 // Check if the loads are consecutive or of we need to swizzle them.
1041 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1042 LoadInst *L = cast<LoadInst>(VL[i]);
1043 if (!L->isSimple()) {
1044 BS.cancelScheduling(VL);
1045 newTreeEntry(VL, false);
1046 DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1049 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1050 if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1051 ++NumLoadsWantToChangeOrder;
1053 BS.cancelScheduling(VL);
1054 newTreeEntry(VL, false);
1055 DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1059 ++NumLoadsWantToKeepOrder;
1060 newTreeEntry(VL, true);
1061 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1064 case Instruction::ZExt:
1065 case Instruction::SExt:
1066 case Instruction::FPToUI:
1067 case Instruction::FPToSI:
1068 case Instruction::FPExt:
1069 case Instruction::PtrToInt:
1070 case Instruction::IntToPtr:
1071 case Instruction::SIToFP:
1072 case Instruction::UIToFP:
1073 case Instruction::Trunc:
1074 case Instruction::FPTrunc:
1075 case Instruction::BitCast: {
1076 Type *SrcTy = VL0->getOperand(0)->getType();
1077 for (unsigned i = 0; i < VL.size(); ++i) {
1078 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1079 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1080 BS.cancelScheduling(VL);
1081 newTreeEntry(VL, false);
1082 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1086 newTreeEntry(VL, true);
1087 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1089 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1091 // Prepare the operand vector.
1092 for (unsigned j = 0; j < VL.size(); ++j)
1093 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1095 buildTree_rec(Operands, Depth+1);
1099 case Instruction::ICmp:
1100 case Instruction::FCmp: {
1101 // Check that all of the compares have the same predicate.
1102 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1103 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1104 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1105 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1106 if (Cmp->getPredicate() != P0 ||
1107 Cmp->getOperand(0)->getType() != ComparedTy) {
1108 BS.cancelScheduling(VL);
1109 newTreeEntry(VL, false);
1110 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1115 newTreeEntry(VL, true);
1116 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1118 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1120 // Prepare the operand vector.
1121 for (unsigned j = 0; j < VL.size(); ++j)
1122 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1124 buildTree_rec(Operands, Depth+1);
1128 case Instruction::Select:
1129 case Instruction::Add:
1130 case Instruction::FAdd:
1131 case Instruction::Sub:
1132 case Instruction::FSub:
1133 case Instruction::Mul:
1134 case Instruction::FMul:
1135 case Instruction::UDiv:
1136 case Instruction::SDiv:
1137 case Instruction::FDiv:
1138 case Instruction::URem:
1139 case Instruction::SRem:
1140 case Instruction::FRem:
1141 case Instruction::Shl:
1142 case Instruction::LShr:
1143 case Instruction::AShr:
1144 case Instruction::And:
1145 case Instruction::Or:
1146 case Instruction::Xor: {
1147 newTreeEntry(VL, true);
1148 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1150 // Sort operands of the instructions so that each side is more likely to
1151 // have the same opcode.
1152 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1153 ValueList Left, Right;
1154 reorderInputsAccordingToOpcode(VL, Left, Right);
1155 buildTree_rec(Left, Depth + 1);
1156 buildTree_rec(Right, Depth + 1);
1160 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1162 // Prepare the operand vector.
1163 for (unsigned j = 0; j < VL.size(); ++j)
1164 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1166 buildTree_rec(Operands, Depth+1);
1170 case Instruction::GetElementPtr: {
1171 // We don't combine GEPs with complicated (nested) indexing.
1172 for (unsigned j = 0; j < VL.size(); ++j) {
1173 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1174 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1175 BS.cancelScheduling(VL);
1176 newTreeEntry(VL, false);
1181 // We can't combine several GEPs into one vector if they operate on
1183 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1184 for (unsigned j = 0; j < VL.size(); ++j) {
1185 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1187 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1188 BS.cancelScheduling(VL);
1189 newTreeEntry(VL, false);
1194 // We don't combine GEPs with non-constant indexes.
1195 for (unsigned j = 0; j < VL.size(); ++j) {
1196 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1197 if (!isa<ConstantInt>(Op)) {
1199 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1200 BS.cancelScheduling(VL);
1201 newTreeEntry(VL, false);
1206 newTreeEntry(VL, true);
1207 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1208 for (unsigned i = 0, e = 2; i < e; ++i) {
1210 // Prepare the operand vector.
1211 for (unsigned j = 0; j < VL.size(); ++j)
1212 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1214 buildTree_rec(Operands, Depth + 1);
1218 case Instruction::Store: {
1219 // Check if the stores are consecutive or of we need to swizzle them.
1220 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1221 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1222 BS.cancelScheduling(VL);
1223 newTreeEntry(VL, false);
1224 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1228 newTreeEntry(VL, true);
1229 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1232 for (unsigned j = 0; j < VL.size(); ++j)
1233 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1235 buildTree_rec(Operands, Depth + 1);
1238 case Instruction::Call: {
1239 // Check if the calls are all to the same vectorizable intrinsic.
1240 CallInst *CI = cast<CallInst>(VL[0]);
1241 // Check if this is an Intrinsic call or something that can be
1242 // represented by an intrinsic call
1243 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1244 if (!isTriviallyVectorizable(ID)) {
1245 BS.cancelScheduling(VL);
1246 newTreeEntry(VL, false);
1247 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1250 Function *Int = CI->getCalledFunction();
1251 Value *A1I = nullptr;
1252 if (hasVectorInstrinsicScalarOpd(ID, 1))
1253 A1I = CI->getArgOperand(1);
1254 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1255 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1256 if (!CI2 || CI2->getCalledFunction() != Int ||
1257 getIntrinsicIDForCall(CI2, TLI) != ID) {
1258 BS.cancelScheduling(VL);
1259 newTreeEntry(VL, false);
1260 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1264 // ctlz,cttz and powi are special intrinsics whose second argument
1265 // should be same in order for them to be vectorized.
1266 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1267 Value *A1J = CI2->getArgOperand(1);
1269 BS.cancelScheduling(VL);
1270 newTreeEntry(VL, false);
1271 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1272 << " argument "<< A1I<<"!=" << A1J
1279 newTreeEntry(VL, true);
1280 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1282 // Prepare the operand vector.
1283 for (unsigned j = 0; j < VL.size(); ++j) {
1284 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1285 Operands.push_back(CI2->getArgOperand(i));
1287 buildTree_rec(Operands, Depth + 1);
1291 case Instruction::ShuffleVector: {
1292 // If this is not an alternate sequence of opcode like add-sub
1293 // then do not vectorize this instruction.
1294 if (!isAltShuffle) {
1295 BS.cancelScheduling(VL);
1296 newTreeEntry(VL, false);
1297 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1300 newTreeEntry(VL, true);
1301 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1302 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1304 // Prepare the operand vector.
1305 for (unsigned j = 0; j < VL.size(); ++j)
1306 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1308 buildTree_rec(Operands, Depth + 1);
1313 BS.cancelScheduling(VL);
1314 newTreeEntry(VL, false);
1315 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1320 int BoUpSLP::getEntryCost(TreeEntry *E) {
1321 ArrayRef<Value*> VL = E->Scalars;
1323 Type *ScalarTy = VL[0]->getType();
1324 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1325 ScalarTy = SI->getValueOperand()->getType();
1326 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1328 if (E->NeedToGather) {
1329 if (allConstant(VL))
1332 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1334 return getGatherCost(E->Scalars);
1336 unsigned Opcode = getSameOpcode(VL);
1337 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1338 Instruction *VL0 = cast<Instruction>(VL[0]);
1340 case Instruction::PHI: {
1343 case Instruction::ExtractElement: {
1344 if (CanReuseExtract(VL)) {
1346 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1347 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1349 // Take credit for instruction that will become dead.
1351 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1355 return getGatherCost(VecTy);
1357 case Instruction::ZExt:
1358 case Instruction::SExt:
1359 case Instruction::FPToUI:
1360 case Instruction::FPToSI:
1361 case Instruction::FPExt:
1362 case Instruction::PtrToInt:
1363 case Instruction::IntToPtr:
1364 case Instruction::SIToFP:
1365 case Instruction::UIToFP:
1366 case Instruction::Trunc:
1367 case Instruction::FPTrunc:
1368 case Instruction::BitCast: {
1369 Type *SrcTy = VL0->getOperand(0)->getType();
1371 // Calculate the cost of this instruction.
1372 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1373 VL0->getType(), SrcTy);
1375 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1376 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1377 return VecCost - ScalarCost;
1379 case Instruction::FCmp:
1380 case Instruction::ICmp:
1381 case Instruction::Select:
1382 case Instruction::Add:
1383 case Instruction::FAdd:
1384 case Instruction::Sub:
1385 case Instruction::FSub:
1386 case Instruction::Mul:
1387 case Instruction::FMul:
1388 case Instruction::UDiv:
1389 case Instruction::SDiv:
1390 case Instruction::FDiv:
1391 case Instruction::URem:
1392 case Instruction::SRem:
1393 case Instruction::FRem:
1394 case Instruction::Shl:
1395 case Instruction::LShr:
1396 case Instruction::AShr:
1397 case Instruction::And:
1398 case Instruction::Or:
1399 case Instruction::Xor: {
1400 // Calculate the cost of this instruction.
1403 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1404 Opcode == Instruction::Select) {
1405 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1406 ScalarCost = VecTy->getNumElements() *
1407 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1408 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1410 // Certain instructions can be cheaper to vectorize if they have a
1411 // constant second vector operand.
1412 TargetTransformInfo::OperandValueKind Op1VK =
1413 TargetTransformInfo::OK_AnyValue;
1414 TargetTransformInfo::OperandValueKind Op2VK =
1415 TargetTransformInfo::OK_UniformConstantValue;
1417 // If all operands are exactly the same ConstantInt then set the
1418 // operand kind to OK_UniformConstantValue.
1419 // If instead not all operands are constants, then set the operand kind
1420 // to OK_AnyValue. If all operands are constants but not the same,
1421 // then set the operand kind to OK_NonUniformConstantValue.
1422 ConstantInt *CInt = nullptr;
1423 for (unsigned i = 0; i < VL.size(); ++i) {
1424 const Instruction *I = cast<Instruction>(VL[i]);
1425 if (!isa<ConstantInt>(I->getOperand(1))) {
1426 Op2VK = TargetTransformInfo::OK_AnyValue;
1430 CInt = cast<ConstantInt>(I->getOperand(1));
1433 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1434 CInt != cast<ConstantInt>(I->getOperand(1)))
1435 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1439 VecTy->getNumElements() *
1440 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1441 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1443 return VecCost - ScalarCost;
1445 case Instruction::GetElementPtr: {
1446 TargetTransformInfo::OperandValueKind Op1VK =
1447 TargetTransformInfo::OK_AnyValue;
1448 TargetTransformInfo::OperandValueKind Op2VK =
1449 TargetTransformInfo::OK_UniformConstantValue;
1452 VecTy->getNumElements() *
1453 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1455 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1457 return VecCost - ScalarCost;
1459 case Instruction::Load: {
1460 // Cost of wide load - cost of scalar loads.
1461 int ScalarLdCost = VecTy->getNumElements() *
1462 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1463 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1464 return VecLdCost - ScalarLdCost;
1466 case Instruction::Store: {
1467 // We know that we can merge the stores. Calculate the cost.
1468 int ScalarStCost = VecTy->getNumElements() *
1469 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1470 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1471 return VecStCost - ScalarStCost;
1473 case Instruction::Call: {
1474 CallInst *CI = cast<CallInst>(VL0);
1475 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1477 // Calculate the cost of the scalar and vector calls.
1478 SmallVector<Type*, 4> ScalarTys, VecTys;
1479 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1480 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1481 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1482 VecTy->getNumElements()));
1485 int ScalarCallCost = VecTy->getNumElements() *
1486 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1488 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1490 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1491 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1492 << " for " << *CI << "\n");
1494 return VecCallCost - ScalarCallCost;
1496 case Instruction::ShuffleVector: {
1497 TargetTransformInfo::OperandValueKind Op1VK =
1498 TargetTransformInfo::OK_AnyValue;
1499 TargetTransformInfo::OperandValueKind Op2VK =
1500 TargetTransformInfo::OK_AnyValue;
1503 for (unsigned i = 0; i < VL.size(); ++i) {
1504 Instruction *I = cast<Instruction>(VL[i]);
1508 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1510 // VecCost is equal to sum of the cost of creating 2 vectors
1511 // and the cost of creating shuffle.
1512 Instruction *I0 = cast<Instruction>(VL[0]);
1514 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1515 Instruction *I1 = cast<Instruction>(VL[1]);
1517 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1519 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1520 return VecCost - ScalarCost;
1523 llvm_unreachable("Unknown instruction");
1527 bool BoUpSLP::isFullyVectorizableTinyTree() {
1528 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1529 VectorizableTree.size() << " is fully vectorizable .\n");
1531 // We only handle trees of height 2.
1532 if (VectorizableTree.size() != 2)
1535 // Handle splat stores.
1536 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1539 // Gathering cost would be too much for tiny trees.
1540 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1546 int BoUpSLP::getTreeCost() {
1548 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1549 VectorizableTree.size() << ".\n");
1551 // We only vectorize tiny trees if it is fully vectorizable.
1552 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1553 if (!VectorizableTree.size()) {
1554 assert(!ExternalUses.size() && "We should not have any external users");
1559 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1561 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1562 int C = getEntryCost(&VectorizableTree[i]);
1563 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1564 << *VectorizableTree[i].Scalars[0] << " .\n");
1568 SmallSet<Value *, 16> ExtractCostCalculated;
1569 int ExtractCost = 0;
1570 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1572 // We only add extract cost once for the same scalar.
1573 if (!ExtractCostCalculated.insert(I->Scalar))
1576 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1577 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1581 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1582 return Cost + ExtractCost;
1585 int BoUpSLP::getGatherCost(Type *Ty) {
1587 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1588 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1592 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1593 // Find the type of the operands in VL.
1594 Type *ScalarTy = VL[0]->getType();
1595 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1596 ScalarTy = SI->getValueOperand()->getType();
1597 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1598 // Find the cost of inserting/extracting values from the vector.
1599 return getGatherCost(VecTy);
1602 Value *BoUpSLP::getPointerOperand(Value *I) {
1603 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1604 return LI->getPointerOperand();
1605 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1606 return SI->getPointerOperand();
1610 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1611 if (LoadInst *L = dyn_cast<LoadInst>(I))
1612 return L->getPointerAddressSpace();
1613 if (StoreInst *S = dyn_cast<StoreInst>(I))
1614 return S->getPointerAddressSpace();
1618 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1619 Value *PtrA = getPointerOperand(A);
1620 Value *PtrB = getPointerOperand(B);
1621 unsigned ASA = getAddressSpaceOperand(A);
1622 unsigned ASB = getAddressSpaceOperand(B);
1624 // Check that the address spaces match and that the pointers are valid.
1625 if (!PtrA || !PtrB || (ASA != ASB))
1628 // Make sure that A and B are different pointers of the same type.
1629 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1632 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1633 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1634 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1636 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1637 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1638 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1640 APInt OffsetDelta = OffsetB - OffsetA;
1642 // Check if they are based on the same pointer. That makes the offsets
1645 return OffsetDelta == Size;
1647 // Compute the necessary base pointer delta to have the necessary final delta
1648 // equal to the size.
1649 APInt BaseDelta = Size - OffsetDelta;
1651 // Otherwise compute the distance with SCEV between the base pointers.
1652 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1653 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1654 const SCEV *C = SE->getConstant(BaseDelta);
1655 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1656 return X == PtrSCEVB;
1659 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1660 Instruction *VL0 = cast<Instruction>(VL[0]);
1661 BasicBlock::iterator NextInst = VL0;
1663 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1664 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1667 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1668 Value *Vec = UndefValue::get(Ty);
1669 // Generate the 'InsertElement' instruction.
1670 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1671 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1672 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1673 GatherSeq.insert(Insrt);
1674 CSEBlocks.insert(Insrt->getParent());
1676 // Add to our 'need-to-extract' list.
1677 if (ScalarToTreeEntry.count(VL[i])) {
1678 int Idx = ScalarToTreeEntry[VL[i]];
1679 TreeEntry *E = &VectorizableTree[Idx];
1680 // Find which lane we need to extract.
1682 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1683 // Is this the lane of the scalar that we are looking for ?
1684 if (E->Scalars[Lane] == VL[i]) {
1689 assert(FoundLane >= 0 && "Could not find the correct lane");
1690 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1698 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1699 SmallDenseMap<Value*, int>::const_iterator Entry
1700 = ScalarToTreeEntry.find(VL[0]);
1701 if (Entry != ScalarToTreeEntry.end()) {
1702 int Idx = Entry->second;
1703 const TreeEntry *En = &VectorizableTree[Idx];
1704 if (En->isSame(VL) && En->VectorizedValue)
1705 return En->VectorizedValue;
1710 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1711 if (ScalarToTreeEntry.count(VL[0])) {
1712 int Idx = ScalarToTreeEntry[VL[0]];
1713 TreeEntry *E = &VectorizableTree[Idx];
1715 return vectorizeTree(E);
1718 Type *ScalarTy = VL[0]->getType();
1719 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1720 ScalarTy = SI->getValueOperand()->getType();
1721 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1723 return Gather(VL, VecTy);
1726 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1727 IRBuilder<>::InsertPointGuard Guard(Builder);
1729 if (E->VectorizedValue) {
1730 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1731 return E->VectorizedValue;
1734 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1735 Type *ScalarTy = VL0->getType();
1736 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1737 ScalarTy = SI->getValueOperand()->getType();
1738 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1740 if (E->NeedToGather) {
1741 setInsertPointAfterBundle(E->Scalars);
1742 return Gather(E->Scalars, VecTy);
1745 unsigned Opcode = getSameOpcode(E->Scalars);
1748 case Instruction::PHI: {
1749 PHINode *PH = dyn_cast<PHINode>(VL0);
1750 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1751 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1752 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1753 E->VectorizedValue = NewPhi;
1755 // PHINodes may have multiple entries from the same block. We want to
1756 // visit every block once.
1757 SmallSet<BasicBlock*, 4> VisitedBBs;
1759 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1761 BasicBlock *IBB = PH->getIncomingBlock(i);
1763 if (!VisitedBBs.insert(IBB)) {
1764 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1768 // Prepare the operand vector.
1769 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1770 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1771 getIncomingValueForBlock(IBB));
1773 Builder.SetInsertPoint(IBB->getTerminator());
1774 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1775 Value *Vec = vectorizeTree(Operands);
1776 NewPhi->addIncoming(Vec, IBB);
1779 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1780 "Invalid number of incoming values");
1784 case Instruction::ExtractElement: {
1785 if (CanReuseExtract(E->Scalars)) {
1786 Value *V = VL0->getOperand(0);
1787 E->VectorizedValue = V;
1790 return Gather(E->Scalars, VecTy);
1792 case Instruction::ZExt:
1793 case Instruction::SExt:
1794 case Instruction::FPToUI:
1795 case Instruction::FPToSI:
1796 case Instruction::FPExt:
1797 case Instruction::PtrToInt:
1798 case Instruction::IntToPtr:
1799 case Instruction::SIToFP:
1800 case Instruction::UIToFP:
1801 case Instruction::Trunc:
1802 case Instruction::FPTrunc:
1803 case Instruction::BitCast: {
1805 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1806 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1808 setInsertPointAfterBundle(E->Scalars);
1810 Value *InVec = vectorizeTree(INVL);
1812 if (Value *V = alreadyVectorized(E->Scalars))
1815 CastInst *CI = dyn_cast<CastInst>(VL0);
1816 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1817 E->VectorizedValue = V;
1818 ++NumVectorInstructions;
1821 case Instruction::FCmp:
1822 case Instruction::ICmp: {
1823 ValueList LHSV, RHSV;
1824 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1825 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1826 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1829 setInsertPointAfterBundle(E->Scalars);
1831 Value *L = vectorizeTree(LHSV);
1832 Value *R = vectorizeTree(RHSV);
1834 if (Value *V = alreadyVectorized(E->Scalars))
1837 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1839 if (Opcode == Instruction::FCmp)
1840 V = Builder.CreateFCmp(P0, L, R);
1842 V = Builder.CreateICmp(P0, L, R);
1844 E->VectorizedValue = V;
1845 ++NumVectorInstructions;
1848 case Instruction::Select: {
1849 ValueList TrueVec, FalseVec, CondVec;
1850 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1851 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1852 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1853 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1856 setInsertPointAfterBundle(E->Scalars);
1858 Value *Cond = vectorizeTree(CondVec);
1859 Value *True = vectorizeTree(TrueVec);
1860 Value *False = vectorizeTree(FalseVec);
1862 if (Value *V = alreadyVectorized(E->Scalars))
1865 Value *V = Builder.CreateSelect(Cond, True, False);
1866 E->VectorizedValue = V;
1867 ++NumVectorInstructions;
1870 case Instruction::Add:
1871 case Instruction::FAdd:
1872 case Instruction::Sub:
1873 case Instruction::FSub:
1874 case Instruction::Mul:
1875 case Instruction::FMul:
1876 case Instruction::UDiv:
1877 case Instruction::SDiv:
1878 case Instruction::FDiv:
1879 case Instruction::URem:
1880 case Instruction::SRem:
1881 case Instruction::FRem:
1882 case Instruction::Shl:
1883 case Instruction::LShr:
1884 case Instruction::AShr:
1885 case Instruction::And:
1886 case Instruction::Or:
1887 case Instruction::Xor: {
1888 ValueList LHSVL, RHSVL;
1889 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1890 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1892 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1893 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1894 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1897 setInsertPointAfterBundle(E->Scalars);
1899 Value *LHS = vectorizeTree(LHSVL);
1900 Value *RHS = vectorizeTree(RHSVL);
1902 if (LHS == RHS && isa<Instruction>(LHS)) {
1903 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1906 if (Value *V = alreadyVectorized(E->Scalars))
1909 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1910 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1911 E->VectorizedValue = V;
1912 ++NumVectorInstructions;
1914 if (Instruction *I = dyn_cast<Instruction>(V))
1915 return propagateMetadata(I, E->Scalars);
1919 case Instruction::Load: {
1920 // Loads are inserted at the head of the tree because we don't want to
1921 // sink them all the way down past store instructions.
1922 setInsertPointAfterBundle(E->Scalars);
1924 LoadInst *LI = cast<LoadInst>(VL0);
1925 unsigned AS = LI->getPointerAddressSpace();
1927 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1928 VecTy->getPointerTo(AS));
1929 unsigned Alignment = LI->getAlignment();
1930 LI = Builder.CreateLoad(VecPtr);
1932 Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
1933 LI->setAlignment(Alignment);
1934 E->VectorizedValue = LI;
1935 ++NumVectorInstructions;
1936 return propagateMetadata(LI, E->Scalars);
1938 case Instruction::Store: {
1939 StoreInst *SI = cast<StoreInst>(VL0);
1940 unsigned Alignment = SI->getAlignment();
1941 unsigned AS = SI->getPointerAddressSpace();
1944 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1945 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1947 setInsertPointAfterBundle(E->Scalars);
1949 Value *VecValue = vectorizeTree(ValueOp);
1950 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1951 VecTy->getPointerTo(AS));
1952 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1954 Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
1955 S->setAlignment(Alignment);
1956 E->VectorizedValue = S;
1957 ++NumVectorInstructions;
1958 return propagateMetadata(S, E->Scalars);
1960 case Instruction::GetElementPtr: {
1961 setInsertPointAfterBundle(E->Scalars);
1964 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1965 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
1967 Value *Op0 = vectorizeTree(Op0VL);
1969 std::vector<Value *> OpVecs;
1970 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
1973 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1974 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
1976 Value *OpVec = vectorizeTree(OpVL);
1977 OpVecs.push_back(OpVec);
1980 Value *V = Builder.CreateGEP(Op0, OpVecs);
1981 E->VectorizedValue = V;
1982 ++NumVectorInstructions;
1984 if (Instruction *I = dyn_cast<Instruction>(V))
1985 return propagateMetadata(I, E->Scalars);
1989 case Instruction::Call: {
1990 CallInst *CI = cast<CallInst>(VL0);
1991 setInsertPointAfterBundle(E->Scalars);
1993 Intrinsic::ID IID = Intrinsic::not_intrinsic;
1994 if (CI && (FI = CI->getCalledFunction())) {
1995 IID = (Intrinsic::ID) FI->getIntrinsicID();
1997 std::vector<Value *> OpVecs;
1998 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2000 // ctlz,cttz and powi are special intrinsics whose second argument is
2001 // a scalar. This argument should not be vectorized.
2002 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2003 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2004 OpVecs.push_back(CEI->getArgOperand(j));
2007 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2008 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2009 OpVL.push_back(CEI->getArgOperand(j));
2012 Value *OpVec = vectorizeTree(OpVL);
2013 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2014 OpVecs.push_back(OpVec);
2017 Module *M = F->getParent();
2018 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2019 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2020 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2021 Value *V = Builder.CreateCall(CF, OpVecs);
2022 E->VectorizedValue = V;
2023 ++NumVectorInstructions;
2026 case Instruction::ShuffleVector: {
2027 ValueList LHSVL, RHSVL;
2028 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2029 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2030 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2032 setInsertPointAfterBundle(E->Scalars);
2034 Value *LHS = vectorizeTree(LHSVL);
2035 Value *RHS = vectorizeTree(RHSVL);
2037 if (Value *V = alreadyVectorized(E->Scalars))
2040 // Create a vector of LHS op1 RHS
2041 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2042 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2044 // Create a vector of LHS op2 RHS
2045 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2046 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2047 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2049 // Create appropriate shuffle to take alternative operations from
2051 std::vector<Constant *> Mask(E->Scalars.size());
2052 unsigned e = E->Scalars.size();
2053 for (unsigned i = 0; i < e; ++i) {
2055 Mask[i] = Builder.getInt32(e + i);
2057 Mask[i] = Builder.getInt32(i);
2060 Value *ShuffleMask = ConstantVector::get(Mask);
2062 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2063 E->VectorizedValue = V;
2064 ++NumVectorInstructions;
2065 if (Instruction *I = dyn_cast<Instruction>(V))
2066 return propagateMetadata(I, E->Scalars);
2071 llvm_unreachable("unknown inst");
2076 Value *BoUpSLP::vectorizeTree() {
2078 // All blocks must be scheduled before any instructions are inserted.
2079 for (auto &BSIter : BlocksSchedules) {
2080 scheduleBlock(BSIter.second.get());
2083 Builder.SetInsertPoint(F->getEntryBlock().begin());
2084 vectorizeTree(&VectorizableTree[0]);
2086 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2088 // Extract all of the elements with the external uses.
2089 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2091 Value *Scalar = it->Scalar;
2092 llvm::User *User = it->User;
2094 // Skip users that we already RAUW. This happens when one instruction
2095 // has multiple uses of the same value.
2096 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2099 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2101 int Idx = ScalarToTreeEntry[Scalar];
2102 TreeEntry *E = &VectorizableTree[Idx];
2103 assert(!E->NeedToGather && "Extracting from a gather list");
2105 Value *Vec = E->VectorizedValue;
2106 assert(Vec && "Can't find vectorizable value");
2108 Value *Lane = Builder.getInt32(it->Lane);
2109 // Generate extracts for out-of-tree users.
2110 // Find the insertion point for the extractelement lane.
2111 if (isa<Instruction>(Vec)){
2112 if (PHINode *PH = dyn_cast<PHINode>(User)) {
2113 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2114 if (PH->getIncomingValue(i) == Scalar) {
2115 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2116 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2117 CSEBlocks.insert(PH->getIncomingBlock(i));
2118 PH->setOperand(i, Ex);
2122 Builder.SetInsertPoint(cast<Instruction>(User));
2123 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2124 CSEBlocks.insert(cast<Instruction>(User)->getParent());
2125 User->replaceUsesOfWith(Scalar, Ex);
2128 Builder.SetInsertPoint(F->getEntryBlock().begin());
2129 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2130 CSEBlocks.insert(&F->getEntryBlock());
2131 User->replaceUsesOfWith(Scalar, Ex);
2134 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2137 // For each vectorized value:
2138 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2139 TreeEntry *Entry = &VectorizableTree[EIdx];
2142 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2143 Value *Scalar = Entry->Scalars[Lane];
2144 // No need to handle users of gathered values.
2145 if (Entry->NeedToGather)
2148 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2150 Type *Ty = Scalar->getType();
2151 if (!Ty->isVoidTy()) {
2153 for (User *U : Scalar->users()) {
2154 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2156 assert((ScalarToTreeEntry.count(U) ||
2157 // It is legal to replace users in the ignorelist by undef.
2158 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2159 UserIgnoreList.end())) &&
2160 "Replacing out-of-tree value with undef");
2163 Value *Undef = UndefValue::get(Ty);
2164 Scalar->replaceAllUsesWith(Undef);
2166 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2167 cast<Instruction>(Scalar)->eraseFromParent();
2171 Builder.ClearInsertionPoint();
2173 return VectorizableTree[0].VectorizedValue;
2176 void BoUpSLP::optimizeGatherSequence() {
2177 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2178 << " gather sequences instructions.\n");
2179 // LICM InsertElementInst sequences.
2180 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2181 e = GatherSeq.end(); it != e; ++it) {
2182 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2187 // Check if this block is inside a loop.
2188 Loop *L = LI->getLoopFor(Insert->getParent());
2192 // Check if it has a preheader.
2193 BasicBlock *PreHeader = L->getLoopPreheader();
2197 // If the vector or the element that we insert into it are
2198 // instructions that are defined in this basic block then we can't
2199 // hoist this instruction.
2200 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2201 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2202 if (CurrVec && L->contains(CurrVec))
2204 if (NewElem && L->contains(NewElem))
2207 // We can hoist this instruction. Move it to the pre-header.
2208 Insert->moveBefore(PreHeader->getTerminator());
2211 // Make a list of all reachable blocks in our CSE queue.
2212 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2213 CSEWorkList.reserve(CSEBlocks.size());
2214 for (BasicBlock *BB : CSEBlocks)
2215 if (DomTreeNode *N = DT->getNode(BB)) {
2216 assert(DT->isReachableFromEntry(N));
2217 CSEWorkList.push_back(N);
2220 // Sort blocks by domination. This ensures we visit a block after all blocks
2221 // dominating it are visited.
2222 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2223 [this](const DomTreeNode *A, const DomTreeNode *B) {
2224 return DT->properlyDominates(A, B);
2227 // Perform O(N^2) search over the gather sequences and merge identical
2228 // instructions. TODO: We can further optimize this scan if we split the
2229 // instructions into different buckets based on the insert lane.
2230 SmallVector<Instruction *, 16> Visited;
2231 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2232 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2233 "Worklist not sorted properly!");
2234 BasicBlock *BB = (*I)->getBlock();
2235 // For all instructions in blocks containing gather sequences:
2236 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2237 Instruction *In = it++;
2238 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2241 // Check if we can replace this instruction with any of the
2242 // visited instructions.
2243 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2246 if (In->isIdenticalTo(*v) &&
2247 DT->dominates((*v)->getParent(), In->getParent())) {
2248 In->replaceAllUsesWith(*v);
2249 In->eraseFromParent();
2255 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2256 Visited.push_back(In);
2264 // Groups the instructions to a bundle (which is then a single scheduling entity)
2265 // and schedules instructions until the bundle gets ready.
2266 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2267 AliasAnalysis *AA) {
2268 if (isa<PHINode>(VL[0]))
2271 // Initialize the instruction bundle.
2272 Instruction *OldScheduleEnd = ScheduleEnd;
2273 ScheduleData *PrevInBundle = nullptr;
2274 ScheduleData *Bundle = nullptr;
2275 bool ReSchedule = false;
2276 DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
2277 for (Value *V : VL) {
2278 extendSchedulingRegion(V);
2279 ScheduleData *BundleMember = getScheduleData(V);
2280 assert(BundleMember &&
2281 "no ScheduleData for bundle member (maybe not in same basic block)");
2282 if (BundleMember->IsScheduled) {
2283 // A bundle member was scheduled as single instruction before and now
2284 // needs to be scheduled as part of the bundle. We just get rid of the
2285 // existing schedule.
2286 DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
2287 << " was already scheduled\n");
2290 assert(BundleMember->isSchedulingEntity() &&
2291 "bundle member already part of other bundle");
2293 PrevInBundle->NextInBundle = BundleMember;
2295 Bundle = BundleMember;
2297 BundleMember->UnscheduledDepsInBundle = 0;
2298 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2300 // Group the instructions to a bundle.
2301 BundleMember->FirstInBundle = Bundle;
2302 PrevInBundle = BundleMember;
2304 if (ScheduleEnd != OldScheduleEnd) {
2305 // The scheduling region got new instructions at the lower end (or it is a
2306 // new region for the first bundle). This makes it necessary to
2307 // recalculate all dependencies.
2308 // It is seldom that this needs to be done a second time after adding the
2309 // initial bundle to the region.
2310 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2311 ScheduleData *SD = getScheduleData(I);
2312 SD->clearDependencies();
2318 initialFillReadyList(ReadyInsts);
2321 DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2322 << BB->getName() << "\n");
2324 calculateDependencies(Bundle, true, AA);
2326 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2327 // means that there are no cyclic dependencies and we can schedule it.
2328 // Note that's important that we don't "schedule" the bundle yet (see
2329 // cancelScheduling).
2330 while (!Bundle->isReady() && !ReadyInsts.empty()) {
2332 ScheduleData *pickedSD = ReadyInsts.back();
2333 ReadyInsts.pop_back();
2335 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2336 schedule(pickedSD, ReadyInsts);
2339 return Bundle->isReady();
2342 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2343 if (isa<PHINode>(VL[0]))
2346 ScheduleData *Bundle = getScheduleData(VL[0]);
2347 DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
2348 assert(!Bundle->IsScheduled &&
2349 "Can't cancel bundle which is already scheduled");
2350 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2351 "tried to unbundle something which is not a bundle");
2353 // Un-bundle: make single instructions out of the bundle.
2354 ScheduleData *BundleMember = Bundle;
2355 while (BundleMember) {
2356 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2357 BundleMember->FirstInBundle = BundleMember;
2358 ScheduleData *Next = BundleMember->NextInBundle;
2359 BundleMember->NextInBundle = nullptr;
2360 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2361 if (BundleMember->UnscheduledDepsInBundle == 0) {
2362 ReadyInsts.insert(BundleMember);
2364 BundleMember = Next;
2368 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2369 if (getScheduleData(V))
2371 Instruction *I = dyn_cast<Instruction>(V);
2372 assert(I && "bundle member must be an instruction");
2373 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2374 if (!ScheduleStart) {
2375 // It's the first instruction in the new region.
2376 initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2378 ScheduleEnd = I->getNextNode();
2379 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2380 DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
2383 // Search up and down at the same time, because we don't know if the new
2384 // instruction is above or below the existing scheduling region.
2385 BasicBlock::reverse_iterator UpIter(ScheduleStart);
2386 BasicBlock::reverse_iterator UpperEnd = BB->rend();
2387 BasicBlock::iterator DownIter(ScheduleEnd);
2388 BasicBlock::iterator LowerEnd = BB->end();
2390 if (UpIter != UpperEnd) {
2391 if (&*UpIter == I) {
2392 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2394 DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
2399 if (DownIter != LowerEnd) {
2400 if (&*DownIter == I) {
2401 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2403 ScheduleEnd = I->getNextNode();
2404 assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2405 DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
2410 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2411 "instruction not found in block");
2415 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2417 ScheduleData *PrevLoadStore,
2418 ScheduleData *NextLoadStore) {
2419 ScheduleData *CurrentLoadStore = PrevLoadStore;
2420 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2421 ScheduleData *SD = ScheduleDataMap[I];
2423 // Allocate a new ScheduleData for the instruction.
2424 if (ChunkPos >= ChunkSize) {
2425 ScheduleDataChunks.push_back(
2426 llvm::make_unique<ScheduleData[]>(ChunkSize));
2429 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2430 ScheduleDataMap[I] = SD;
2433 assert(!isInSchedulingRegion(SD) &&
2434 "new ScheduleData already in scheduling region");
2435 SD->init(SchedulingRegionID);
2437 if (I->mayReadOrWriteMemory()) {
2438 // Update the linked list of memory accessing instructions.
2439 if (CurrentLoadStore) {
2440 CurrentLoadStore->NextLoadStore = SD;
2442 FirstLoadStoreInRegion = SD;
2444 CurrentLoadStore = SD;
2447 if (NextLoadStore) {
2448 if (CurrentLoadStore)
2449 CurrentLoadStore->NextLoadStore = NextLoadStore;
2451 LastLoadStoreInRegion = CurrentLoadStore;
2455 /// \returns the AA location that is being access by the instruction.
2456 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
2457 if (StoreInst *SI = dyn_cast<StoreInst>(I))
2458 return AA->getLocation(SI);
2459 if (LoadInst *LI = dyn_cast<LoadInst>(I))
2460 return AA->getLocation(LI);
2461 return AliasAnalysis::Location();
2464 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2465 bool InsertInReadyList,
2466 AliasAnalysis *AA) {
2467 assert(SD->isSchedulingEntity());
2469 SmallVector<ScheduleData *, 10> WorkList;
2470 WorkList.push_back(SD);
2472 while (!WorkList.empty()) {
2473 ScheduleData *SD = WorkList.back();
2474 WorkList.pop_back();
2476 ScheduleData *BundleMember = SD;
2477 while (BundleMember) {
2478 assert(isInSchedulingRegion(BundleMember));
2479 if (!BundleMember->hasValidDependencies()) {
2481 DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
2482 BundleMember->Dependencies = 0;
2483 BundleMember->resetUnscheduledDeps();
2485 // Handle def-use chain dependencies.
2486 for (User *U : BundleMember->Inst->users()) {
2487 if (isa<Instruction>(U)) {
2488 ScheduleData *UseSD = getScheduleData(U);
2489 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2490 BundleMember->Dependencies++;
2491 ScheduleData *DestBundle = UseSD->FirstInBundle;
2492 if (!DestBundle->IsScheduled) {
2493 BundleMember->incrementUnscheduledDeps(1);
2495 if (!DestBundle->hasValidDependencies()) {
2496 WorkList.push_back(DestBundle);
2500 // I'm not sure if this can ever happen. But we need to be safe.
2501 // This lets the instruction/bundle never be scheduled and eventally
2502 // disable vectorization.
2503 BundleMember->Dependencies++;
2504 BundleMember->incrementUnscheduledDeps(1);
2508 // Handle the memory dependencies.
2509 ScheduleData *DepDest = BundleMember->NextLoadStore;
2511 AliasAnalysis::Location SrcLoc = getLocation(BundleMember->Inst, AA);
2512 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2515 assert(isInSchedulingRegion(DepDest));
2516 if (SrcMayWrite || DepDest->Inst->mayWriteToMemory()) {
2517 AliasAnalysis::Location DstLoc = getLocation(DepDest->Inst, AA);
2518 if (!SrcLoc.Ptr || !DstLoc.Ptr || AA->alias(SrcLoc, DstLoc)) {
2519 DepDest->MemoryDependencies.push_back(BundleMember);
2520 BundleMember->Dependencies++;
2521 ScheduleData *DestBundle = DepDest->FirstInBundle;
2522 if (!DestBundle->IsScheduled) {
2523 BundleMember->incrementUnscheduledDeps(1);
2525 if (!DestBundle->hasValidDependencies()) {
2526 WorkList.push_back(DestBundle);
2530 DepDest = DepDest->NextLoadStore;
2534 BundleMember = BundleMember->NextInBundle;
2536 if (InsertInReadyList && SD->isReady()) {
2537 ReadyInsts.push_back(SD);
2538 DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
2543 void BoUpSLP::BlockScheduling::resetSchedule() {
2544 assert(ScheduleStart &&
2545 "tried to reset schedule on block which has not been scheduled");
2546 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2547 ScheduleData *SD = getScheduleData(I);
2548 assert(isInSchedulingRegion(SD));
2549 SD->IsScheduled = false;
2550 SD->resetUnscheduledDeps();
2555 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2557 if (!BS->ScheduleStart)
2560 DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2562 BS->resetSchedule();
2564 // For the real scheduling we use a more sophisticated ready-list: it is
2565 // sorted by the original instruction location. This lets the final schedule
2566 // be as close as possible to the original instruction order.
2567 struct ScheduleDataCompare {
2568 bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2569 return SD2->SchedulingPriority < SD1->SchedulingPriority;
2572 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2574 // Ensure that all depencency data is updated and fill the ready-list with
2575 // initial instructions.
2577 int NumToSchedule = 0;
2578 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2579 I = I->getNextNode()) {
2580 ScheduleData *SD = BS->getScheduleData(I);
2582 SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2583 "scheduler and vectorizer have different opinion on what is a bundle");
2584 SD->FirstInBundle->SchedulingPriority = Idx++;
2585 if (SD->isSchedulingEntity()) {
2586 BS->calculateDependencies(SD, false, AA);
2590 BS->initialFillReadyList(ReadyInsts);
2592 Instruction *LastScheduledInst = BS->ScheduleEnd;
2594 // Do the "real" scheduling.
2595 while (!ReadyInsts.empty()) {
2596 ScheduleData *picked = *ReadyInsts.begin();
2597 ReadyInsts.erase(ReadyInsts.begin());
2599 // Move the scheduled instruction(s) to their dedicated places, if not
2601 ScheduleData *BundleMember = picked;
2602 while (BundleMember) {
2603 Instruction *pickedInst = BundleMember->Inst;
2604 if (LastScheduledInst->getNextNode() != pickedInst) {
2605 BS->BB->getInstList().remove(pickedInst);
2606 BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
2608 LastScheduledInst = pickedInst;
2609 BundleMember = BundleMember->NextInBundle;
2612 BS->schedule(picked, ReadyInsts);
2615 assert(NumToSchedule == 0 && "could not schedule all instructions");
2617 // Avoid duplicate scheduling of the block.
2618 BS->ScheduleStart = nullptr;
2621 /// The SLPVectorizer Pass.
2622 struct SLPVectorizer : public FunctionPass {
2623 typedef SmallVector<StoreInst *, 8> StoreList;
2624 typedef MapVector<Value *, StoreList> StoreListMap;
2626 /// Pass identification, replacement for typeid
2629 explicit SLPVectorizer() : FunctionPass(ID) {
2630 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2633 ScalarEvolution *SE;
2634 const DataLayout *DL;
2635 TargetTransformInfo *TTI;
2636 TargetLibraryInfo *TLI;
2641 bool runOnFunction(Function &F) override {
2642 if (skipOptnoneFunction(F))
2645 SE = &getAnalysis<ScalarEvolution>();
2646 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2647 DL = DLP ? &DLP->getDataLayout() : nullptr;
2648 TTI = &getAnalysis<TargetTransformInfo>();
2649 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2650 AA = &getAnalysis<AliasAnalysis>();
2651 LI = &getAnalysis<LoopInfo>();
2652 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2655 bool Changed = false;
2657 // If the target claims to have no vector registers don't attempt
2659 if (!TTI->getNumberOfRegisters(true))
2662 // Must have DataLayout. We can't require it because some tests run w/o
2667 // Don't vectorize when the attribute NoImplicitFloat is used.
2668 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2671 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2673 // Use the bottom up slp vectorizer to construct chains that start with
2674 // store instructions.
2675 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2677 // Scan the blocks in the function in post order.
2678 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2679 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2680 BasicBlock *BB = *it;
2681 // Vectorize trees that end at stores.
2682 if (unsigned count = collectStores(BB, R)) {
2684 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2685 Changed |= vectorizeStoreChains(R);
2688 // Vectorize trees that end at reductions.
2689 Changed |= vectorizeChainsInBlock(BB, R);
2693 R.optimizeGatherSequence();
2694 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2695 DEBUG(verifyFunction(F));
2700 void getAnalysisUsage(AnalysisUsage &AU) const override {
2701 FunctionPass::getAnalysisUsage(AU);
2702 AU.addRequired<ScalarEvolution>();
2703 AU.addRequired<AliasAnalysis>();
2704 AU.addRequired<TargetTransformInfo>();
2705 AU.addRequired<LoopInfo>();
2706 AU.addRequired<DominatorTreeWrapperPass>();
2707 AU.addPreserved<LoopInfo>();
2708 AU.addPreserved<DominatorTreeWrapperPass>();
2709 AU.setPreservesCFG();
2714 /// \brief Collect memory references and sort them according to their base
2715 /// object. We sort the stores to their base objects to reduce the cost of the
2716 /// quadratic search on the stores. TODO: We can further reduce this cost
2717 /// if we flush the chain creation every time we run into a memory barrier.
2718 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2720 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2721 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2723 /// \brief Try to vectorize a list of operands.
2724 /// \@param BuildVector A list of users to ignore for the purpose of
2725 /// scheduling and that don't need extracting.
2726 /// \returns true if a value was vectorized.
2727 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2728 ArrayRef<Value *> BuildVector = None,
2729 bool allowReorder = false);
2731 /// \brief Try to vectorize a chain that may start at the operands of \V;
2732 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2734 /// \brief Vectorize the stores that were collected in StoreRefs.
2735 bool vectorizeStoreChains(BoUpSLP &R);
2737 /// \brief Scan the basic block and look for patterns that are likely to start
2738 /// a vectorization chain.
2739 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2741 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2744 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2747 StoreListMap StoreRefs;
2750 /// \brief Check that the Values in the slice in VL array are still existent in
2751 /// the WeakVH array.
2752 /// Vectorization of part of the VL array may cause later values in the VL array
2753 /// to become invalid. We track when this has happened in the WeakVH array.
2754 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2755 SmallVectorImpl<WeakVH> &VH,
2756 unsigned SliceBegin,
2757 unsigned SliceSize) {
2758 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2765 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2766 int CostThreshold, BoUpSLP &R) {
2767 unsigned ChainLen = Chain.size();
2768 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2770 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2771 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2772 unsigned VF = MinVecRegSize / Sz;
2774 if (!isPowerOf2_32(Sz) || VF < 2)
2777 // Keep track of values that were deleted by vectorizing in the loop below.
2778 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2780 bool Changed = false;
2781 // Look for profitable vectorizable trees at all offsets, starting at zero.
2782 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2786 // Check that a previous iteration of this loop did not delete the Value.
2787 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2790 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2792 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2794 R.buildTree(Operands);
2796 int Cost = R.getTreeCost();
2798 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2799 if (Cost < CostThreshold) {
2800 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2803 // Move to the next bundle.
2812 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2813 int costThreshold, BoUpSLP &R) {
2814 SetVector<Value *> Heads, Tails;
2815 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2817 // We may run into multiple chains that merge into a single chain. We mark the
2818 // stores that we vectorized so that we don't visit the same store twice.
2819 BoUpSLP::ValueSet VectorizedStores;
2820 bool Changed = false;
2822 // Do a quadratic search on all of the given stores and find
2823 // all of the pairs of stores that follow each other.
2824 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2825 for (unsigned j = 0; j < e; ++j) {
2829 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2830 Tails.insert(Stores[j]);
2831 Heads.insert(Stores[i]);
2832 ConsecutiveChain[Stores[i]] = Stores[j];
2837 // For stores that start but don't end a link in the chain:
2838 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2840 if (Tails.count(*it))
2843 // We found a store instr that starts a chain. Now follow the chain and try
2845 BoUpSLP::ValueList Operands;
2847 // Collect the chain into a list.
2848 while (Tails.count(I) || Heads.count(I)) {
2849 if (VectorizedStores.count(I))
2851 Operands.push_back(I);
2852 // Move to the next value in the chain.
2853 I = ConsecutiveChain[I];
2856 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2858 // Mark the vectorized stores so that we don't vectorize them again.
2860 VectorizedStores.insert(Operands.begin(), Operands.end());
2861 Changed |= Vectorized;
2868 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2871 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2872 StoreInst *SI = dyn_cast<StoreInst>(it);
2876 // Don't touch volatile stores.
2877 if (!SI->isSimple())
2880 // Check that the pointer points to scalars.
2881 Type *Ty = SI->getValueOperand()->getType();
2882 if (Ty->isAggregateType() || Ty->isVectorTy())
2885 // Find the base pointer.
2886 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2888 // Save the store locations.
2889 StoreRefs[Ptr].push_back(SI);
2895 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2898 Value *VL[] = { A, B };
2899 return tryToVectorizeList(VL, R, None, true);
2902 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2903 ArrayRef<Value *> BuildVector,
2904 bool allowReorder) {
2908 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2910 // Check that all of the parts are scalar instructions of the same type.
2911 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2915 unsigned Opcode0 = I0->getOpcode();
2917 Type *Ty0 = I0->getType();
2918 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2919 unsigned VF = MinVecRegSize / Sz;
2921 for (int i = 0, e = VL.size(); i < e; ++i) {
2922 Type *Ty = VL[i]->getType();
2923 if (Ty->isAggregateType() || Ty->isVectorTy())
2925 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2926 if (!Inst || Inst->getOpcode() != Opcode0)
2930 bool Changed = false;
2932 // Keep track of values that were deleted by vectorizing in the loop below.
2933 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2935 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2936 unsigned OpsWidth = 0;
2943 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2946 // Check that a previous iteration of this loop did not delete the Value.
2947 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2950 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2952 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2954 ArrayRef<Value *> BuildVectorSlice;
2955 if (!BuildVector.empty())
2956 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2958 R.buildTree(Ops, BuildVectorSlice);
2959 // TODO: check if we can allow reordering also for other cases than
2960 // tryToVectorizePair()
2961 if (allowReorder && R.shouldReorder()) {
2962 assert(Ops.size() == 2);
2963 assert(BuildVectorSlice.empty());
2964 Value *ReorderedOps[] = { Ops[1], Ops[0] };
2965 R.buildTree(ReorderedOps, None);
2967 int Cost = R.getTreeCost();
2969 if (Cost < -SLPCostThreshold) {
2970 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2971 Value *VectorizedRoot = R.vectorizeTree();
2973 // Reconstruct the build vector by extracting the vectorized root. This
2974 // way we handle the case where some elements of the vector are undefined.
2975 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2976 if (!BuildVectorSlice.empty()) {
2977 // The insert point is the last build vector instruction. The vectorized
2978 // root will precede it. This guarantees that we get an instruction. The
2979 // vectorized tree could have been constant folded.
2980 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2981 unsigned VecIdx = 0;
2982 for (auto &V : BuildVectorSlice) {
2983 IRBuilder<true, NoFolder> Builder(
2984 ++BasicBlock::iterator(InsertAfter));
2985 InsertElementInst *IE = cast<InsertElementInst>(V);
2986 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2987 VectorizedRoot, Builder.getInt32(VecIdx++)));
2988 IE->setOperand(1, Extract);
2989 IE->removeFromParent();
2990 IE->insertAfter(Extract);
2994 // Move to the next bundle.
3003 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3007 // Try to vectorize V.
3008 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3011 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3012 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3014 if (B && B->hasOneUse()) {
3015 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3016 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3017 if (tryToVectorizePair(A, B0, R)) {
3021 if (tryToVectorizePair(A, B1, R)) {
3028 if (A && A->hasOneUse()) {
3029 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3030 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3031 if (tryToVectorizePair(A0, B, R)) {
3035 if (tryToVectorizePair(A1, B, R)) {
3043 /// \brief Generate a shuffle mask to be used in a reduction tree.
3045 /// \param VecLen The length of the vector to be reduced.
3046 /// \param NumEltsToRdx The number of elements that should be reduced in the
3048 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3049 /// reduction. A pairwise reduction will generate a mask of
3050 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
3051 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3052 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3053 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3054 bool IsPairwise, bool IsLeft,
3055 IRBuilder<> &Builder) {
3056 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3058 SmallVector<Constant *, 32> ShuffleMask(
3059 VecLen, UndefValue::get(Builder.getInt32Ty()));
3062 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3063 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3064 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3066 // Move the upper half of the vector to the lower half.
3067 for (unsigned i = 0; i != NumEltsToRdx; ++i)
3068 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3070 return ConstantVector::get(ShuffleMask);
3074 /// Model horizontal reductions.
3076 /// A horizontal reduction is a tree of reduction operations (currently add and
3077 /// fadd) that has operations that can be put into a vector as its leaf.
3078 /// For example, this tree:
3085 /// This tree has "mul" as its reduced values and "+" as its reduction
3086 /// operations. A reduction might be feeding into a store or a binary operation
3101 class HorizontalReduction {
3102 SmallVector<Value *, 16> ReductionOps;
3103 SmallVector<Value *, 32> ReducedVals;
3105 BinaryOperator *ReductionRoot;
3106 PHINode *ReductionPHI;
3108 /// The opcode of the reduction.
3109 unsigned ReductionOpcode;
3110 /// The opcode of the values we perform a reduction on.
3111 unsigned ReducedValueOpcode;
3112 /// The width of one full horizontal reduction operation.
3113 unsigned ReduxWidth;
3114 /// Should we model this reduction as a pairwise reduction tree or a tree that
3115 /// splits the vector in halves and adds those halves.
3116 bool IsPairwiseReduction;
3119 HorizontalReduction()
3120 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3121 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3123 /// \brief Try to find a reduction tree.
3124 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3125 const DataLayout *DL) {
3127 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3128 "Thi phi needs to use the binary operator");
3130 // We could have a initial reductions that is not an add.
3131 // r *= v1 + v2 + v3 + v4
3132 // In such a case start looking for a tree rooted in the first '+'.
3134 if (B->getOperand(0) == Phi) {
3136 B = dyn_cast<BinaryOperator>(B->getOperand(1));
3137 } else if (B->getOperand(1) == Phi) {
3139 B = dyn_cast<BinaryOperator>(B->getOperand(0));
3146 Type *Ty = B->getType();
3147 if (Ty->isVectorTy())
3150 ReductionOpcode = B->getOpcode();
3151 ReducedValueOpcode = 0;
3152 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3159 // We currently only support adds.
3160 if (ReductionOpcode != Instruction::Add &&
3161 ReductionOpcode != Instruction::FAdd)
3164 // Post order traverse the reduction tree starting at B. We only handle true
3165 // trees containing only binary operators.
3166 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3167 Stack.push_back(std::make_pair(B, 0));
3168 while (!Stack.empty()) {
3169 BinaryOperator *TreeN = Stack.back().first;
3170 unsigned EdgeToVist = Stack.back().second++;
3171 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3173 // Only handle trees in the current basic block.
3174 if (TreeN->getParent() != B->getParent())
3177 // Each tree node needs to have one user except for the ultimate
3179 if (!TreeN->hasOneUse() && TreeN != B)
3183 if (EdgeToVist == 2 || IsReducedValue) {
3184 if (IsReducedValue) {
3185 // Make sure that the opcodes of the operations that we are going to
3187 if (!ReducedValueOpcode)
3188 ReducedValueOpcode = TreeN->getOpcode();
3189 else if (ReducedValueOpcode != TreeN->getOpcode())
3191 ReducedVals.push_back(TreeN);
3193 // We need to be able to reassociate the adds.
3194 if (!TreeN->isAssociative())
3196 ReductionOps.push_back(TreeN);
3203 // Visit left or right.
3204 Value *NextV = TreeN->getOperand(EdgeToVist);
3205 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3207 Stack.push_back(std::make_pair(Next, 0));
3208 else if (NextV != Phi)
3214 /// \brief Attempt to vectorize the tree found by
3215 /// matchAssociativeReduction.
3216 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3217 if (ReducedVals.empty())
3220 unsigned NumReducedVals = ReducedVals.size();
3221 if (NumReducedVals < ReduxWidth)
3224 Value *VectorizedTree = nullptr;
3225 IRBuilder<> Builder(ReductionRoot);
3226 FastMathFlags Unsafe;
3227 Unsafe.setUnsafeAlgebra();
3228 Builder.SetFastMathFlags(Unsafe);
3231 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3232 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
3233 V.buildTree(ValsToReduce, ReductionOps);
3236 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3237 if (Cost >= -SLPCostThreshold)
3240 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3243 // Vectorize a tree.
3244 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3245 Value *VectorizedRoot = V.vectorizeTree();
3247 // Emit a reduction.
3248 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3249 if (VectorizedTree) {
3250 Builder.SetCurrentDebugLocation(Loc);
3251 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3252 ReducedSubTree, "bin.rdx");
3254 VectorizedTree = ReducedSubTree;
3257 if (VectorizedTree) {
3258 // Finish the reduction.
3259 for (; i < NumReducedVals; ++i) {
3260 Builder.SetCurrentDebugLocation(
3261 cast<Instruction>(ReducedVals[i])->getDebugLoc());
3262 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3267 assert(ReductionRoot && "Need a reduction operation");
3268 ReductionRoot->setOperand(0, VectorizedTree);
3269 ReductionRoot->setOperand(1, ReductionPHI);
3271 ReductionRoot->replaceAllUsesWith(VectorizedTree);
3273 return VectorizedTree != nullptr;
3278 /// \brief Calcuate the cost of a reduction.
3279 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3280 Type *ScalarTy = FirstReducedVal->getType();
3281 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3283 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3284 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3286 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3287 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3289 int ScalarReduxCost =
3290 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3292 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3293 << " for reduction that starts with " << *FirstReducedVal
3295 << (IsPairwiseReduction ? "pairwise" : "splitting")
3296 << " reduction)\n");
3298 return VecReduxCost - ScalarReduxCost;
3301 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3302 Value *R, const Twine &Name = "") {
3303 if (Opcode == Instruction::FAdd)
3304 return Builder.CreateFAdd(L, R, Name);
3305 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3308 /// \brief Emit a horizontal reduction of the vectorized value.
3309 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3310 assert(VectorizedValue && "Need to have a vectorized tree node");
3311 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
3312 assert(isPowerOf2_32(ReduxWidth) &&
3313 "We only handle power-of-two reductions for now");
3315 Value *TmpVec = ValToReduce;
3316 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3317 if (IsPairwiseReduction) {
3319 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3321 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3323 Value *LeftShuf = Builder.CreateShuffleVector(
3324 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3325 Value *RightShuf = Builder.CreateShuffleVector(
3326 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3328 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3332 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3333 Value *Shuf = Builder.CreateShuffleVector(
3334 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3335 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3339 // The result is in the first element of the vector.
3340 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3344 /// \brief Recognize construction of vectors like
3345 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
3346 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
3347 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
3348 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
3350 /// Returns true if it matches
3352 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3353 SmallVectorImpl<Value *> &BuildVector,
3354 SmallVectorImpl<Value *> &BuildVectorOpds) {
3355 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3358 InsertElementInst *IE = FirstInsertElem;
3360 BuildVector.push_back(IE);
3361 BuildVectorOpds.push_back(IE->getOperand(1));
3363 if (IE->use_empty())
3366 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3370 // If this isn't the final use, make sure the next insertelement is the only
3371 // use. It's OK if the final constructed vector is used multiple times
3372 if (!IE->hasOneUse())
3381 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3382 return V->getType() < V2->getType();
3385 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3386 bool Changed = false;
3387 SmallVector<Value *, 4> Incoming;
3388 SmallSet<Value *, 16> VisitedInstrs;
3390 bool HaveVectorizedPhiNodes = true;
3391 while (HaveVectorizedPhiNodes) {
3392 HaveVectorizedPhiNodes = false;
3394 // Collect the incoming values from the PHIs.
3396 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3398 PHINode *P = dyn_cast<PHINode>(instr);
3402 if (!VisitedInstrs.count(P))
3403 Incoming.push_back(P);
3407 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3409 // Try to vectorize elements base on their type.
3410 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3414 // Look for the next elements with the same type.
3415 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3416 while (SameTypeIt != E &&
3417 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3418 VisitedInstrs.insert(*SameTypeIt);
3422 // Try to vectorize them.
3423 unsigned NumElts = (SameTypeIt - IncIt);
3424 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3426 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
3427 // Success start over because instructions might have been changed.
3428 HaveVectorizedPhiNodes = true;
3433 // Start over at the next instruction of a different type (or the end).
3438 VisitedInstrs.clear();
3440 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3441 // We may go through BB multiple times so skip the one we have checked.
3442 if (!VisitedInstrs.insert(it))
3445 if (isa<DbgInfoIntrinsic>(it))
3448 // Try to vectorize reductions that use PHINodes.
3449 if (PHINode *P = dyn_cast<PHINode>(it)) {
3450 // Check that the PHI is a reduction PHI.
3451 if (P->getNumIncomingValues() != 2)
3454 (P->getIncomingBlock(0) == BB
3455 ? (P->getIncomingValue(0))
3456 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3458 // Check if this is a Binary Operator.
3459 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3463 // Try to match and vectorize a horizontal reduction.
3464 HorizontalReduction HorRdx;
3465 if (ShouldVectorizeHor &&
3466 HorRdx.matchAssociativeReduction(P, BI, DL) &&
3467 HorRdx.tryToReduce(R, TTI)) {
3474 Value *Inst = BI->getOperand(0);
3476 Inst = BI->getOperand(1);
3478 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3479 // We would like to start over since some instructions are deleted
3480 // and the iterator may become invalid value.
3490 // Try to vectorize horizontal reductions feeding into a store.
3491 if (ShouldStartVectorizeHorAtStore)
3492 if (StoreInst *SI = dyn_cast<StoreInst>(it))
3493 if (BinaryOperator *BinOp =
3494 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3495 HorizontalReduction HorRdx;
3496 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3497 HorRdx.tryToReduce(R, TTI)) ||
3498 tryToVectorize(BinOp, R))) {
3506 // Try to vectorize trees that start at compare instructions.
3507 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3508 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3510 // We would like to start over since some instructions are deleted
3511 // and the iterator may become invalid value.
3517 for (int i = 0; i < 2; ++i) {
3518 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3519 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3521 // We would like to start over since some instructions are deleted
3522 // and the iterator may become invalid value.
3531 // Try to vectorize trees that start at insertelement instructions.
3532 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3533 SmallVector<Value *, 16> BuildVector;
3534 SmallVector<Value *, 16> BuildVectorOpds;
3535 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3538 // Vectorize starting with the build vector operands ignoring the
3539 // BuildVector instructions for the purpose of scheduling and user
3541 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3554 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3555 bool Changed = false;
3556 // Attempt to sort and vectorize each of the store-groups.
3557 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3559 if (it->second.size() < 2)
3562 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3563 << it->second.size() << ".\n");
3565 // Process the stores in chunks of 16.
3566 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3567 unsigned Len = std::min<unsigned>(CE - CI, 16);
3568 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
3569 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
3575 } // end anonymous namespace
3577 char SLPVectorizer::ID = 0;
3578 static const char lv_name[] = "SLP Vectorizer";
3579 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3580 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3581 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3582 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3583 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3584 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3587 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }