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/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/NoFolder.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/VectorUtils.h"
48 #define SV_NAME "slp-vectorizer"
49 #define DEBUG_TYPE "SLP"
52 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
53 cl::desc("Only vectorize if you gain more than this "
57 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
58 cl::desc("Attempt to vectorize horizontal reductions"));
60 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
61 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
63 "Attempt to vectorize horizontal reductions feeding into a store"));
67 static const unsigned MinVecRegSize = 128;
69 static const unsigned RecursionMaxDepth = 12;
71 /// A helper class for numbering instructions in multiple blocks.
72 /// Numbers start at zero for each basic block.
73 struct BlockNumbering {
75 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
77 void numberInstructions() {
81 // Number the instructions in the block.
82 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
84 InstrVec.push_back(it);
85 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
90 int getIndex(Instruction *I) {
91 assert(I->getParent() == BB && "Invalid instruction");
94 assert(InstrIdx.count(I) && "Unknown instruction");
98 Instruction *getInstruction(unsigned loc) {
100 numberInstructions();
101 assert(InstrVec.size() > loc && "Invalid Index");
102 return InstrVec[loc];
105 void forget() { Valid = false; }
108 /// The block we are numbering.
110 /// Is the block numbered.
112 /// Maps instructions to numbers and back.
113 SmallDenseMap<Instruction *, int> InstrIdx;
114 /// Maps integers to Instructions.
115 SmallVector<Instruction *, 32> InstrVec;
118 /// \returns the parent basic block if all of the instructions in \p VL
119 /// are in the same block or null otherwise.
120 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
121 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
124 BasicBlock *BB = I0->getParent();
125 for (int i = 1, e = VL.size(); i < e; i++) {
126 Instruction *I = dyn_cast<Instruction>(VL[i]);
130 if (BB != I->getParent())
136 /// \returns True if all of the values in \p VL are constants.
137 static bool allConstant(ArrayRef<Value *> VL) {
138 for (unsigned i = 0, e = VL.size(); i < e; ++i)
139 if (!isa<Constant>(VL[i]))
144 /// \returns True if all of the values in \p VL are identical.
145 static bool isSplat(ArrayRef<Value *> VL) {
146 for (unsigned i = 1, e = VL.size(); i < e; ++i)
152 ///\returns Opcode that can be clubbed with \p Op to create an alternate
153 /// sequence which can later be merged as a ShuffleVector instruction.
154 static unsigned getAltOpcode(unsigned Op) {
156 case Instruction::FAdd:
157 return Instruction::FSub;
158 case Instruction::FSub:
159 return Instruction::FAdd;
160 case Instruction::Add:
161 return Instruction::Sub;
162 case Instruction::Sub:
163 return Instruction::Add;
169 ///\returns bool representing if Opcode \p Op can be part
170 /// of an alternate sequence which can later be merged as
171 /// a ShuffleVector instruction.
172 static bool canCombineAsAltInst(unsigned Op) {
173 if (Op == Instruction::FAdd || Op == Instruction::FSub ||
174 Op == Instruction::Sub || Op == Instruction::Add)
179 /// \returns ShuffleVector instruction if intructions in \p VL have
180 /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
181 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
182 static unsigned isAltInst(ArrayRef<Value *> VL) {
183 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
184 unsigned Opcode = I0->getOpcode();
185 unsigned AltOpcode = getAltOpcode(Opcode);
186 for (int i = 1, e = VL.size(); i < e; i++) {
187 Instruction *I = dyn_cast<Instruction>(VL[i]);
188 if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
191 return Instruction::ShuffleVector;
194 /// \returns The opcode if all of the Instructions in \p VL have the same
196 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
197 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
200 unsigned Opcode = I0->getOpcode();
201 for (int i = 1, e = VL.size(); i < e; i++) {
202 Instruction *I = dyn_cast<Instruction>(VL[i]);
203 if (!I || Opcode != I->getOpcode()) {
204 if (canCombineAsAltInst(Opcode) && i == 1)
205 return isAltInst(VL);
212 /// \returns \p I after propagating metadata from \p VL.
213 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
214 Instruction *I0 = cast<Instruction>(VL[0]);
215 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
216 I0->getAllMetadataOtherThanDebugLoc(Metadata);
218 for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
219 unsigned Kind = Metadata[i].first;
220 MDNode *MD = Metadata[i].second;
222 for (int i = 1, e = VL.size(); MD && i != e; i++) {
223 Instruction *I = cast<Instruction>(VL[i]);
224 MDNode *IMD = I->getMetadata(Kind);
228 MD = nullptr; // Remove unknown metadata
230 case LLVMContext::MD_tbaa:
231 MD = MDNode::getMostGenericTBAA(MD, IMD);
233 case LLVMContext::MD_alias_scope:
234 case LLVMContext::MD_noalias:
235 MD = MDNode::intersect(MD, IMD);
237 case LLVMContext::MD_fpmath:
238 MD = MDNode::getMostGenericFPMath(MD, IMD);
242 I->setMetadata(Kind, MD);
247 /// \returns The type that all of the values in \p VL have or null if there
248 /// are different types.
249 static Type* getSameType(ArrayRef<Value *> VL) {
250 Type *Ty = VL[0]->getType();
251 for (int i = 1, e = VL.size(); i < e; i++)
252 if (VL[i]->getType() != Ty)
258 /// \returns True if the ExtractElement instructions in VL can be vectorized
259 /// to use the original vector.
260 static bool CanReuseExtract(ArrayRef<Value *> VL) {
261 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
262 // Check if all of the extracts come from the same vector and from the
265 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
266 Value *Vec = E0->getOperand(0);
268 // We have to extract from the same vector type.
269 unsigned NElts = Vec->getType()->getVectorNumElements();
271 if (NElts != VL.size())
274 // Check that all of the indices extract from the correct offset.
275 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
276 if (!CI || CI->getZExtValue())
279 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
280 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
281 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
283 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
290 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
291 SmallVectorImpl<Value *> &Left,
292 SmallVectorImpl<Value *> &Right) {
294 SmallVector<Value *, 16> OrigLeft, OrigRight;
296 bool AllSameOpcodeLeft = true;
297 bool AllSameOpcodeRight = true;
298 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
299 Instruction *I = cast<Instruction>(VL[i]);
300 Value *V0 = I->getOperand(0);
301 Value *V1 = I->getOperand(1);
303 OrigLeft.push_back(V0);
304 OrigRight.push_back(V1);
306 Instruction *I0 = dyn_cast<Instruction>(V0);
307 Instruction *I1 = dyn_cast<Instruction>(V1);
309 // Check whether all operands on one side have the same opcode. In this case
310 // we want to preserve the original order and not make things worse by
312 AllSameOpcodeLeft = I0;
313 AllSameOpcodeRight = I1;
315 if (i && AllSameOpcodeLeft) {
316 if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
317 if(P0->getOpcode() != I0->getOpcode())
318 AllSameOpcodeLeft = false;
320 AllSameOpcodeLeft = false;
322 if (i && AllSameOpcodeRight) {
323 if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
324 if(P1->getOpcode() != I1->getOpcode())
325 AllSameOpcodeRight = false;
327 AllSameOpcodeRight = false;
330 // Sort two opcodes. In the code below we try to preserve the ability to use
331 // broadcast of values instead of individual inserts.
338 // If we just sorted according to opcode we would leave the first line in
339 // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
342 // Because vr2 and vr1 are from the same load we loose the opportunity of a
343 // broadcast for the packed right side in the backend: we have [vr1, vl2]
344 // instead of [vr1, vr2=vr1].
346 if(!i && I0->getOpcode() > I1->getOpcode()) {
349 } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
350 // Try not to destroy a broad cast for no apparent benefit.
353 } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] == I0) {
354 // Try preserve broadcasts.
357 } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
358 // Try preserve broadcasts.
367 // One opcode, put the instruction on the right.
377 bool LeftBroadcast = isSplat(Left);
378 bool RightBroadcast = isSplat(Right);
380 // Don't reorder if the operands where good to begin with.
381 if (!(LeftBroadcast || RightBroadcast) &&
382 (AllSameOpcodeRight || AllSameOpcodeLeft)) {
388 /// Bottom Up SLP Vectorizer.
391 typedef SmallVector<Value *, 8> ValueList;
392 typedef SmallVector<Instruction *, 16> InstrList;
393 typedef SmallPtrSet<Value *, 16> ValueSet;
394 typedef SmallVector<StoreInst *, 8> StoreList;
396 BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
397 TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
398 LoopInfo *Li, DominatorTree *Dt)
399 : F(Func), SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
400 Builder(Se->getContext()) {}
402 /// \brief Vectorize the tree that starts with the elements in \p VL.
403 /// Returns the vectorized root.
404 Value *vectorizeTree();
406 /// \returns the vectorization cost of the subtree that starts at \p VL.
407 /// A negative number means that this is profitable.
410 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
411 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
412 void buildTree(ArrayRef<Value *> Roots,
413 ArrayRef<Value *> UserIgnoreLst = None);
415 /// Clear the internal data structures that are created by 'buildTree'.
417 VectorizableTree.clear();
418 ScalarToTreeEntry.clear();
420 ExternalUses.clear();
421 MemBarrierIgnoreList.clear();
424 /// \returns true if the memory operations A and B are consecutive.
425 bool isConsecutiveAccess(Value *A, Value *B);
427 /// \brief Perform LICM and CSE on the newly generated gather sequences.
428 void optimizeGatherSequence();
433 /// \returns the cost of the vectorizable entry.
434 int getEntryCost(TreeEntry *E);
436 /// This is the recursive part of buildTree.
437 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
439 /// Vectorize a single entry in the tree.
440 Value *vectorizeTree(TreeEntry *E);
442 /// Vectorize a single entry in the tree, starting in \p VL.
443 Value *vectorizeTree(ArrayRef<Value *> VL);
445 /// \returns the pointer to the vectorized value if \p VL is already
446 /// vectorized, or NULL. They may happen in cycles.
447 Value *alreadyVectorized(ArrayRef<Value *> VL) const;
449 /// \brief Take the pointer operand from the Load/Store instruction.
450 /// \returns NULL if this is not a valid Load/Store instruction.
451 static Value *getPointerOperand(Value *I);
453 /// \brief Take the address space operand from the Load/Store instruction.
454 /// \returns -1 if this is not a valid Load/Store instruction.
455 static unsigned getAddressSpaceOperand(Value *I);
457 /// \returns the scalarization cost for this type. Scalarization in this
458 /// context means the creation of vectors from a group of scalars.
459 int getGatherCost(Type *Ty);
461 /// \returns the scalarization cost for this list of values. Assuming that
462 /// this subtree gets vectorized, we may need to extract the values from the
463 /// roots. This method calculates the cost of extracting the values.
464 int getGatherCost(ArrayRef<Value *> VL);
466 /// \returns the AA location that is being access by the instruction.
467 AliasAnalysis::Location getLocation(Instruction *I);
469 /// \brief Checks if it is possible to sink an instruction from
470 /// \p Src to \p Dst.
471 /// \returns the pointer to the barrier instruction if we can't sink.
472 Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
474 /// \returns the index of the last instruction in the BB from \p VL.
475 int getLastIndex(ArrayRef<Value *> VL);
477 /// \returns the Instruction in the bundle \p VL.
478 Instruction *getLastInstruction(ArrayRef<Value *> VL);
480 /// \brief Set the Builder insert point to one after the last instruction in
482 void setInsertPointAfterBundle(ArrayRef<Value *> VL);
484 /// \returns a vector from a collection of scalars in \p VL.
485 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
487 /// \returns whether the VectorizableTree is fully vectoriable and will
488 /// be beneficial even the tree height is tiny.
489 bool isFullyVectorizableTinyTree();
492 TreeEntry() : Scalars(), VectorizedValue(nullptr), LastScalarIndex(0),
495 /// \returns true if the scalars in VL are equal to this entry.
496 bool isSame(ArrayRef<Value *> VL) const {
497 assert(VL.size() == Scalars.size() && "Invalid size");
498 return std::equal(VL.begin(), VL.end(), Scalars.begin());
501 /// A vector of scalars.
504 /// The Scalars are vectorized into this value. It is initialized to Null.
505 Value *VectorizedValue;
507 /// The index in the basic block of the last scalar.
510 /// Do we need to gather this sequence ?
514 /// Create a new VectorizableTree entry.
515 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
516 VectorizableTree.push_back(TreeEntry());
517 int idx = VectorizableTree.size() - 1;
518 TreeEntry *Last = &VectorizableTree[idx];
519 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
520 Last->NeedToGather = !Vectorized;
522 Last->LastScalarIndex = getLastIndex(VL);
523 for (int i = 0, e = VL.size(); i != e; ++i) {
524 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
525 ScalarToTreeEntry[VL[i]] = idx;
528 Last->LastScalarIndex = 0;
529 MustGather.insert(VL.begin(), VL.end());
534 /// -- Vectorization State --
535 /// Holds all of the tree entries.
536 std::vector<TreeEntry> VectorizableTree;
538 /// Maps a specific scalar to its tree entry.
539 SmallDenseMap<Value*, int> ScalarToTreeEntry;
541 /// A list of scalars that we found that we need to keep as scalars.
544 /// This POD struct describes one external user in the vectorized tree.
545 struct ExternalUser {
546 ExternalUser (Value *S, llvm::User *U, int L) :
547 Scalar(S), User(U), Lane(L){};
548 // Which scalar in our function.
550 // Which user that uses the scalar.
552 // Which lane does the scalar belong to.
555 typedef SmallVector<ExternalUser, 16> UserList;
557 /// A list of values that need to extracted out of the tree.
558 /// This list holds pairs of (Internal Scalar : External User).
559 UserList ExternalUses;
561 /// A list of instructions to ignore while sinking
562 /// memory instructions. This map must be reset between runs of getCost.
563 ValueSet MemBarrierIgnoreList;
565 /// Holds all of the instructions that we gathered.
566 SetVector<Instruction *> GatherSeq;
567 /// A list of blocks that we are going to CSE.
568 SetVector<BasicBlock *> CSEBlocks;
570 /// Numbers instructions in different blocks.
571 DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
573 /// \brief Get the corresponding instruction numbering list for a given
574 /// BasicBlock. The list is allocated lazily.
575 BlockNumbering &getBlockNumbering(BasicBlock *BB) {
576 auto I = BlocksNumbers.insert(std::make_pair(BB, BlockNumbering(BB)));
577 return I.first->second;
580 /// List of users to ignore during scheduling and that don't need extracting.
581 ArrayRef<Value *> UserIgnoreList;
583 // Analysis and block reference.
586 const DataLayout *DL;
587 TargetTransformInfo *TTI;
588 TargetLibraryInfo *TLI;
592 /// Instruction builder to construct the vectorized tree.
596 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
597 ArrayRef<Value *> UserIgnoreLst) {
599 UserIgnoreList = UserIgnoreLst;
600 if (!getSameType(Roots))
602 buildTree_rec(Roots, 0);
604 // Collect the values that we need to extract from the tree.
605 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
606 TreeEntry *Entry = &VectorizableTree[EIdx];
609 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
610 Value *Scalar = Entry->Scalars[Lane];
612 // No need to handle users of gathered values.
613 if (Entry->NeedToGather)
616 for (User *U : Scalar->users()) {
617 DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
619 // Skip in-tree scalars that become vectors.
620 if (ScalarToTreeEntry.count(U)) {
621 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
623 int Idx = ScalarToTreeEntry[U]; (void) Idx;
624 assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
627 Instruction *UserInst = dyn_cast<Instruction>(U);
631 // Ignore users in the user ignore list.
632 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
633 UserIgnoreList.end())
636 DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
637 Lane << " from " << *Scalar << ".\n");
638 ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
645 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
646 bool SameTy = getSameType(VL); (void)SameTy;
647 bool isAltShuffle = false;
648 assert(SameTy && "Invalid types!");
650 if (Depth == RecursionMaxDepth) {
651 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
652 newTreeEntry(VL, false);
656 // Don't handle vectors.
657 if (VL[0]->getType()->isVectorTy()) {
658 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
659 newTreeEntry(VL, false);
663 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
664 if (SI->getValueOperand()->getType()->isVectorTy()) {
665 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
666 newTreeEntry(VL, false);
669 unsigned Opcode = getSameOpcode(VL);
671 // Check that this shuffle vector refers to the alternate
672 // sequence of opcodes.
673 if (Opcode == Instruction::ShuffleVector) {
674 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
675 unsigned Op = I0->getOpcode();
676 if (Op != Instruction::ShuffleVector)
680 // If all of the operands are identical or constant we have a simple solution.
681 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
682 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
683 newTreeEntry(VL, false);
687 // We now know that this is a vector of instructions of the same type from
690 // Check if this is a duplicate of another entry.
691 if (ScalarToTreeEntry.count(VL[0])) {
692 int Idx = ScalarToTreeEntry[VL[0]];
693 TreeEntry *E = &VectorizableTree[Idx];
694 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
695 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
696 if (E->Scalars[i] != VL[i]) {
697 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
698 newTreeEntry(VL, false);
702 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
706 // Check that none of the instructions in the bundle are already in the tree.
707 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
708 if (ScalarToTreeEntry.count(VL[i])) {
709 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
710 ") is already in tree.\n");
711 newTreeEntry(VL, false);
716 // If any of the scalars appears in the table OR it is marked as a value that
717 // needs to stat scalar then we need to gather the scalars.
718 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
719 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
720 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
721 newTreeEntry(VL, false);
726 // Check that all of the users of the scalars that we want to vectorize are
728 Instruction *VL0 = cast<Instruction>(VL[0]);
729 int MyLastIndex = getLastIndex(VL);
730 BasicBlock *BB = cast<Instruction>(VL0)->getParent();
732 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
733 Instruction *Scalar = cast<Instruction>(VL[i]);
734 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n");
735 for (User *U : Scalar->users()) {
736 DEBUG(dbgs() << "SLP: \tUser " << *U << ". \n");
737 Instruction *UI = dyn_cast<Instruction>(U);
739 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
740 newTreeEntry(VL, false);
744 // We don't care if the user is in a different basic block.
745 BasicBlock *UserBlock = UI->getParent();
746 if (UserBlock != BB) {
747 DEBUG(dbgs() << "SLP: User from a different basic block "
752 // If this is a PHINode within this basic block then we can place the
753 // extract wherever we want.
754 if (isa<PHINode>(*UI)) {
755 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *UI << ". \n");
759 // Check if this is a safe in-tree user.
760 if (ScalarToTreeEntry.count(UI)) {
761 int Idx = ScalarToTreeEntry[UI];
762 int VecLocation = VectorizableTree[Idx].LastScalarIndex;
763 if (VecLocation <= MyLastIndex) {
764 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
765 newTreeEntry(VL, false);
768 DEBUG(dbgs() << "SLP: In-tree user (" << *UI << ") at #" <<
769 VecLocation << " vector value (" << *Scalar << ") at #"
770 << MyLastIndex << ".\n");
774 // Ignore users in the user ignore list.
775 if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UI) !=
776 UserIgnoreList.end())
779 // Make sure that we can schedule this unknown user.
780 BlockNumbering &BN = getBlockNumbering(BB);
781 int UserIndex = BN.getIndex(UI);
782 if (UserIndex < MyLastIndex) {
784 DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
786 newTreeEntry(VL, false);
792 // Check that every instructions appears once in this bundle.
793 for (unsigned i = 0, e = VL.size(); i < e; ++i)
794 for (unsigned j = i+1; j < e; ++j)
795 if (VL[i] == VL[j]) {
796 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
797 newTreeEntry(VL, false);
801 // Check that instructions in this bundle don't reference other instructions.
802 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
803 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
804 for (User *U : VL[i]->users()) {
805 for (unsigned j = 0; j < e; ++j) {
806 if (i != j && U == VL[j]) {
807 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << *U << ". \n");
808 newTreeEntry(VL, false);
815 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
817 // Check if it is safe to sink the loads or the stores.
818 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
819 Instruction *Last = getLastInstruction(VL);
821 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
824 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
826 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
827 << "\n because of " << *Barrier << ". Gathering.\n");
828 newTreeEntry(VL, false);
835 case Instruction::PHI: {
836 PHINode *PH = dyn_cast<PHINode>(VL0);
838 // Check for terminator values (e.g. invoke).
839 for (unsigned j = 0; j < VL.size(); ++j)
840 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
841 TerminatorInst *Term = dyn_cast<TerminatorInst>(
842 cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
844 DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
845 newTreeEntry(VL, false);
850 newTreeEntry(VL, true);
851 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
853 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
855 // Prepare the operand vector.
856 for (unsigned j = 0; j < VL.size(); ++j)
857 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
858 PH->getIncomingBlock(i)));
860 buildTree_rec(Operands, Depth + 1);
864 case Instruction::ExtractElement: {
865 bool Reuse = CanReuseExtract(VL);
867 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
869 newTreeEntry(VL, Reuse);
872 case Instruction::Load: {
873 // Check if the loads are consecutive or of we need to swizzle them.
874 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
875 LoadInst *L = cast<LoadInst>(VL[i]);
876 if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
877 newTreeEntry(VL, false);
878 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
882 newTreeEntry(VL, true);
883 DEBUG(dbgs() << "SLP: added a vector of loads.\n");
886 case Instruction::ZExt:
887 case Instruction::SExt:
888 case Instruction::FPToUI:
889 case Instruction::FPToSI:
890 case Instruction::FPExt:
891 case Instruction::PtrToInt:
892 case Instruction::IntToPtr:
893 case Instruction::SIToFP:
894 case Instruction::UIToFP:
895 case Instruction::Trunc:
896 case Instruction::FPTrunc:
897 case Instruction::BitCast: {
898 Type *SrcTy = VL0->getOperand(0)->getType();
899 for (unsigned i = 0; i < VL.size(); ++i) {
900 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
901 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
902 newTreeEntry(VL, false);
903 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
907 newTreeEntry(VL, true);
908 DEBUG(dbgs() << "SLP: added a vector of casts.\n");
910 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
912 // Prepare the operand vector.
913 for (unsigned j = 0; j < VL.size(); ++j)
914 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
916 buildTree_rec(Operands, Depth+1);
920 case Instruction::ICmp:
921 case Instruction::FCmp: {
922 // Check that all of the compares have the same predicate.
923 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
924 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
925 for (unsigned i = 1, e = VL.size(); i < e; ++i) {
926 CmpInst *Cmp = cast<CmpInst>(VL[i]);
927 if (Cmp->getPredicate() != P0 ||
928 Cmp->getOperand(0)->getType() != ComparedTy) {
929 newTreeEntry(VL, false);
930 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
935 newTreeEntry(VL, true);
936 DEBUG(dbgs() << "SLP: added a vector of compares.\n");
938 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
940 // Prepare the operand vector.
941 for (unsigned j = 0; j < VL.size(); ++j)
942 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
944 buildTree_rec(Operands, Depth+1);
948 case Instruction::Select:
949 case Instruction::Add:
950 case Instruction::FAdd:
951 case Instruction::Sub:
952 case Instruction::FSub:
953 case Instruction::Mul:
954 case Instruction::FMul:
955 case Instruction::UDiv:
956 case Instruction::SDiv:
957 case Instruction::FDiv:
958 case Instruction::URem:
959 case Instruction::SRem:
960 case Instruction::FRem:
961 case Instruction::Shl:
962 case Instruction::LShr:
963 case Instruction::AShr:
964 case Instruction::And:
965 case Instruction::Or:
966 case Instruction::Xor: {
967 newTreeEntry(VL, true);
968 DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
970 // Sort operands of the instructions so that each side is more likely to
971 // have the same opcode.
972 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
973 ValueList Left, Right;
974 reorderInputsAccordingToOpcode(VL, Left, Right);
975 BasicBlock *LeftBB = getSameBlock(Left);
976 BasicBlock *RightBB = getSameBlock(Right);
977 // If we have common uses on separate paths in the tree make sure we
978 // process the one with greater common depth first.
979 // We can use block numbering to determine the subtree traversal as
980 // earler user has to come in between the common use and the later user.
981 if (LeftBB && RightBB && LeftBB == RightBB &&
982 getLastIndex(Right) > getLastIndex(Left)) {
983 buildTree_rec(Right, Depth + 1);
984 buildTree_rec(Left, Depth + 1);
986 buildTree_rec(Left, Depth + 1);
987 buildTree_rec(Right, Depth + 1);
992 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
994 // Prepare the operand vector.
995 for (unsigned j = 0; j < VL.size(); ++j)
996 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
998 buildTree_rec(Operands, Depth+1);
1002 case Instruction::GetElementPtr: {
1003 // We don't combine GEPs with complicated (nested) indexing.
1004 for (unsigned j = 0; j < VL.size(); ++j) {
1005 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1006 DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1007 newTreeEntry(VL, false);
1012 // We can't combine several GEPs into one vector if they operate on
1014 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1015 for (unsigned j = 0; j < VL.size(); ++j) {
1016 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1018 DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1019 newTreeEntry(VL, false);
1024 // We don't combine GEPs with non-constant indexes.
1025 for (unsigned j = 0; j < VL.size(); ++j) {
1026 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1027 if (!isa<ConstantInt>(Op)) {
1029 dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1030 newTreeEntry(VL, false);
1035 newTreeEntry(VL, true);
1036 DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1037 for (unsigned i = 0, e = 2; i < e; ++i) {
1039 // Prepare the operand vector.
1040 for (unsigned j = 0; j < VL.size(); ++j)
1041 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1043 buildTree_rec(Operands, Depth + 1);
1047 case Instruction::Store: {
1048 // Check if the stores are consecutive or of we need to swizzle them.
1049 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1050 if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1051 newTreeEntry(VL, false);
1052 DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1056 newTreeEntry(VL, true);
1057 DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1060 for (unsigned j = 0; j < VL.size(); ++j)
1061 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1063 // We can ignore these values because we are sinking them down.
1064 MemBarrierIgnoreList.insert(VL.begin(), VL.end());
1065 buildTree_rec(Operands, Depth + 1);
1068 case Instruction::Call: {
1069 // Check if the calls are all to the same vectorizable intrinsic.
1070 CallInst *CI = cast<CallInst>(VL[0]);
1071 // Check if this is an Intrinsic call or something that can be
1072 // represented by an intrinsic call
1073 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1074 if (!isTriviallyVectorizable(ID)) {
1075 newTreeEntry(VL, false);
1076 DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1079 Function *Int = CI->getCalledFunction();
1080 Value *A1I = nullptr;
1081 if (hasVectorInstrinsicScalarOpd(ID, 1))
1082 A1I = CI->getArgOperand(1);
1083 for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1084 CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1085 if (!CI2 || CI2->getCalledFunction() != Int ||
1086 getIntrinsicIDForCall(CI2, TLI) != ID) {
1087 newTreeEntry(VL, false);
1088 DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1092 // ctlz,cttz and powi are special intrinsics whose second argument
1093 // should be same in order for them to be vectorized.
1094 if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1095 Value *A1J = CI2->getArgOperand(1);
1097 newTreeEntry(VL, false);
1098 DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1099 << " argument "<< A1I<<"!=" << A1J
1106 newTreeEntry(VL, true);
1107 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1109 // Prepare the operand vector.
1110 for (unsigned j = 0; j < VL.size(); ++j) {
1111 CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1112 Operands.push_back(CI2->getArgOperand(i));
1114 buildTree_rec(Operands, Depth + 1);
1118 case Instruction::ShuffleVector: {
1119 // If this is not an alternate sequence of opcode like add-sub
1120 // then do not vectorize this instruction.
1121 if (!isAltShuffle) {
1122 newTreeEntry(VL, false);
1123 DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1126 newTreeEntry(VL, true);
1127 DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1128 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1130 // Prepare the operand vector.
1131 for (unsigned j = 0; j < VL.size(); ++j)
1132 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1134 buildTree_rec(Operands, Depth + 1);
1139 newTreeEntry(VL, false);
1140 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1145 int BoUpSLP::getEntryCost(TreeEntry *E) {
1146 ArrayRef<Value*> VL = E->Scalars;
1148 Type *ScalarTy = VL[0]->getType();
1149 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1150 ScalarTy = SI->getValueOperand()->getType();
1151 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1153 if (E->NeedToGather) {
1154 if (allConstant(VL))
1157 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1159 return getGatherCost(E->Scalars);
1161 unsigned Opcode = getSameOpcode(VL);
1162 assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1163 Instruction *VL0 = cast<Instruction>(VL[0]);
1165 case Instruction::PHI: {
1168 case Instruction::ExtractElement: {
1169 if (CanReuseExtract(VL)) {
1171 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1172 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1174 // Take credit for instruction that will become dead.
1176 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1180 return getGatherCost(VecTy);
1182 case Instruction::ZExt:
1183 case Instruction::SExt:
1184 case Instruction::FPToUI:
1185 case Instruction::FPToSI:
1186 case Instruction::FPExt:
1187 case Instruction::PtrToInt:
1188 case Instruction::IntToPtr:
1189 case Instruction::SIToFP:
1190 case Instruction::UIToFP:
1191 case Instruction::Trunc:
1192 case Instruction::FPTrunc:
1193 case Instruction::BitCast: {
1194 Type *SrcTy = VL0->getOperand(0)->getType();
1196 // Calculate the cost of this instruction.
1197 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1198 VL0->getType(), SrcTy);
1200 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1201 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1202 return VecCost - ScalarCost;
1204 case Instruction::FCmp:
1205 case Instruction::ICmp:
1206 case Instruction::Select:
1207 case Instruction::Add:
1208 case Instruction::FAdd:
1209 case Instruction::Sub:
1210 case Instruction::FSub:
1211 case Instruction::Mul:
1212 case Instruction::FMul:
1213 case Instruction::UDiv:
1214 case Instruction::SDiv:
1215 case Instruction::FDiv:
1216 case Instruction::URem:
1217 case Instruction::SRem:
1218 case Instruction::FRem:
1219 case Instruction::Shl:
1220 case Instruction::LShr:
1221 case Instruction::AShr:
1222 case Instruction::And:
1223 case Instruction::Or:
1224 case Instruction::Xor: {
1225 // Calculate the cost of this instruction.
1228 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1229 Opcode == Instruction::Select) {
1230 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1231 ScalarCost = VecTy->getNumElements() *
1232 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1233 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1235 // Certain instructions can be cheaper to vectorize if they have a
1236 // constant second vector operand.
1237 TargetTransformInfo::OperandValueKind Op1VK =
1238 TargetTransformInfo::OK_AnyValue;
1239 TargetTransformInfo::OperandValueKind Op2VK =
1240 TargetTransformInfo::OK_UniformConstantValue;
1242 // If all operands are exactly the same ConstantInt then set the
1243 // operand kind to OK_UniformConstantValue.
1244 // If instead not all operands are constants, then set the operand kind
1245 // to OK_AnyValue. If all operands are constants but not the same,
1246 // then set the operand kind to OK_NonUniformConstantValue.
1247 ConstantInt *CInt = nullptr;
1248 for (unsigned i = 0; i < VL.size(); ++i) {
1249 const Instruction *I = cast<Instruction>(VL[i]);
1250 if (!isa<ConstantInt>(I->getOperand(1))) {
1251 Op2VK = TargetTransformInfo::OK_AnyValue;
1255 CInt = cast<ConstantInt>(I->getOperand(1));
1258 if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1259 CInt != cast<ConstantInt>(I->getOperand(1)))
1260 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1264 VecTy->getNumElements() *
1265 TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1266 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1268 return VecCost - ScalarCost;
1270 case Instruction::GetElementPtr: {
1271 TargetTransformInfo::OperandValueKind Op1VK =
1272 TargetTransformInfo::OK_AnyValue;
1273 TargetTransformInfo::OperandValueKind Op2VK =
1274 TargetTransformInfo::OK_UniformConstantValue;
1277 VecTy->getNumElements() *
1278 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1280 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1282 return VecCost - ScalarCost;
1284 case Instruction::Load: {
1285 // Cost of wide load - cost of scalar loads.
1286 int ScalarLdCost = VecTy->getNumElements() *
1287 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1288 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1289 return VecLdCost - ScalarLdCost;
1291 case Instruction::Store: {
1292 // We know that we can merge the stores. Calculate the cost.
1293 int ScalarStCost = VecTy->getNumElements() *
1294 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1295 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1296 return VecStCost - ScalarStCost;
1298 case Instruction::Call: {
1299 CallInst *CI = cast<CallInst>(VL0);
1300 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1302 // Calculate the cost of the scalar and vector calls.
1303 SmallVector<Type*, 4> ScalarTys, VecTys;
1304 for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1305 ScalarTys.push_back(CI->getArgOperand(op)->getType());
1306 VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1307 VecTy->getNumElements()));
1310 int ScalarCallCost = VecTy->getNumElements() *
1311 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1313 int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1315 DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1316 << " (" << VecCallCost << "-" << ScalarCallCost << ")"
1317 << " for " << *CI << "\n");
1319 return VecCallCost - ScalarCallCost;
1321 case Instruction::ShuffleVector: {
1322 TargetTransformInfo::OperandValueKind Op1VK =
1323 TargetTransformInfo::OK_AnyValue;
1324 TargetTransformInfo::OperandValueKind Op2VK =
1325 TargetTransformInfo::OK_AnyValue;
1328 for (unsigned i = 0; i < VL.size(); ++i) {
1329 Instruction *I = cast<Instruction>(VL[i]);
1333 TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1335 // VecCost is equal to sum of the cost of creating 2 vectors
1336 // and the cost of creating shuffle.
1337 Instruction *I0 = cast<Instruction>(VL[0]);
1339 TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1340 Instruction *I1 = cast<Instruction>(VL[1]);
1342 TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1344 TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1345 return VecCost - ScalarCost;
1348 llvm_unreachable("Unknown instruction");
1352 bool BoUpSLP::isFullyVectorizableTinyTree() {
1353 DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1354 VectorizableTree.size() << " is fully vectorizable .\n");
1356 // We only handle trees of height 2.
1357 if (VectorizableTree.size() != 2)
1360 // Handle splat stores.
1361 if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1364 // Gathering cost would be too much for tiny trees.
1365 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1371 int BoUpSLP::getTreeCost() {
1373 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1374 VectorizableTree.size() << ".\n");
1376 // We only vectorize tiny trees if it is fully vectorizable.
1377 if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1378 if (!VectorizableTree.size()) {
1379 assert(!ExternalUses.size() && "We should not have any external users");
1384 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1386 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1387 int C = getEntryCost(&VectorizableTree[i]);
1388 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1389 << *VectorizableTree[i].Scalars[0] << " .\n");
1393 SmallSet<Value *, 16> ExtractCostCalculated;
1394 int ExtractCost = 0;
1395 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1397 // We only add extract cost once for the same scalar.
1398 if (!ExtractCostCalculated.insert(I->Scalar))
1401 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1402 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1406 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1407 return Cost + ExtractCost;
1410 int BoUpSLP::getGatherCost(Type *Ty) {
1412 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1413 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1417 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1418 // Find the type of the operands in VL.
1419 Type *ScalarTy = VL[0]->getType();
1420 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1421 ScalarTy = SI->getValueOperand()->getType();
1422 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1423 // Find the cost of inserting/extracting values from the vector.
1424 return getGatherCost(VecTy);
1427 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1428 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1429 return AA->getLocation(SI);
1430 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1431 return AA->getLocation(LI);
1432 return AliasAnalysis::Location();
1435 Value *BoUpSLP::getPointerOperand(Value *I) {
1436 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1437 return LI->getPointerOperand();
1438 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1439 return SI->getPointerOperand();
1443 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1444 if (LoadInst *L = dyn_cast<LoadInst>(I))
1445 return L->getPointerAddressSpace();
1446 if (StoreInst *S = dyn_cast<StoreInst>(I))
1447 return S->getPointerAddressSpace();
1451 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1452 Value *PtrA = getPointerOperand(A);
1453 Value *PtrB = getPointerOperand(B);
1454 unsigned ASA = getAddressSpaceOperand(A);
1455 unsigned ASB = getAddressSpaceOperand(B);
1457 // Check that the address spaces match and that the pointers are valid.
1458 if (!PtrA || !PtrB || (ASA != ASB))
1461 // Make sure that A and B are different pointers of the same type.
1462 if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1465 unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1466 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1467 APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1469 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1470 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1471 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1473 APInt OffsetDelta = OffsetB - OffsetA;
1475 // Check if they are based on the same pointer. That makes the offsets
1478 return OffsetDelta == Size;
1480 // Compute the necessary base pointer delta to have the necessary final delta
1481 // equal to the size.
1482 APInt BaseDelta = Size - OffsetDelta;
1484 // Otherwise compute the distance with SCEV between the base pointers.
1485 const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1486 const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1487 const SCEV *C = SE->getConstant(BaseDelta);
1488 const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1489 return X == PtrSCEVB;
1492 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1493 assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1494 BasicBlock::iterator I = Src, E = Dst;
1495 /// Scan all of the instruction from SRC to DST and check if
1496 /// the source may alias.
1497 for (++I; I != E; ++I) {
1498 // Ignore store instructions that are marked as 'ignore'.
1499 if (MemBarrierIgnoreList.count(I))
1501 if (Src->mayWriteToMemory()) /* Write */ {
1502 if (!I->mayReadOrWriteMemory())
1505 if (!I->mayWriteToMemory())
1508 AliasAnalysis::Location A = getLocation(&*I);
1509 AliasAnalysis::Location B = getLocation(Src);
1511 if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1517 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1518 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1519 assert(BB == getSameBlock(VL) && "Invalid block");
1520 BlockNumbering &BN = getBlockNumbering(BB);
1522 int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1523 for (unsigned i = 0, e = VL.size(); i < e; ++i)
1524 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1528 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1529 BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1530 assert(BB == getSameBlock(VL) && "Invalid block");
1531 BlockNumbering &BN = getBlockNumbering(BB);
1533 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1534 for (unsigned i = 1, e = VL.size(); i < e; ++i)
1535 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1536 Instruction *I = BN.getInstruction(MaxIdx);
1537 assert(I && "bad location");
1541 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1542 Instruction *VL0 = cast<Instruction>(VL[0]);
1543 Instruction *LastInst = getLastInstruction(VL);
1544 BasicBlock::iterator NextInst = LastInst;
1546 Builder.SetInsertPoint(VL0->getParent(), NextInst);
1547 Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1550 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1551 Value *Vec = UndefValue::get(Ty);
1552 // Generate the 'InsertElement' instruction.
1553 for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1554 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1555 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1556 GatherSeq.insert(Insrt);
1557 CSEBlocks.insert(Insrt->getParent());
1559 // Add to our 'need-to-extract' list.
1560 if (ScalarToTreeEntry.count(VL[i])) {
1561 int Idx = ScalarToTreeEntry[VL[i]];
1562 TreeEntry *E = &VectorizableTree[Idx];
1563 // Find which lane we need to extract.
1565 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1566 // Is this the lane of the scalar that we are looking for ?
1567 if (E->Scalars[Lane] == VL[i]) {
1572 assert(FoundLane >= 0 && "Could not find the correct lane");
1573 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1581 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1582 SmallDenseMap<Value*, int>::const_iterator Entry
1583 = ScalarToTreeEntry.find(VL[0]);
1584 if (Entry != ScalarToTreeEntry.end()) {
1585 int Idx = Entry->second;
1586 const TreeEntry *En = &VectorizableTree[Idx];
1587 if (En->isSame(VL) && En->VectorizedValue)
1588 return En->VectorizedValue;
1593 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1594 if (ScalarToTreeEntry.count(VL[0])) {
1595 int Idx = ScalarToTreeEntry[VL[0]];
1596 TreeEntry *E = &VectorizableTree[Idx];
1598 return vectorizeTree(E);
1601 Type *ScalarTy = VL[0]->getType();
1602 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1603 ScalarTy = SI->getValueOperand()->getType();
1604 VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1606 return Gather(VL, VecTy);
1609 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1610 IRBuilder<>::InsertPointGuard Guard(Builder);
1612 if (E->VectorizedValue) {
1613 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1614 return E->VectorizedValue;
1617 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1618 Type *ScalarTy = VL0->getType();
1619 if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1620 ScalarTy = SI->getValueOperand()->getType();
1621 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1623 if (E->NeedToGather) {
1624 setInsertPointAfterBundle(E->Scalars);
1625 return Gather(E->Scalars, VecTy);
1627 unsigned Opcode = getSameOpcode(E->Scalars);
1630 case Instruction::PHI: {
1631 PHINode *PH = dyn_cast<PHINode>(VL0);
1632 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1633 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1634 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1635 E->VectorizedValue = NewPhi;
1637 // PHINodes may have multiple entries from the same block. We want to
1638 // visit every block once.
1639 SmallSet<BasicBlock*, 4> VisitedBBs;
1641 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1643 BasicBlock *IBB = PH->getIncomingBlock(i);
1645 if (!VisitedBBs.insert(IBB)) {
1646 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1650 // Prepare the operand vector.
1651 for (unsigned j = 0; j < E->Scalars.size(); ++j)
1652 Operands.push_back(cast<PHINode>(E->Scalars[j])->
1653 getIncomingValueForBlock(IBB));
1655 Builder.SetInsertPoint(IBB->getTerminator());
1656 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1657 Value *Vec = vectorizeTree(Operands);
1658 NewPhi->addIncoming(Vec, IBB);
1661 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1662 "Invalid number of incoming values");
1666 case Instruction::ExtractElement: {
1667 if (CanReuseExtract(E->Scalars)) {
1668 Value *V = VL0->getOperand(0);
1669 E->VectorizedValue = V;
1672 return Gather(E->Scalars, VecTy);
1674 case Instruction::ZExt:
1675 case Instruction::SExt:
1676 case Instruction::FPToUI:
1677 case Instruction::FPToSI:
1678 case Instruction::FPExt:
1679 case Instruction::PtrToInt:
1680 case Instruction::IntToPtr:
1681 case Instruction::SIToFP:
1682 case Instruction::UIToFP:
1683 case Instruction::Trunc:
1684 case Instruction::FPTrunc:
1685 case Instruction::BitCast: {
1687 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1688 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1690 setInsertPointAfterBundle(E->Scalars);
1692 Value *InVec = vectorizeTree(INVL);
1694 if (Value *V = alreadyVectorized(E->Scalars))
1697 CastInst *CI = dyn_cast<CastInst>(VL0);
1698 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1699 E->VectorizedValue = V;
1702 case Instruction::FCmp:
1703 case Instruction::ICmp: {
1704 ValueList LHSV, RHSV;
1705 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1706 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1707 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1710 setInsertPointAfterBundle(E->Scalars);
1712 Value *L = vectorizeTree(LHSV);
1713 Value *R = vectorizeTree(RHSV);
1715 if (Value *V = alreadyVectorized(E->Scalars))
1718 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1720 if (Opcode == Instruction::FCmp)
1721 V = Builder.CreateFCmp(P0, L, R);
1723 V = Builder.CreateICmp(P0, L, R);
1725 E->VectorizedValue = V;
1728 case Instruction::Select: {
1729 ValueList TrueVec, FalseVec, CondVec;
1730 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1731 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1732 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1733 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1736 setInsertPointAfterBundle(E->Scalars);
1738 Value *Cond = vectorizeTree(CondVec);
1739 Value *True = vectorizeTree(TrueVec);
1740 Value *False = vectorizeTree(FalseVec);
1742 if (Value *V = alreadyVectorized(E->Scalars))
1745 Value *V = Builder.CreateSelect(Cond, True, False);
1746 E->VectorizedValue = V;
1749 case Instruction::Add:
1750 case Instruction::FAdd:
1751 case Instruction::Sub:
1752 case Instruction::FSub:
1753 case Instruction::Mul:
1754 case Instruction::FMul:
1755 case Instruction::UDiv:
1756 case Instruction::SDiv:
1757 case Instruction::FDiv:
1758 case Instruction::URem:
1759 case Instruction::SRem:
1760 case Instruction::FRem:
1761 case Instruction::Shl:
1762 case Instruction::LShr:
1763 case Instruction::AShr:
1764 case Instruction::And:
1765 case Instruction::Or:
1766 case Instruction::Xor: {
1767 ValueList LHSVL, RHSVL;
1768 if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1769 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1771 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1772 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1773 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1776 setInsertPointAfterBundle(E->Scalars);
1778 Value *LHS = vectorizeTree(LHSVL);
1779 Value *RHS = vectorizeTree(RHSVL);
1781 if (LHS == RHS && isa<Instruction>(LHS)) {
1782 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1785 if (Value *V = alreadyVectorized(E->Scalars))
1788 BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1789 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1790 E->VectorizedValue = V;
1792 if (Instruction *I = dyn_cast<Instruction>(V))
1793 return propagateMetadata(I, E->Scalars);
1797 case Instruction::Load: {
1798 // Loads are inserted at the head of the tree because we don't want to
1799 // sink them all the way down past store instructions.
1800 setInsertPointAfterBundle(E->Scalars);
1802 LoadInst *LI = cast<LoadInst>(VL0);
1803 unsigned AS = LI->getPointerAddressSpace();
1805 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1806 VecTy->getPointerTo(AS));
1807 unsigned Alignment = LI->getAlignment();
1808 LI = Builder.CreateLoad(VecPtr);
1810 Alignment = DL->getABITypeAlignment(LI->getPointerOperand()->getType());
1811 LI->setAlignment(Alignment);
1812 E->VectorizedValue = LI;
1813 return propagateMetadata(LI, E->Scalars);
1815 case Instruction::Store: {
1816 StoreInst *SI = cast<StoreInst>(VL0);
1817 unsigned Alignment = SI->getAlignment();
1818 unsigned AS = SI->getPointerAddressSpace();
1821 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1822 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1824 setInsertPointAfterBundle(E->Scalars);
1826 Value *VecValue = vectorizeTree(ValueOp);
1827 Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1828 VecTy->getPointerTo(AS));
1829 StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1831 Alignment = DL->getABITypeAlignment(SI->getPointerOperand()->getType());
1832 S->setAlignment(Alignment);
1833 E->VectorizedValue = S;
1834 return propagateMetadata(S, E->Scalars);
1836 case Instruction::GetElementPtr: {
1837 setInsertPointAfterBundle(E->Scalars);
1840 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1841 Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
1843 Value *Op0 = vectorizeTree(Op0VL);
1845 std::vector<Value *> OpVecs;
1846 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
1849 for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1850 OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
1852 Value *OpVec = vectorizeTree(OpVL);
1853 OpVecs.push_back(OpVec);
1856 Value *V = Builder.CreateGEP(Op0, OpVecs);
1857 E->VectorizedValue = V;
1859 if (Instruction *I = dyn_cast<Instruction>(V))
1860 return propagateMetadata(I, E->Scalars);
1864 case Instruction::Call: {
1865 CallInst *CI = cast<CallInst>(VL0);
1866 setInsertPointAfterBundle(E->Scalars);
1868 Intrinsic::ID IID = Intrinsic::not_intrinsic;
1869 if (CI && (FI = CI->getCalledFunction())) {
1870 IID = (Intrinsic::ID) FI->getIntrinsicID();
1872 std::vector<Value *> OpVecs;
1873 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
1875 // ctlz,cttz and powi are special intrinsics whose second argument is
1876 // a scalar. This argument should not be vectorized.
1877 if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
1878 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
1879 OpVecs.push_back(CEI->getArgOperand(j));
1882 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1883 CallInst *CEI = cast<CallInst>(E->Scalars[i]);
1884 OpVL.push_back(CEI->getArgOperand(j));
1887 Value *OpVec = vectorizeTree(OpVL);
1888 DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
1889 OpVecs.push_back(OpVec);
1892 Module *M = F->getParent();
1893 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1894 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
1895 Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
1896 Value *V = Builder.CreateCall(CF, OpVecs);
1897 E->VectorizedValue = V;
1900 case Instruction::ShuffleVector: {
1901 ValueList LHSVL, RHSVL;
1902 for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1903 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1904 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1906 setInsertPointAfterBundle(E->Scalars);
1908 Value *LHS = vectorizeTree(LHSVL);
1909 Value *RHS = vectorizeTree(RHSVL);
1911 if (Value *V = alreadyVectorized(E->Scalars))
1914 // Create a vector of LHS op1 RHS
1915 BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
1916 Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
1918 // Create a vector of LHS op2 RHS
1919 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
1920 BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
1921 Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
1923 // Create appropriate shuffle to take alternative operations from
1925 std::vector<Constant *> Mask(E->Scalars.size());
1926 unsigned e = E->Scalars.size();
1927 for (unsigned i = 0; i < e; ++i) {
1929 Mask[i] = Builder.getInt32(e + i);
1931 Mask[i] = Builder.getInt32(i);
1934 Value *ShuffleMask = ConstantVector::get(Mask);
1936 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
1937 E->VectorizedValue = V;
1938 if (Instruction *I = dyn_cast<Instruction>(V))
1939 return propagateMetadata(I, E->Scalars);
1944 llvm_unreachable("unknown inst");
1949 Value *BoUpSLP::vectorizeTree() {
1950 Builder.SetInsertPoint(F->getEntryBlock().begin());
1951 vectorizeTree(&VectorizableTree[0]);
1953 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1955 // Extract all of the elements with the external uses.
1956 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1958 Value *Scalar = it->Scalar;
1959 llvm::User *User = it->User;
1961 // Skip users that we already RAUW. This happens when one instruction
1962 // has multiple uses of the same value.
1963 if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
1966 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1968 int Idx = ScalarToTreeEntry[Scalar];
1969 TreeEntry *E = &VectorizableTree[Idx];
1970 assert(!E->NeedToGather && "Extracting from a gather list");
1972 Value *Vec = E->VectorizedValue;
1973 assert(Vec && "Can't find vectorizable value");
1975 Value *Lane = Builder.getInt32(it->Lane);
1976 // Generate extracts for out-of-tree users.
1977 // Find the insertion point for the extractelement lane.
1978 if (isa<Instruction>(Vec)){
1979 if (PHINode *PH = dyn_cast<PHINode>(User)) {
1980 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1981 if (PH->getIncomingValue(i) == Scalar) {
1982 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1983 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1984 CSEBlocks.insert(PH->getIncomingBlock(i));
1985 PH->setOperand(i, Ex);
1989 Builder.SetInsertPoint(cast<Instruction>(User));
1990 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1991 CSEBlocks.insert(cast<Instruction>(User)->getParent());
1992 User->replaceUsesOfWith(Scalar, Ex);
1995 Builder.SetInsertPoint(F->getEntryBlock().begin());
1996 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1997 CSEBlocks.insert(&F->getEntryBlock());
1998 User->replaceUsesOfWith(Scalar, Ex);
2001 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2004 // For each vectorized value:
2005 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2006 TreeEntry *Entry = &VectorizableTree[EIdx];
2009 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2010 Value *Scalar = Entry->Scalars[Lane];
2011 // No need to handle users of gathered values.
2012 if (Entry->NeedToGather)
2015 assert(Entry->VectorizedValue && "Can't find vectorizable value");
2017 Type *Ty = Scalar->getType();
2018 if (!Ty->isVoidTy()) {
2020 for (User *U : Scalar->users()) {
2021 DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2023 assert((ScalarToTreeEntry.count(U) ||
2024 // It is legal to replace users in the ignorelist by undef.
2025 (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2026 UserIgnoreList.end())) &&
2027 "Replacing out-of-tree value with undef");
2030 Value *Undef = UndefValue::get(Ty);
2031 Scalar->replaceAllUsesWith(Undef);
2033 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2034 cast<Instruction>(Scalar)->eraseFromParent();
2038 for (auto &BN : BlocksNumbers)
2041 Builder.ClearInsertionPoint();
2043 return VectorizableTree[0].VectorizedValue;
2046 void BoUpSLP::optimizeGatherSequence() {
2047 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2048 << " gather sequences instructions.\n");
2049 // LICM InsertElementInst sequences.
2050 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2051 e = GatherSeq.end(); it != e; ++it) {
2052 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2057 // Check if this block is inside a loop.
2058 Loop *L = LI->getLoopFor(Insert->getParent());
2062 // Check if it has a preheader.
2063 BasicBlock *PreHeader = L->getLoopPreheader();
2067 // If the vector or the element that we insert into it are
2068 // instructions that are defined in this basic block then we can't
2069 // hoist this instruction.
2070 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2071 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2072 if (CurrVec && L->contains(CurrVec))
2074 if (NewElem && L->contains(NewElem))
2077 // We can hoist this instruction. Move it to the pre-header.
2078 Insert->moveBefore(PreHeader->getTerminator());
2081 // Make a list of all reachable blocks in our CSE queue.
2082 SmallVector<const DomTreeNode *, 8> CSEWorkList;
2083 CSEWorkList.reserve(CSEBlocks.size());
2084 for (BasicBlock *BB : CSEBlocks)
2085 if (DomTreeNode *N = DT->getNode(BB)) {
2086 assert(DT->isReachableFromEntry(N));
2087 CSEWorkList.push_back(N);
2090 // Sort blocks by domination. This ensures we visit a block after all blocks
2091 // dominating it are visited.
2092 std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2093 [this](const DomTreeNode *A, const DomTreeNode *B) {
2094 return DT->properlyDominates(A, B);
2097 // Perform O(N^2) search over the gather sequences and merge identical
2098 // instructions. TODO: We can further optimize this scan if we split the
2099 // instructions into different buckets based on the insert lane.
2100 SmallVector<Instruction *, 16> Visited;
2101 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2102 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2103 "Worklist not sorted properly!");
2104 BasicBlock *BB = (*I)->getBlock();
2105 // For all instructions in blocks containing gather sequences:
2106 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2107 Instruction *In = it++;
2108 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2111 // Check if we can replace this instruction with any of the
2112 // visited instructions.
2113 for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2116 if (In->isIdenticalTo(*v) &&
2117 DT->dominates((*v)->getParent(), In->getParent())) {
2118 In->replaceAllUsesWith(*v);
2119 In->eraseFromParent();
2125 assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2126 Visited.push_back(In);
2134 /// The SLPVectorizer Pass.
2135 struct SLPVectorizer : public FunctionPass {
2136 typedef SmallVector<StoreInst *, 8> StoreList;
2137 typedef MapVector<Value *, StoreList> StoreListMap;
2139 /// Pass identification, replacement for typeid
2142 explicit SLPVectorizer() : FunctionPass(ID) {
2143 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
2146 ScalarEvolution *SE;
2147 const DataLayout *DL;
2148 TargetTransformInfo *TTI;
2149 TargetLibraryInfo *TLI;
2154 bool runOnFunction(Function &F) override {
2155 if (skipOptnoneFunction(F))
2158 SE = &getAnalysis<ScalarEvolution>();
2159 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2160 DL = DLP ? &DLP->getDataLayout() : nullptr;
2161 TTI = &getAnalysis<TargetTransformInfo>();
2162 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
2163 AA = &getAnalysis<AliasAnalysis>();
2164 LI = &getAnalysis<LoopInfo>();
2165 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2168 bool Changed = false;
2170 // If the target claims to have no vector registers don't attempt
2172 if (!TTI->getNumberOfRegisters(true))
2175 // Must have DataLayout. We can't require it because some tests run w/o
2180 // Don't vectorize when the attribute NoImplicitFloat is used.
2181 if (F.hasFnAttribute(Attribute::NoImplicitFloat))
2184 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
2186 // Use the bottom up slp vectorizer to construct chains that start with
2187 // store instructions.
2188 BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT);
2190 // Scan the blocks in the function in post order.
2191 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
2192 e = po_end(&F.getEntryBlock()); it != e; ++it) {
2193 BasicBlock *BB = *it;
2194 // Vectorize trees that end at stores.
2195 if (unsigned count = collectStores(BB, R)) {
2197 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
2198 Changed |= vectorizeStoreChains(R);
2201 // Vectorize trees that end at reductions.
2202 Changed |= vectorizeChainsInBlock(BB, R);
2206 R.optimizeGatherSequence();
2207 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
2208 DEBUG(verifyFunction(F));
2213 void getAnalysisUsage(AnalysisUsage &AU) const override {
2214 FunctionPass::getAnalysisUsage(AU);
2215 AU.addRequired<ScalarEvolution>();
2216 AU.addRequired<AliasAnalysis>();
2217 AU.addRequired<TargetTransformInfo>();
2218 AU.addRequired<LoopInfo>();
2219 AU.addRequired<DominatorTreeWrapperPass>();
2220 AU.addPreserved<LoopInfo>();
2221 AU.addPreserved<DominatorTreeWrapperPass>();
2222 AU.setPreservesCFG();
2227 /// \brief Collect memory references and sort them according to their base
2228 /// object. We sort the stores to their base objects to reduce the cost of the
2229 /// quadratic search on the stores. TODO: We can further reduce this cost
2230 /// if we flush the chain creation every time we run into a memory barrier.
2231 unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
2233 /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
2234 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
2236 /// \brief Try to vectorize a list of operands.
2237 /// \@param BuildVector A list of users to ignore for the purpose of
2238 /// scheduling and that don't need extracting.
2239 /// \returns true if a value was vectorized.
2240 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2241 ArrayRef<Value *> BuildVector = None);
2243 /// \brief Try to vectorize a chain that may start at the operands of \V;
2244 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
2246 /// \brief Vectorize the stores that were collected in StoreRefs.
2247 bool vectorizeStoreChains(BoUpSLP &R);
2249 /// \brief Scan the basic block and look for patterns that are likely to start
2250 /// a vectorization chain.
2251 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
2253 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
2256 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
2259 StoreListMap StoreRefs;
2262 /// \brief Check that the Values in the slice in VL array are still existent in
2263 /// the WeakVH array.
2264 /// Vectorization of part of the VL array may cause later values in the VL array
2265 /// to become invalid. We track when this has happened in the WeakVH array.
2266 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
2267 SmallVectorImpl<WeakVH> &VH,
2268 unsigned SliceBegin,
2269 unsigned SliceSize) {
2270 for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
2277 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
2278 int CostThreshold, BoUpSLP &R) {
2279 unsigned ChainLen = Chain.size();
2280 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
2282 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
2283 unsigned Sz = DL->getTypeSizeInBits(StoreTy);
2284 unsigned VF = MinVecRegSize / Sz;
2286 if (!isPowerOf2_32(Sz) || VF < 2)
2289 // Keep track of values that were deleted by vectorizing in the loop below.
2290 SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
2292 bool Changed = false;
2293 // Look for profitable vectorizable trees at all offsets, starting at zero.
2294 for (unsigned i = 0, e = ChainLen; i < e; ++i) {
2298 // Check that a previous iteration of this loop did not delete the Value.
2299 if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
2302 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
2304 ArrayRef<Value *> Operands = Chain.slice(i, VF);
2306 R.buildTree(Operands);
2308 int Cost = R.getTreeCost();
2310 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
2311 if (Cost < CostThreshold) {
2312 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
2315 // Move to the next bundle.
2324 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
2325 int costThreshold, BoUpSLP &R) {
2326 SetVector<Value *> Heads, Tails;
2327 SmallDenseMap<Value *, Value *> ConsecutiveChain;
2329 // We may run into multiple chains that merge into a single chain. We mark the
2330 // stores that we vectorized so that we don't visit the same store twice.
2331 BoUpSLP::ValueSet VectorizedStores;
2332 bool Changed = false;
2334 // Do a quadratic search on all of the given stores and find
2335 // all of the pairs of stores that follow each other.
2336 for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
2337 for (unsigned j = 0; j < e; ++j) {
2341 if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
2342 Tails.insert(Stores[j]);
2343 Heads.insert(Stores[i]);
2344 ConsecutiveChain[Stores[i]] = Stores[j];
2349 // For stores that start but don't end a link in the chain:
2350 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
2352 if (Tails.count(*it))
2355 // We found a store instr that starts a chain. Now follow the chain and try
2357 BoUpSLP::ValueList Operands;
2359 // Collect the chain into a list.
2360 while (Tails.count(I) || Heads.count(I)) {
2361 if (VectorizedStores.count(I))
2363 Operands.push_back(I);
2364 // Move to the next value in the chain.
2365 I = ConsecutiveChain[I];
2368 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
2370 // Mark the vectorized stores so that we don't vectorize them again.
2372 VectorizedStores.insert(Operands.begin(), Operands.end());
2373 Changed |= Vectorized;
2380 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
2383 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2384 StoreInst *SI = dyn_cast<StoreInst>(it);
2388 // Don't touch volatile stores.
2389 if (!SI->isSimple())
2392 // Check that the pointer points to scalars.
2393 Type *Ty = SI->getValueOperand()->getType();
2394 if (Ty->isAggregateType() || Ty->isVectorTy())
2397 // Find the base pointer.
2398 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2400 // Save the store locations.
2401 StoreRefs[Ptr].push_back(SI);
2407 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2410 Value *VL[] = { A, B };
2411 return tryToVectorizeList(VL, R);
2414 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
2415 ArrayRef<Value *> BuildVector) {
2419 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2421 // Check that all of the parts are scalar instructions of the same type.
2422 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2426 unsigned Opcode0 = I0->getOpcode();
2428 Type *Ty0 = I0->getType();
2429 unsigned Sz = DL->getTypeSizeInBits(Ty0);
2430 unsigned VF = MinVecRegSize / Sz;
2432 for (int i = 0, e = VL.size(); i < e; ++i) {
2433 Type *Ty = VL[i]->getType();
2434 if (Ty->isAggregateType() || Ty->isVectorTy())
2436 Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2437 if (!Inst || Inst->getOpcode() != Opcode0)
2441 bool Changed = false;
2443 // Keep track of values that were deleted by vectorizing in the loop below.
2444 SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2446 for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2447 unsigned OpsWidth = 0;
2454 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2457 // Check that a previous iteration of this loop did not delete the Value.
2458 if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2461 DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2463 ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2465 ArrayRef<Value *> BuildVectorSlice;
2466 if (!BuildVector.empty())
2467 BuildVectorSlice = BuildVector.slice(i, OpsWidth);
2469 R.buildTree(Ops, BuildVectorSlice);
2470 int Cost = R.getTreeCost();
2472 if (Cost < -SLPCostThreshold) {
2473 DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
2474 Value *VectorizedRoot = R.vectorizeTree();
2476 // Reconstruct the build vector by extracting the vectorized root. This
2477 // way we handle the case where some elements of the vector are undefined.
2478 // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
2479 if (!BuildVectorSlice.empty()) {
2480 // The insert point is the last build vector instruction. The vectorized
2481 // root will precede it. This guarantees that we get an instruction. The
2482 // vectorized tree could have been constant folded.
2483 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
2484 unsigned VecIdx = 0;
2485 for (auto &V : BuildVectorSlice) {
2486 IRBuilder<true, NoFolder> Builder(
2487 ++BasicBlock::iterator(InsertAfter));
2488 InsertElementInst *IE = cast<InsertElementInst>(V);
2489 Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
2490 VectorizedRoot, Builder.getInt32(VecIdx++)));
2491 IE->setOperand(1, Extract);
2492 IE->removeFromParent();
2493 IE->insertAfter(Extract);
2497 // Move to the next bundle.
2506 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2510 // Try to vectorize V.
2511 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2514 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2515 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2517 if (B && B->hasOneUse()) {
2518 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2519 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2520 if (tryToVectorizePair(A, B0, R)) {
2524 if (tryToVectorizePair(A, B1, R)) {
2531 if (A && A->hasOneUse()) {
2532 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2533 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2534 if (tryToVectorizePair(A0, B, R)) {
2538 if (tryToVectorizePair(A1, B, R)) {
2546 /// \brief Generate a shuffle mask to be used in a reduction tree.
2548 /// \param VecLen The length of the vector to be reduced.
2549 /// \param NumEltsToRdx The number of elements that should be reduced in the
2551 /// \param IsPairwise Whether the reduction is a pairwise or splitting
2552 /// reduction. A pairwise reduction will generate a mask of
2553 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
2554 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2555 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
2556 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2557 bool IsPairwise, bool IsLeft,
2558 IRBuilder<> &Builder) {
2559 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2561 SmallVector<Constant *, 32> ShuffleMask(
2562 VecLen, UndefValue::get(Builder.getInt32Ty()));
2565 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2566 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2567 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2569 // Move the upper half of the vector to the lower half.
2570 for (unsigned i = 0; i != NumEltsToRdx; ++i)
2571 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2573 return ConstantVector::get(ShuffleMask);
2577 /// Model horizontal reductions.
2579 /// A horizontal reduction is a tree of reduction operations (currently add and
2580 /// fadd) that has operations that can be put into a vector as its leaf.
2581 /// For example, this tree:
2588 /// This tree has "mul" as its reduced values and "+" as its reduction
2589 /// operations. A reduction might be feeding into a store or a binary operation
2604 class HorizontalReduction {
2605 SmallVector<Value *, 16> ReductionOps;
2606 SmallVector<Value *, 32> ReducedVals;
2608 BinaryOperator *ReductionRoot;
2609 PHINode *ReductionPHI;
2611 /// The opcode of the reduction.
2612 unsigned ReductionOpcode;
2613 /// The opcode of the values we perform a reduction on.
2614 unsigned ReducedValueOpcode;
2615 /// The width of one full horizontal reduction operation.
2616 unsigned ReduxWidth;
2617 /// Should we model this reduction as a pairwise reduction tree or a tree that
2618 /// splits the vector in halves and adds those halves.
2619 bool IsPairwiseReduction;
2622 HorizontalReduction()
2623 : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
2624 ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2626 /// \brief Try to find a reduction tree.
2627 bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2628 const DataLayout *DL) {
2630 std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2631 "Thi phi needs to use the binary operator");
2633 // We could have a initial reductions that is not an add.
2634 // r *= v1 + v2 + v3 + v4
2635 // In such a case start looking for a tree rooted in the first '+'.
2637 if (B->getOperand(0) == Phi) {
2639 B = dyn_cast<BinaryOperator>(B->getOperand(1));
2640 } else if (B->getOperand(1) == Phi) {
2642 B = dyn_cast<BinaryOperator>(B->getOperand(0));
2649 Type *Ty = B->getType();
2650 if (Ty->isVectorTy())
2653 ReductionOpcode = B->getOpcode();
2654 ReducedValueOpcode = 0;
2655 ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2662 // We currently only support adds.
2663 if (ReductionOpcode != Instruction::Add &&
2664 ReductionOpcode != Instruction::FAdd)
2667 // Post order traverse the reduction tree starting at B. We only handle true
2668 // trees containing only binary operators.
2669 SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2670 Stack.push_back(std::make_pair(B, 0));
2671 while (!Stack.empty()) {
2672 BinaryOperator *TreeN = Stack.back().first;
2673 unsigned EdgeToVist = Stack.back().second++;
2674 bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2676 // Only handle trees in the current basic block.
2677 if (TreeN->getParent() != B->getParent())
2680 // Each tree node needs to have one user except for the ultimate
2682 if (!TreeN->hasOneUse() && TreeN != B)
2686 if (EdgeToVist == 2 || IsReducedValue) {
2687 if (IsReducedValue) {
2688 // Make sure that the opcodes of the operations that we are going to
2690 if (!ReducedValueOpcode)
2691 ReducedValueOpcode = TreeN->getOpcode();
2692 else if (ReducedValueOpcode != TreeN->getOpcode())
2694 ReducedVals.push_back(TreeN);
2696 // We need to be able to reassociate the adds.
2697 if (!TreeN->isAssociative())
2699 ReductionOps.push_back(TreeN);
2706 // Visit left or right.
2707 Value *NextV = TreeN->getOperand(EdgeToVist);
2708 BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2710 Stack.push_back(std::make_pair(Next, 0));
2711 else if (NextV != Phi)
2717 /// \brief Attempt to vectorize the tree found by
2718 /// matchAssociativeReduction.
2719 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2720 if (ReducedVals.empty())
2723 unsigned NumReducedVals = ReducedVals.size();
2724 if (NumReducedVals < ReduxWidth)
2727 Value *VectorizedTree = nullptr;
2728 IRBuilder<> Builder(ReductionRoot);
2729 FastMathFlags Unsafe;
2730 Unsafe.setUnsafeAlgebra();
2731 Builder.SetFastMathFlags(Unsafe);
2734 for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2735 ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2736 V.buildTree(ValsToReduce, ReductionOps);
2739 int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2740 if (Cost >= -SLPCostThreshold)
2743 DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2746 // Vectorize a tree.
2747 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2748 Value *VectorizedRoot = V.vectorizeTree();
2750 // Emit a reduction.
2751 Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2752 if (VectorizedTree) {
2753 Builder.SetCurrentDebugLocation(Loc);
2754 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2755 ReducedSubTree, "bin.rdx");
2757 VectorizedTree = ReducedSubTree;
2760 if (VectorizedTree) {
2761 // Finish the reduction.
2762 for (; i < NumReducedVals; ++i) {
2763 Builder.SetCurrentDebugLocation(
2764 cast<Instruction>(ReducedVals[i])->getDebugLoc());
2765 VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2770 assert(ReductionRoot && "Need a reduction operation");
2771 ReductionRoot->setOperand(0, VectorizedTree);
2772 ReductionRoot->setOperand(1, ReductionPHI);
2774 ReductionRoot->replaceAllUsesWith(VectorizedTree);
2776 return VectorizedTree != nullptr;
2781 /// \brief Calcuate the cost of a reduction.
2782 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2783 Type *ScalarTy = FirstReducedVal->getType();
2784 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2786 int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2787 int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2789 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2790 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2792 int ScalarReduxCost =
2793 ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2795 DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2796 << " for reduction that starts with " << *FirstReducedVal
2798 << (IsPairwiseReduction ? "pairwise" : "splitting")
2799 << " reduction)\n");
2801 return VecReduxCost - ScalarReduxCost;
2804 static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2805 Value *R, const Twine &Name = "") {
2806 if (Opcode == Instruction::FAdd)
2807 return Builder.CreateFAdd(L, R, Name);
2808 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2811 /// \brief Emit a horizontal reduction of the vectorized value.
2812 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2813 assert(VectorizedValue && "Need to have a vectorized tree node");
2814 Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2815 assert(isPowerOf2_32(ReduxWidth) &&
2816 "We only handle power-of-two reductions for now");
2818 Value *TmpVec = ValToReduce;
2819 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2820 if (IsPairwiseReduction) {
2822 createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2824 createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2826 Value *LeftShuf = Builder.CreateShuffleVector(
2827 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2828 Value *RightShuf = Builder.CreateShuffleVector(
2829 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2831 TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2835 createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2836 Value *Shuf = Builder.CreateShuffleVector(
2837 TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2838 TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2842 // The result is in the first element of the vector.
2843 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2847 /// \brief Recognize construction of vectors like
2848 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
2849 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
2850 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
2851 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
2853 /// Returns true if it matches
2855 static bool findBuildVector(InsertElementInst *FirstInsertElem,
2856 SmallVectorImpl<Value *> &BuildVector,
2857 SmallVectorImpl<Value *> &BuildVectorOpds) {
2858 if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
2861 InsertElementInst *IE = FirstInsertElem;
2863 BuildVector.push_back(IE);
2864 BuildVectorOpds.push_back(IE->getOperand(1));
2866 if (IE->use_empty())
2869 InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
2873 // If this isn't the final use, make sure the next insertelement is the only
2874 // use. It's OK if the final constructed vector is used multiple times
2875 if (!IE->hasOneUse())
2884 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2885 return V->getType() < V2->getType();
2888 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2889 bool Changed = false;
2890 SmallVector<Value *, 4> Incoming;
2891 SmallSet<Value *, 16> VisitedInstrs;
2893 bool HaveVectorizedPhiNodes = true;
2894 while (HaveVectorizedPhiNodes) {
2895 HaveVectorizedPhiNodes = false;
2897 // Collect the incoming values from the PHIs.
2899 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2901 PHINode *P = dyn_cast<PHINode>(instr);
2905 if (!VisitedInstrs.count(P))
2906 Incoming.push_back(P);
2910 std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2912 // Try to vectorize elements base on their type.
2913 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2917 // Look for the next elements with the same type.
2918 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2919 while (SameTypeIt != E &&
2920 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2921 VisitedInstrs.insert(*SameTypeIt);
2925 // Try to vectorize them.
2926 unsigned NumElts = (SameTypeIt - IncIt);
2927 DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2929 tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2930 // Success start over because instructions might have been changed.
2931 HaveVectorizedPhiNodes = true;
2936 // Start over at the next instruction of a different type (or the end).
2941 VisitedInstrs.clear();
2943 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2944 // We may go through BB multiple times so skip the one we have checked.
2945 if (!VisitedInstrs.insert(it))
2948 if (isa<DbgInfoIntrinsic>(it))
2951 // Try to vectorize reductions that use PHINodes.
2952 if (PHINode *P = dyn_cast<PHINode>(it)) {
2953 // Check that the PHI is a reduction PHI.
2954 if (P->getNumIncomingValues() != 2)
2957 (P->getIncomingBlock(0) == BB
2958 ? (P->getIncomingValue(0))
2959 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
2961 // Check if this is a Binary Operator.
2962 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2966 // Try to match and vectorize a horizontal reduction.
2967 HorizontalReduction HorRdx;
2968 if (ShouldVectorizeHor &&
2969 HorRdx.matchAssociativeReduction(P, BI, DL) &&
2970 HorRdx.tryToReduce(R, TTI)) {
2977 Value *Inst = BI->getOperand(0);
2979 Inst = BI->getOperand(1);
2981 if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2982 // We would like to start over since some instructions are deleted
2983 // and the iterator may become invalid value.
2993 // Try to vectorize horizontal reductions feeding into a store.
2994 if (ShouldStartVectorizeHorAtStore)
2995 if (StoreInst *SI = dyn_cast<StoreInst>(it))
2996 if (BinaryOperator *BinOp =
2997 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2998 HorizontalReduction HorRdx;
2999 if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3000 HorRdx.tryToReduce(R, TTI)) ||
3001 tryToVectorize(BinOp, R))) {
3009 // Try to vectorize trees that start at compare instructions.
3010 if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3011 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3013 // We would like to start over since some instructions are deleted
3014 // and the iterator may become invalid value.
3020 for (int i = 0; i < 2; ++i) {
3021 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3022 if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3024 // We would like to start over since some instructions are deleted
3025 // and the iterator may become invalid value.
3034 // Try to vectorize trees that start at insertelement instructions.
3035 if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3036 SmallVector<Value *, 16> BuildVector;
3037 SmallVector<Value *, 16> BuildVectorOpds;
3038 if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3041 // Vectorize starting with the build vector operands ignoring the
3042 // BuildVector instructions for the purpose of scheduling and user
3044 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3057 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3058 bool Changed = false;
3059 // Attempt to sort and vectorize each of the store-groups.
3060 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3062 if (it->second.size() < 2)
3065 DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3066 << it->second.size() << ".\n");
3068 // Process the stores in chunks of 16.
3069 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3070 unsigned Len = std::min<unsigned>(CE - CI, 16);
3071 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
3072 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
3078 } // end anonymous namespace
3080 char SLPVectorizer::ID = 0;
3081 static const char lv_name[] = "SLP Vectorizer";
3082 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3083 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3084 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3085 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3086 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3087 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3090 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }