SLPVectorizer.cpp revision a0d44fe4cd92c11466b82af4f5089af845a2eeb5
1//===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
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.
13//
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.
16//
17//===----------------------------------------------------------------------===//
18#define SV_NAME "slp-vectorizer"
19#define DEBUG_TYPE "SLP"
20
21#include "llvm/Transforms/Vectorize.h"
22#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/PostOrderIterator.h"
24#include "llvm/ADT/SetVector.h"
25#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpressions.h"
28#include "llvm/Analysis/TargetTransformInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
30#include "llvm/Analysis/Verifier.h"
31#include "llvm/Analysis/LoopInfo.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Pass.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/raw_ostream.h"
43#include <algorithm>
44#include <map>
45
46using namespace llvm;
47
48static cl::opt<int>
49    SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
50                     cl::desc("Only vectorize if you gain more than this "
51                              "number "));
52
53static cl::opt<bool>
54ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
55                   cl::desc("Attempt to vectorize horizontal reductions"));
56
57static cl::opt<bool> ShouldStartVectorizeHorAtStore(
58    "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
59    cl::desc(
60        "Attempt to vectorize horizontal reductions feeding into a store"));
61
62namespace {
63
64static const unsigned MinVecRegSize = 128;
65
66static const unsigned RecursionMaxDepth = 12;
67
68/// A helper class for numbering instructions in multiple blocks.
69/// Numbers start at zero for each basic block.
70struct BlockNumbering {
71
72  BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
73
74  BlockNumbering() : BB(0), Valid(false) {}
75
76  void numberInstructions() {
77    unsigned Loc = 0;
78    InstrIdx.clear();
79    InstrVec.clear();
80    // Number the instructions in the block.
81    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
82      InstrIdx[it] = Loc++;
83      InstrVec.push_back(it);
84      assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
85    }
86    Valid = true;
87  }
88
89  int getIndex(Instruction *I) {
90    assert(I->getParent() == BB && "Invalid instruction");
91    if (!Valid)
92      numberInstructions();
93    assert(InstrIdx.count(I) && "Unknown instruction");
94    return InstrIdx[I];
95  }
96
97  Instruction *getInstruction(unsigned loc) {
98    if (!Valid)
99      numberInstructions();
100    assert(InstrVec.size() > loc && "Invalid Index");
101    return InstrVec[loc];
102  }
103
104  void forget() { Valid = false; }
105
106private:
107  /// The block we are numbering.
108  BasicBlock *BB;
109  /// Is the block numbered.
110  bool Valid;
111  /// Maps instructions to numbers and back.
112  SmallDenseMap<Instruction *, int> InstrIdx;
113  /// Maps integers to Instructions.
114  SmallVector<Instruction *, 32> InstrVec;
115};
116
117/// \returns the parent basic block if all of the instructions in \p VL
118/// are in the same block or null otherwise.
119static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
120  Instruction *I0 = dyn_cast<Instruction>(VL[0]);
121  if (!I0)
122    return 0;
123  BasicBlock *BB = I0->getParent();
124  for (int i = 1, e = VL.size(); i < e; i++) {
125    Instruction *I = dyn_cast<Instruction>(VL[i]);
126    if (!I)
127      return 0;
128
129    if (BB != I->getParent())
130      return 0;
131  }
132  return BB;
133}
134
135/// \returns True if all of the values in \p VL are constants.
136static bool allConstant(ArrayRef<Value *> VL) {
137  for (unsigned i = 0, e = VL.size(); i < e; ++i)
138    if (!isa<Constant>(VL[i]))
139      return false;
140  return true;
141}
142
143/// \returns True if all of the values in \p VL are identical.
144static bool isSplat(ArrayRef<Value *> VL) {
145  for (unsigned i = 1, e = VL.size(); i < e; ++i)
146    if (VL[i] != VL[0])
147      return false;
148  return true;
149}
150
151/// \returns The opcode if all of the Instructions in \p VL have the same
152/// opcode, or zero.
153static unsigned getSameOpcode(ArrayRef<Value *> VL) {
154  Instruction *I0 = dyn_cast<Instruction>(VL[0]);
155  if (!I0)
156    return 0;
157  unsigned Opcode = I0->getOpcode();
158  for (int i = 1, e = VL.size(); i < e; i++) {
159    Instruction *I = dyn_cast<Instruction>(VL[i]);
160    if (!I || Opcode != I->getOpcode())
161      return 0;
162  }
163  return Opcode;
164}
165
166/// \returns \p I after propagating metadata from \p VL.
167static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
168  Instruction *I0 = cast<Instruction>(VL[0]);
169  SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
170  I0->getAllMetadataOtherThanDebugLoc(Metadata);
171
172  for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
173    unsigned Kind = Metadata[i].first;
174    MDNode *MD = Metadata[i].second;
175
176    for (int i = 1, e = VL.size(); MD && i != e; i++) {
177      Instruction *I = cast<Instruction>(VL[i]);
178      MDNode *IMD = I->getMetadata(Kind);
179
180      switch (Kind) {
181      default:
182        MD = 0; // Remove unknown metadata
183        break;
184      case LLVMContext::MD_tbaa:
185        MD = MDNode::getMostGenericTBAA(MD, IMD);
186        break;
187      case LLVMContext::MD_fpmath:
188        MD = MDNode::getMostGenericFPMath(MD, IMD);
189        break;
190      }
191    }
192    I->setMetadata(Kind, MD);
193  }
194  return I;
195}
196
197/// \returns The type that all of the values in \p VL have or null if there
198/// are different types.
199static Type* getSameType(ArrayRef<Value *> VL) {
200  Type *Ty = VL[0]->getType();
201  for (int i = 1, e = VL.size(); i < e; i++)
202    if (VL[i]->getType() != Ty)
203      return 0;
204
205  return Ty;
206}
207
208/// \returns True if the ExtractElement instructions in VL can be vectorized
209/// to use the original vector.
210static bool CanReuseExtract(ArrayRef<Value *> VL) {
211  assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
212  // Check if all of the extracts come from the same vector and from the
213  // correct offset.
214  Value *VL0 = VL[0];
215  ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
216  Value *Vec = E0->getOperand(0);
217
218  // We have to extract from the same vector type.
219  unsigned NElts = Vec->getType()->getVectorNumElements();
220
221  if (NElts != VL.size())
222    return false;
223
224  // Check that all of the indices extract from the correct offset.
225  ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
226  if (!CI || CI->getZExtValue())
227    return false;
228
229  for (unsigned i = 1, e = VL.size(); i < e; ++i) {
230    ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
231    ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
232
233    if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
234      return false;
235  }
236
237  return true;
238}
239
240static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
241                                           SmallVectorImpl<Value *> &Left,
242                                           SmallVectorImpl<Value *> &Right) {
243
244  SmallVector<Value *, 16> OrigLeft, OrigRight;
245
246  bool AllSameOpcodeLeft = true;
247  bool AllSameOpcodeRight = true;
248  for (unsigned i = 0, e = VL.size(); i != e; ++i) {
249    Instruction *I = cast<Instruction>(VL[i]);
250    Value *V0 = I->getOperand(0);
251    Value *V1 = I->getOperand(1);
252
253    OrigLeft.push_back(V0);
254    OrigRight.push_back(V1);
255
256    Instruction *I0 = dyn_cast<Instruction>(V0);
257    Instruction *I1 = dyn_cast<Instruction>(V1);
258
259    // Check whether all operands on one side have the same opcode. In this case
260    // we want to preserve the original order and not make things worse by
261    // reordering.
262    AllSameOpcodeLeft = I0;
263    AllSameOpcodeRight = I1;
264
265    if (i && AllSameOpcodeLeft) {
266      if(Instruction *P0 = dyn_cast<Instruction>(OrigLeft[i-1])) {
267        if(P0->getOpcode() != I0->getOpcode())
268          AllSameOpcodeLeft = false;
269      } else
270        AllSameOpcodeLeft = false;
271    }
272    if (i && AllSameOpcodeRight) {
273      if(Instruction *P1 = dyn_cast<Instruction>(OrigRight[i-1])) {
274        if(P1->getOpcode() != I1->getOpcode())
275          AllSameOpcodeRight = false;
276      } else
277        AllSameOpcodeRight = false;
278    }
279
280    // Sort two opcodes. In the code below we try to preserve the ability to use
281    // broadcast of values instead of individual inserts.
282    // vl1 = load
283    // vl2 = phi
284    // vr1 = load
285    // vr2 = vr2
286    //    = vl1 x vr1
287    //    = vl2 x vr2
288    // If we just sorted according to opcode we would leave the first line in
289    // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
290    //    = vl1 x vr1
291    //    = vr2 x vl2
292    // Because vr2 and vr1 are from the same load we loose the opportunity of a
293    // broadcast for the packed right side in the backend: we have [vr1, vl2]
294    // instead of [vr1, vr2=vr1].
295    if (I0 && I1) {
296       if(!i && I0->getOpcode() > I1->getOpcode()) {
297         Left.push_back(I1);
298         Right.push_back(I0);
299       } else if (i && I0->getOpcode() > I1->getOpcode() && Right[i-1] != I1) {
300         // Try not to destroy a broad cast for no apparent benefit.
301         Left.push_back(I1);
302         Right.push_back(I0);
303       } else if (i && I0->getOpcode() == I1->getOpcode() && Right[i-1] ==  I0) {
304         // Try preserve broadcasts.
305         Left.push_back(I1);
306         Right.push_back(I0);
307       } else if (i && I0->getOpcode() == I1->getOpcode() && Left[i-1] == I1) {
308         // Try preserve broadcasts.
309         Left.push_back(I1);
310         Right.push_back(I0);
311       } else {
312         Left.push_back(I0);
313         Right.push_back(I1);
314       }
315       continue;
316    }
317    // One opcode, put the instruction on the right.
318    if (I0) {
319      Left.push_back(V1);
320      Right.push_back(I0);
321      continue;
322    }
323    Left.push_back(V0);
324    Right.push_back(V1);
325  }
326
327  bool LeftBroadcast = isSplat(Left);
328  bool RightBroadcast = isSplat(Right);
329
330  // Don't reorder if the operands where good to begin with.
331  if (!(LeftBroadcast || RightBroadcast) &&
332      (AllSameOpcodeRight || AllSameOpcodeLeft)) {
333    Left = OrigLeft;
334    Right = OrigRight;
335  }
336}
337
338/// Bottom Up SLP Vectorizer.
339class BoUpSLP {
340public:
341  typedef SmallVector<Value *, 8> ValueList;
342  typedef SmallVector<Instruction *, 16> InstrList;
343  typedef SmallPtrSet<Value *, 16> ValueSet;
344  typedef SmallVector<StoreInst *, 8> StoreList;
345
346  BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
347          TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
348          DominatorTree *Dt) :
349    F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
350    Builder(Se->getContext()) {
351      // Setup the block numbering utility for all of the blocks in the
352      // function.
353      for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
354        BasicBlock *BB = it;
355        BlocksNumbers[BB] = BlockNumbering(BB);
356      }
357    }
358
359  /// \brief Vectorize the tree that starts with the elements in \p VL.
360  /// Returns the vectorized root.
361  Value *vectorizeTree();
362
363  /// \returns the vectorization cost of the subtree that starts at \p VL.
364  /// A negative number means that this is profitable.
365  int getTreeCost();
366
367  /// Construct a vectorizable tree that starts at \p Roots and is possibly
368  /// used by a reduction of \p RdxOps.
369  void buildTree(ArrayRef<Value *> Roots, ValueSet *RdxOps = 0);
370
371  /// Clear the internal data structures that are created by 'buildTree'.
372  void deleteTree() {
373    RdxOps = 0;
374    VectorizableTree.clear();
375    ScalarToTreeEntry.clear();
376    MustGather.clear();
377    ExternalUses.clear();
378    MemBarrierIgnoreList.clear();
379  }
380
381  /// \returns true if the memory operations A and B are consecutive.
382  bool isConsecutiveAccess(Value *A, Value *B);
383
384  /// \brief Perform LICM and CSE on the newly generated gather sequences.
385  void optimizeGatherSequence();
386private:
387  struct TreeEntry;
388
389  /// \returns the cost of the vectorizable entry.
390  int getEntryCost(TreeEntry *E);
391
392  /// This is the recursive part of buildTree.
393  void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
394
395  /// Vectorize a single entry in the tree.
396  Value *vectorizeTree(TreeEntry *E);
397
398  /// Vectorize a single entry in the tree, starting in \p VL.
399  Value *vectorizeTree(ArrayRef<Value *> VL);
400
401  /// \returns the pointer to the vectorized value if \p VL is already
402  /// vectorized, or NULL. They may happen in cycles.
403  Value *alreadyVectorized(ArrayRef<Value *> VL) const;
404
405  /// \brief Take the pointer operand from the Load/Store instruction.
406  /// \returns NULL if this is not a valid Load/Store instruction.
407  static Value *getPointerOperand(Value *I);
408
409  /// \brief Take the address space operand from the Load/Store instruction.
410  /// \returns -1 if this is not a valid Load/Store instruction.
411  static unsigned getAddressSpaceOperand(Value *I);
412
413  /// \returns the scalarization cost for this type. Scalarization in this
414  /// context means the creation of vectors from a group of scalars.
415  int getGatherCost(Type *Ty);
416
417  /// \returns the scalarization cost for this list of values. Assuming that
418  /// this subtree gets vectorized, we may need to extract the values from the
419  /// roots. This method calculates the cost of extracting the values.
420  int getGatherCost(ArrayRef<Value *> VL);
421
422  /// \returns the AA location that is being access by the instruction.
423  AliasAnalysis::Location getLocation(Instruction *I);
424
425  /// \brief Checks if it is possible to sink an instruction from
426  /// \p Src to \p Dst.
427  /// \returns the pointer to the barrier instruction if we can't sink.
428  Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
429
430  /// \returns the index of the last instruction in the BB from \p VL.
431  int getLastIndex(ArrayRef<Value *> VL);
432
433  /// \returns the Instruction in the bundle \p VL.
434  Instruction *getLastInstruction(ArrayRef<Value *> VL);
435
436  /// \brief Set the Builder insert point to one after the last instruction in
437  /// the bundle
438  void setInsertPointAfterBundle(ArrayRef<Value *> VL);
439
440  /// \returns a vector from a collection of scalars in \p VL.
441  Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
442
443  /// \returns whether the VectorizableTree is fully vectoriable and will
444  /// be beneficial even the tree height is tiny.
445  bool isFullyVectorizableTinyTree();
446
447  struct TreeEntry {
448    TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
449    NeedToGather(0) {}
450
451    /// \returns true if the scalars in VL are equal to this entry.
452    bool isSame(ArrayRef<Value *> VL) const {
453      assert(VL.size() == Scalars.size() && "Invalid size");
454      return std::equal(VL.begin(), VL.end(), Scalars.begin());
455    }
456
457    /// A vector of scalars.
458    ValueList Scalars;
459
460    /// The Scalars are vectorized into this value. It is initialized to Null.
461    Value *VectorizedValue;
462
463    /// The index in the basic block of the last scalar.
464    int LastScalarIndex;
465
466    /// Do we need to gather this sequence ?
467    bool NeedToGather;
468  };
469
470  /// Create a new VectorizableTree entry.
471  TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
472    VectorizableTree.push_back(TreeEntry());
473    int idx = VectorizableTree.size() - 1;
474    TreeEntry *Last = &VectorizableTree[idx];
475    Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
476    Last->NeedToGather = !Vectorized;
477    if (Vectorized) {
478      Last->LastScalarIndex = getLastIndex(VL);
479      for (int i = 0, e = VL.size(); i != e; ++i) {
480        assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
481        ScalarToTreeEntry[VL[i]] = idx;
482      }
483    } else {
484      Last->LastScalarIndex = 0;
485      MustGather.insert(VL.begin(), VL.end());
486    }
487    return Last;
488  }
489
490  /// -- Vectorization State --
491  /// Holds all of the tree entries.
492  std::vector<TreeEntry> VectorizableTree;
493
494  /// Maps a specific scalar to its tree entry.
495  SmallDenseMap<Value*, int> ScalarToTreeEntry;
496
497  /// A list of scalars that we found that we need to keep as scalars.
498  ValueSet MustGather;
499
500  /// This POD struct describes one external user in the vectorized tree.
501  struct ExternalUser {
502    ExternalUser (Value *S, llvm::User *U, int L) :
503      Scalar(S), User(U), Lane(L){};
504    // Which scalar in our function.
505    Value *Scalar;
506    // Which user that uses the scalar.
507    llvm::User *User;
508    // Which lane does the scalar belong to.
509    int Lane;
510  };
511  typedef SmallVector<ExternalUser, 16> UserList;
512
513  /// A list of values that need to extracted out of the tree.
514  /// This list holds pairs of (Internal Scalar : External User).
515  UserList ExternalUses;
516
517  /// A list of instructions to ignore while sinking
518  /// memory instructions. This map must be reset between runs of getCost.
519  ValueSet MemBarrierIgnoreList;
520
521  /// Holds all of the instructions that we gathered.
522  SetVector<Instruction *> GatherSeq;
523  /// A list of blocks that we are going to CSE.
524  SmallSet<BasicBlock *, 8> CSEBlocks;
525
526  /// Numbers instructions in different blocks.
527  DenseMap<BasicBlock *, BlockNumbering> BlocksNumbers;
528
529  /// Reduction operators.
530  ValueSet *RdxOps;
531
532  // Analysis and block reference.
533  Function *F;
534  ScalarEvolution *SE;
535  DataLayout *DL;
536  TargetTransformInfo *TTI;
537  AliasAnalysis *AA;
538  LoopInfo *LI;
539  DominatorTree *DT;
540  /// Instruction builder to construct the vectorized tree.
541  IRBuilder<> Builder;
542};
543
544void BoUpSLP::buildTree(ArrayRef<Value *> Roots, ValueSet *Rdx) {
545  deleteTree();
546  RdxOps = Rdx;
547  if (!getSameType(Roots))
548    return;
549  buildTree_rec(Roots, 0);
550
551  // Collect the values that we need to extract from the tree.
552  for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
553    TreeEntry *Entry = &VectorizableTree[EIdx];
554
555    // For each lane:
556    for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
557      Value *Scalar = Entry->Scalars[Lane];
558
559      // No need to handle users of gathered values.
560      if (Entry->NeedToGather)
561        continue;
562
563      for (Value::use_iterator User = Scalar->use_begin(),
564           UE = Scalar->use_end(); User != UE; ++User) {
565        DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n");
566
567        bool Gathered = MustGather.count(*User);
568
569        // Skip in-tree scalars that become vectors.
570        if (ScalarToTreeEntry.count(*User) && !Gathered) {
571          DEBUG(dbgs() << "SLP: \tInternal user will be removed:" <<
572                **User << ".\n");
573          int Idx = ScalarToTreeEntry[*User]; (void) Idx;
574          assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
575          continue;
576        }
577        Instruction *UserInst = dyn_cast<Instruction>(*User);
578        if (!UserInst)
579          continue;
580
581        // Ignore uses that are part of the reduction.
582        if (Rdx && std::find(Rdx->begin(), Rdx->end(), UserInst) != Rdx->end())
583          continue;
584
585        DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " <<
586              Lane << " from " << *Scalar << ".\n");
587        ExternalUses.push_back(ExternalUser(Scalar, *User, Lane));
588      }
589    }
590  }
591}
592
593
594void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
595  bool SameTy = getSameType(VL); (void)SameTy;
596  assert(SameTy && "Invalid types!");
597
598  if (Depth == RecursionMaxDepth) {
599    DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
600    newTreeEntry(VL, false);
601    return;
602  }
603
604  // Don't handle vectors.
605  if (VL[0]->getType()->isVectorTy()) {
606    DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
607    newTreeEntry(VL, false);
608    return;
609  }
610
611  if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
612    if (SI->getValueOperand()->getType()->isVectorTy()) {
613      DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
614      newTreeEntry(VL, false);
615      return;
616    }
617
618  // If all of the operands are identical or constant we have a simple solution.
619  if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
620      !getSameOpcode(VL)) {
621    DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
622    newTreeEntry(VL, false);
623    return;
624  }
625
626  // We now know that this is a vector of instructions of the same type from
627  // the same block.
628
629  // Check if this is a duplicate of another entry.
630  if (ScalarToTreeEntry.count(VL[0])) {
631    int Idx = ScalarToTreeEntry[VL[0]];
632    TreeEntry *E = &VectorizableTree[Idx];
633    for (unsigned i = 0, e = VL.size(); i != e; ++i) {
634      DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
635      if (E->Scalars[i] != VL[i]) {
636        DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
637        newTreeEntry(VL, false);
638        return;
639      }
640    }
641    DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
642    return;
643  }
644
645  // Check that none of the instructions in the bundle are already in the tree.
646  for (unsigned i = 0, e = VL.size(); i != e; ++i) {
647    if (ScalarToTreeEntry.count(VL[i])) {
648      DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
649            ") is already in tree.\n");
650      newTreeEntry(VL, false);
651      return;
652    }
653  }
654
655  // If any of the scalars appears in the table OR it is marked as a value that
656  // needs to stat scalar then we need to gather the scalars.
657  for (unsigned i = 0, e = VL.size(); i != e; ++i) {
658    if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
659      DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
660      newTreeEntry(VL, false);
661      return;
662    }
663  }
664
665  // Check that all of the users of the scalars that we want to vectorize are
666  // schedulable.
667  Instruction *VL0 = cast<Instruction>(VL[0]);
668  int MyLastIndex = getLastIndex(VL);
669  BasicBlock *BB = cast<Instruction>(VL0)->getParent();
670
671  for (unsigned i = 0, e = VL.size(); i != e; ++i) {
672    Instruction *Scalar = cast<Instruction>(VL[i]);
673    DEBUG(dbgs() << "SLP: Checking users of  " << *Scalar << ". \n");
674    for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
675         U != UE; ++U) {
676      DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
677      Instruction *User = dyn_cast<Instruction>(*U);
678      if (!User) {
679        DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
680        newTreeEntry(VL, false);
681        return;
682      }
683
684      // We don't care if the user is in a different basic block.
685      BasicBlock *UserBlock = User->getParent();
686      if (UserBlock != BB) {
687        DEBUG(dbgs() << "SLP: User from a different basic block "
688              << *User << ". \n");
689        continue;
690      }
691
692      // If this is a PHINode within this basic block then we can place the
693      // extract wherever we want.
694      if (isa<PHINode>(*User)) {
695        DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
696        continue;
697      }
698
699      // Check if this is a safe in-tree user.
700      if (ScalarToTreeEntry.count(User)) {
701        int Idx = ScalarToTreeEntry[User];
702        int VecLocation = VectorizableTree[Idx].LastScalarIndex;
703        if (VecLocation <= MyLastIndex) {
704          DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
705          newTreeEntry(VL, false);
706          return;
707        }
708        DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
709              VecLocation << " vector value (" << *Scalar << ") at #"
710              << MyLastIndex << ".\n");
711        continue;
712      }
713
714      // This user is part of the reduction.
715      if (RdxOps && RdxOps->count(User))
716        continue;
717
718      // Make sure that we can schedule this unknown user.
719      BlockNumbering &BN = BlocksNumbers[BB];
720      int UserIndex = BN.getIndex(User);
721      if (UserIndex < MyLastIndex) {
722
723        DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
724              << *User << ". \n");
725        newTreeEntry(VL, false);
726        return;
727      }
728    }
729  }
730
731  // Check that every instructions appears once in this bundle.
732  for (unsigned i = 0, e = VL.size(); i < e; ++i)
733    for (unsigned j = i+1; j < e; ++j)
734      if (VL[i] == VL[j]) {
735        DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
736        newTreeEntry(VL, false);
737        return;
738      }
739
740  // Check that instructions in this bundle don't reference other instructions.
741  // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
742  for (unsigned i = 0, e = VL.size(); i < e; ++i) {
743    for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
744         U != UE; ++U) {
745      for (unsigned j = 0; j < e; ++j) {
746        if (i != j && *U == VL[j]) {
747          DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
748          newTreeEntry(VL, false);
749          return;
750        }
751      }
752    }
753  }
754
755  DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
756
757  unsigned Opcode = getSameOpcode(VL);
758
759  // Check if it is safe to sink the loads or the stores.
760  if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
761    Instruction *Last = getLastInstruction(VL);
762
763    for (unsigned i = 0, e = VL.size(); i < e; ++i) {
764      if (VL[i] == Last)
765        continue;
766      Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
767      if (Barrier) {
768        DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
769              << "\n because of " << *Barrier << ".  Gathering.\n");
770        newTreeEntry(VL, false);
771        return;
772      }
773    }
774  }
775
776  switch (Opcode) {
777    case Instruction::PHI: {
778      PHINode *PH = dyn_cast<PHINode>(VL0);
779
780      // Check for terminator values (e.g. invoke).
781      for (unsigned j = 0; j < VL.size(); ++j)
782        for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
783          TerminatorInst *Term = dyn_cast<TerminatorInst>(cast<PHINode>(VL[j])->getIncomingValue(i));
784          if (Term) {
785            DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
786            newTreeEntry(VL, false);
787            return;
788          }
789        }
790
791      newTreeEntry(VL, true);
792      DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
793
794      for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
795        ValueList Operands;
796        // Prepare the operand vector.
797        for (unsigned j = 0; j < VL.size(); ++j)
798          Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
799
800        buildTree_rec(Operands, Depth + 1);
801      }
802      return;
803    }
804    case Instruction::ExtractElement: {
805      bool Reuse = CanReuseExtract(VL);
806      if (Reuse) {
807        DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
808      }
809      newTreeEntry(VL, Reuse);
810      return;
811    }
812    case Instruction::Load: {
813      // Check if the loads are consecutive or of we need to swizzle them.
814      for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
815        LoadInst *L = cast<LoadInst>(VL[i]);
816        if (!L->isSimple() || !isConsecutiveAccess(VL[i], VL[i + 1])) {
817          newTreeEntry(VL, false);
818          DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
819          return;
820        }
821      }
822      newTreeEntry(VL, true);
823      DEBUG(dbgs() << "SLP: added a vector of loads.\n");
824      return;
825    }
826    case Instruction::ZExt:
827    case Instruction::SExt:
828    case Instruction::FPToUI:
829    case Instruction::FPToSI:
830    case Instruction::FPExt:
831    case Instruction::PtrToInt:
832    case Instruction::IntToPtr:
833    case Instruction::SIToFP:
834    case Instruction::UIToFP:
835    case Instruction::Trunc:
836    case Instruction::FPTrunc:
837    case Instruction::BitCast: {
838      Type *SrcTy = VL0->getOperand(0)->getType();
839      for (unsigned i = 0; i < VL.size(); ++i) {
840        Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
841        if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
842          newTreeEntry(VL, false);
843          DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
844          return;
845        }
846      }
847      newTreeEntry(VL, true);
848      DEBUG(dbgs() << "SLP: added a vector of casts.\n");
849
850      for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
851        ValueList Operands;
852        // Prepare the operand vector.
853        for (unsigned j = 0; j < VL.size(); ++j)
854          Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
855
856        buildTree_rec(Operands, Depth+1);
857      }
858      return;
859    }
860    case Instruction::ICmp:
861    case Instruction::FCmp: {
862      // Check that all of the compares have the same predicate.
863      CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
864      Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
865      for (unsigned i = 1, e = VL.size(); i < e; ++i) {
866        CmpInst *Cmp = cast<CmpInst>(VL[i]);
867        if (Cmp->getPredicate() != P0 ||
868            Cmp->getOperand(0)->getType() != ComparedTy) {
869          newTreeEntry(VL, false);
870          DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
871          return;
872        }
873      }
874
875      newTreeEntry(VL, true);
876      DEBUG(dbgs() << "SLP: added a vector of compares.\n");
877
878      for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
879        ValueList Operands;
880        // Prepare the operand vector.
881        for (unsigned j = 0; j < VL.size(); ++j)
882          Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
883
884        buildTree_rec(Operands, Depth+1);
885      }
886      return;
887    }
888    case Instruction::Select:
889    case Instruction::Add:
890    case Instruction::FAdd:
891    case Instruction::Sub:
892    case Instruction::FSub:
893    case Instruction::Mul:
894    case Instruction::FMul:
895    case Instruction::UDiv:
896    case Instruction::SDiv:
897    case Instruction::FDiv:
898    case Instruction::URem:
899    case Instruction::SRem:
900    case Instruction::FRem:
901    case Instruction::Shl:
902    case Instruction::LShr:
903    case Instruction::AShr:
904    case Instruction::And:
905    case Instruction::Or:
906    case Instruction::Xor: {
907      newTreeEntry(VL, true);
908      DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
909
910      // Sort operands of the instructions so that each side is more likely to
911      // have the same opcode.
912      if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
913        ValueList Left, Right;
914        reorderInputsAccordingToOpcode(VL, Left, Right);
915        buildTree_rec(Left, Depth + 1);
916        buildTree_rec(Right, Depth + 1);
917        return;
918      }
919
920      for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
921        ValueList Operands;
922        // Prepare the operand vector.
923        for (unsigned j = 0; j < VL.size(); ++j)
924          Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
925
926        buildTree_rec(Operands, Depth+1);
927      }
928      return;
929    }
930    case Instruction::Store: {
931      // Check if the stores are consecutive or of we need to swizzle them.
932      for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
933        if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
934          newTreeEntry(VL, false);
935          DEBUG(dbgs() << "SLP: Non consecutive store.\n");
936          return;
937        }
938
939      newTreeEntry(VL, true);
940      DEBUG(dbgs() << "SLP: added a vector of stores.\n");
941
942      ValueList Operands;
943      for (unsigned j = 0; j < VL.size(); ++j)
944        Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
945
946      // We can ignore these values because we are sinking them down.
947      MemBarrierIgnoreList.insert(VL.begin(), VL.end());
948      buildTree_rec(Operands, Depth + 1);
949      return;
950    }
951    default:
952      newTreeEntry(VL, false);
953      DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
954      return;
955  }
956}
957
958int BoUpSLP::getEntryCost(TreeEntry *E) {
959  ArrayRef<Value*> VL = E->Scalars;
960
961  Type *ScalarTy = VL[0]->getType();
962  if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
963    ScalarTy = SI->getValueOperand()->getType();
964  VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
965
966  if (E->NeedToGather) {
967    if (allConstant(VL))
968      return 0;
969    if (isSplat(VL)) {
970      return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
971    }
972    return getGatherCost(E->Scalars);
973  }
974
975  assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
976         "Invalid VL");
977  Instruction *VL0 = cast<Instruction>(VL[0]);
978  unsigned Opcode = VL0->getOpcode();
979  switch (Opcode) {
980    case Instruction::PHI: {
981      return 0;
982    }
983    case Instruction::ExtractElement: {
984      if (CanReuseExtract(VL))
985        return 0;
986      return getGatherCost(VecTy);
987    }
988    case Instruction::ZExt:
989    case Instruction::SExt:
990    case Instruction::FPToUI:
991    case Instruction::FPToSI:
992    case Instruction::FPExt:
993    case Instruction::PtrToInt:
994    case Instruction::IntToPtr:
995    case Instruction::SIToFP:
996    case Instruction::UIToFP:
997    case Instruction::Trunc:
998    case Instruction::FPTrunc:
999    case Instruction::BitCast: {
1000      Type *SrcTy = VL0->getOperand(0)->getType();
1001
1002      // Calculate the cost of this instruction.
1003      int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1004                                                         VL0->getType(), SrcTy);
1005
1006      VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1007      int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1008      return VecCost - ScalarCost;
1009    }
1010    case Instruction::FCmp:
1011    case Instruction::ICmp:
1012    case Instruction::Select:
1013    case Instruction::Add:
1014    case Instruction::FAdd:
1015    case Instruction::Sub:
1016    case Instruction::FSub:
1017    case Instruction::Mul:
1018    case Instruction::FMul:
1019    case Instruction::UDiv:
1020    case Instruction::SDiv:
1021    case Instruction::FDiv:
1022    case Instruction::URem:
1023    case Instruction::SRem:
1024    case Instruction::FRem:
1025    case Instruction::Shl:
1026    case Instruction::LShr:
1027    case Instruction::AShr:
1028    case Instruction::And:
1029    case Instruction::Or:
1030    case Instruction::Xor: {
1031      // Calculate the cost of this instruction.
1032      int ScalarCost = 0;
1033      int VecCost = 0;
1034      if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1035          Opcode == Instruction::Select) {
1036        VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1037        ScalarCost = VecTy->getNumElements() *
1038        TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1039        VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1040      } else {
1041        // Certain instructions can be cheaper to vectorize if they have a
1042        // constant second vector operand.
1043        TargetTransformInfo::OperandValueKind Op1VK =
1044            TargetTransformInfo::OK_AnyValue;
1045        TargetTransformInfo::OperandValueKind Op2VK =
1046            TargetTransformInfo::OK_UniformConstantValue;
1047
1048        // Check whether all second operands are constant.
1049        for (unsigned i = 0; i < VL.size(); ++i)
1050          if (!isa<ConstantInt>(cast<Instruction>(VL[i])->getOperand(1))) {
1051            Op2VK = TargetTransformInfo::OK_AnyValue;
1052            break;
1053          }
1054
1055        ScalarCost =
1056            VecTy->getNumElements() *
1057            TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK);
1058        VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK);
1059      }
1060      return VecCost - ScalarCost;
1061    }
1062    case Instruction::Load: {
1063      // Cost of wide load - cost of scalar loads.
1064      int ScalarLdCost = VecTy->getNumElements() *
1065      TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1066      int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1067      return VecLdCost - ScalarLdCost;
1068    }
1069    case Instruction::Store: {
1070      // We know that we can merge the stores. Calculate the cost.
1071      int ScalarStCost = VecTy->getNumElements() *
1072      TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1073      int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1074      return VecStCost - ScalarStCost;
1075    }
1076    default:
1077      llvm_unreachable("Unknown instruction");
1078  }
1079}
1080
1081bool BoUpSLP::isFullyVectorizableTinyTree() {
1082  DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1083        VectorizableTree.size() << " is fully vectorizable .\n");
1084
1085  // We only handle trees of height 2.
1086  if (VectorizableTree.size() != 2)
1087    return false;
1088
1089  // Gathering cost would be too much for tiny trees.
1090  if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1091    return false;
1092
1093  return true;
1094}
1095
1096int BoUpSLP::getTreeCost() {
1097  int Cost = 0;
1098  DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1099        VectorizableTree.size() << ".\n");
1100
1101  // We only vectorize tiny trees if it is fully vectorizable.
1102  if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1103    if (!VectorizableTree.size()) {
1104      assert(!ExternalUses.size() && "We should not have any external users");
1105    }
1106    return INT_MAX;
1107  }
1108
1109  unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1110
1111  for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1112    int C = getEntryCost(&VectorizableTree[i]);
1113    DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1114          << *VectorizableTree[i].Scalars[0] << " .\n");
1115    Cost += C;
1116  }
1117
1118  int ExtractCost = 0;
1119  for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1120       I != E; ++I) {
1121
1122    VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1123    ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1124                                           I->Lane);
1125  }
1126
1127
1128  DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1129  return  Cost + ExtractCost;
1130}
1131
1132int BoUpSLP::getGatherCost(Type *Ty) {
1133  int Cost = 0;
1134  for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1135    Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1136  return Cost;
1137}
1138
1139int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1140  // Find the type of the operands in VL.
1141  Type *ScalarTy = VL[0]->getType();
1142  if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1143    ScalarTy = SI->getValueOperand()->getType();
1144  VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1145  // Find the cost of inserting/extracting values from the vector.
1146  return getGatherCost(VecTy);
1147}
1148
1149AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
1150  if (StoreInst *SI = dyn_cast<StoreInst>(I))
1151    return AA->getLocation(SI);
1152  if (LoadInst *LI = dyn_cast<LoadInst>(I))
1153    return AA->getLocation(LI);
1154  return AliasAnalysis::Location();
1155}
1156
1157Value *BoUpSLP::getPointerOperand(Value *I) {
1158  if (LoadInst *LI = dyn_cast<LoadInst>(I))
1159    return LI->getPointerOperand();
1160  if (StoreInst *SI = dyn_cast<StoreInst>(I))
1161    return SI->getPointerOperand();
1162  return 0;
1163}
1164
1165unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1166  if (LoadInst *L = dyn_cast<LoadInst>(I))
1167    return L->getPointerAddressSpace();
1168  if (StoreInst *S = dyn_cast<StoreInst>(I))
1169    return S->getPointerAddressSpace();
1170  return -1;
1171}
1172
1173bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1174  Value *PtrA = getPointerOperand(A);
1175  Value *PtrB = getPointerOperand(B);
1176  unsigned ASA = getAddressSpaceOperand(A);
1177  unsigned ASB = getAddressSpaceOperand(B);
1178
1179  // Check that the address spaces match and that the pointers are valid.
1180  if (!PtrA || !PtrB || (ASA != ASB))
1181    return false;
1182
1183  // Make sure that A and B are different pointers of the same type.
1184  if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1185    return false;
1186
1187  unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1188  Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1189  APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1190
1191  APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1192  PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1193  PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1194
1195  APInt OffsetDelta = OffsetB - OffsetA;
1196
1197  // Check if they are based on the same pointer. That makes the offsets
1198  // sufficient.
1199  if (PtrA == PtrB)
1200    return OffsetDelta == Size;
1201
1202  // Compute the necessary base pointer delta to have the necessary final delta
1203  // equal to the size.
1204  APInt BaseDelta = Size - OffsetDelta;
1205
1206  // Otherwise compute the distance with SCEV between the base pointers.
1207  const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1208  const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1209  const SCEV *C = SE->getConstant(BaseDelta);
1210  const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1211  return X == PtrSCEVB;
1212}
1213
1214Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
1215  assert(Src->getParent() == Dst->getParent() && "Not the same BB");
1216  BasicBlock::iterator I = Src, E = Dst;
1217  /// Scan all of the instruction from SRC to DST and check if
1218  /// the source may alias.
1219  for (++I; I != E; ++I) {
1220    // Ignore store instructions that are marked as 'ignore'.
1221    if (MemBarrierIgnoreList.count(I))
1222      continue;
1223    if (Src->mayWriteToMemory()) /* Write */ {
1224      if (!I->mayReadOrWriteMemory())
1225        continue;
1226    } else /* Read */ {
1227      if (!I->mayWriteToMemory())
1228        continue;
1229    }
1230    AliasAnalysis::Location A = getLocation(&*I);
1231    AliasAnalysis::Location B = getLocation(Src);
1232
1233    if (!A.Ptr || !B.Ptr || AA->alias(A, B))
1234      return I;
1235  }
1236  return 0;
1237}
1238
1239int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
1240  BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1241  assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1242  BlockNumbering &BN = BlocksNumbers[BB];
1243
1244  int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
1245  for (unsigned i = 0, e = VL.size(); i < e; ++i)
1246    MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1247  return MaxIdx;
1248}
1249
1250Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
1251  BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
1252  assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
1253  BlockNumbering &BN = BlocksNumbers[BB];
1254
1255  int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
1256  for (unsigned i = 1, e = VL.size(); i < e; ++i)
1257    MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
1258  Instruction *I = BN.getInstruction(MaxIdx);
1259  assert(I && "bad location");
1260  return I;
1261}
1262
1263void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1264  Instruction *VL0 = cast<Instruction>(VL[0]);
1265  Instruction *LastInst = getLastInstruction(VL);
1266  BasicBlock::iterator NextInst = LastInst;
1267  ++NextInst;
1268  Builder.SetInsertPoint(VL0->getParent(), NextInst);
1269  Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
1270}
1271
1272Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1273  Value *Vec = UndefValue::get(Ty);
1274  // Generate the 'InsertElement' instruction.
1275  for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1276    Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1277    if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
1278      GatherSeq.insert(Insrt);
1279      CSEBlocks.insert(Insrt->getParent());
1280
1281      // Add to our 'need-to-extract' list.
1282      if (ScalarToTreeEntry.count(VL[i])) {
1283        int Idx = ScalarToTreeEntry[VL[i]];
1284        TreeEntry *E = &VectorizableTree[Idx];
1285        // Find which lane we need to extract.
1286        int FoundLane = -1;
1287        for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
1288          // Is this the lane of the scalar that we are looking for ?
1289          if (E->Scalars[Lane] == VL[i]) {
1290            FoundLane = Lane;
1291            break;
1292          }
1293        }
1294        assert(FoundLane >= 0 && "Could not find the correct lane");
1295        ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
1296      }
1297    }
1298  }
1299
1300  return Vec;
1301}
1302
1303Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
1304  SmallDenseMap<Value*, int>::const_iterator Entry
1305    = ScalarToTreeEntry.find(VL[0]);
1306  if (Entry != ScalarToTreeEntry.end()) {
1307    int Idx = Entry->second;
1308    const TreeEntry *En = &VectorizableTree[Idx];
1309    if (En->isSame(VL) && En->VectorizedValue)
1310      return En->VectorizedValue;
1311  }
1312  return 0;
1313}
1314
1315Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1316  if (ScalarToTreeEntry.count(VL[0])) {
1317    int Idx = ScalarToTreeEntry[VL[0]];
1318    TreeEntry *E = &VectorizableTree[Idx];
1319    if (E->isSame(VL))
1320      return vectorizeTree(E);
1321  }
1322
1323  Type *ScalarTy = VL[0]->getType();
1324  if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1325    ScalarTy = SI->getValueOperand()->getType();
1326  VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1327
1328  return Gather(VL, VecTy);
1329}
1330
1331Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1332  IRBuilder<>::InsertPointGuard Guard(Builder);
1333
1334  if (E->VectorizedValue) {
1335    DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1336    return E->VectorizedValue;
1337  }
1338
1339  Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1340  Type *ScalarTy = VL0->getType();
1341  if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
1342    ScalarTy = SI->getValueOperand()->getType();
1343  VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1344
1345  if (E->NeedToGather) {
1346    setInsertPointAfterBundle(E->Scalars);
1347    return Gather(E->Scalars, VecTy);
1348  }
1349
1350  unsigned Opcode = VL0->getOpcode();
1351  assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1352
1353  switch (Opcode) {
1354    case Instruction::PHI: {
1355      PHINode *PH = dyn_cast<PHINode>(VL0);
1356      Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
1357      Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1358      PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1359      E->VectorizedValue = NewPhi;
1360
1361      // PHINodes may have multiple entries from the same block. We want to
1362      // visit every block once.
1363      SmallSet<BasicBlock*, 4> VisitedBBs;
1364
1365      for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1366        ValueList Operands;
1367        BasicBlock *IBB = PH->getIncomingBlock(i);
1368
1369        if (!VisitedBBs.insert(IBB)) {
1370          NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
1371          continue;
1372        }
1373
1374        // Prepare the operand vector.
1375        for (unsigned j = 0; j < E->Scalars.size(); ++j)
1376          Operands.push_back(cast<PHINode>(E->Scalars[j])->
1377                             getIncomingValueForBlock(IBB));
1378
1379        Builder.SetInsertPoint(IBB->getTerminator());
1380        Builder.SetCurrentDebugLocation(PH->getDebugLoc());
1381        Value *Vec = vectorizeTree(Operands);
1382        NewPhi->addIncoming(Vec, IBB);
1383      }
1384
1385      assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1386             "Invalid number of incoming values");
1387      return NewPhi;
1388    }
1389
1390    case Instruction::ExtractElement: {
1391      if (CanReuseExtract(E->Scalars)) {
1392        Value *V = VL0->getOperand(0);
1393        E->VectorizedValue = V;
1394        return V;
1395      }
1396      return Gather(E->Scalars, VecTy);
1397    }
1398    case Instruction::ZExt:
1399    case Instruction::SExt:
1400    case Instruction::FPToUI:
1401    case Instruction::FPToSI:
1402    case Instruction::FPExt:
1403    case Instruction::PtrToInt:
1404    case Instruction::IntToPtr:
1405    case Instruction::SIToFP:
1406    case Instruction::UIToFP:
1407    case Instruction::Trunc:
1408    case Instruction::FPTrunc:
1409    case Instruction::BitCast: {
1410      ValueList INVL;
1411      for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1412        INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1413
1414      setInsertPointAfterBundle(E->Scalars);
1415
1416      Value *InVec = vectorizeTree(INVL);
1417
1418      if (Value *V = alreadyVectorized(E->Scalars))
1419        return V;
1420
1421      CastInst *CI = dyn_cast<CastInst>(VL0);
1422      Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1423      E->VectorizedValue = V;
1424      return V;
1425    }
1426    case Instruction::FCmp:
1427    case Instruction::ICmp: {
1428      ValueList LHSV, RHSV;
1429      for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1430        LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1431        RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1432      }
1433
1434      setInsertPointAfterBundle(E->Scalars);
1435
1436      Value *L = vectorizeTree(LHSV);
1437      Value *R = vectorizeTree(RHSV);
1438
1439      if (Value *V = alreadyVectorized(E->Scalars))
1440        return V;
1441
1442      CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1443      Value *V;
1444      if (Opcode == Instruction::FCmp)
1445        V = Builder.CreateFCmp(P0, L, R);
1446      else
1447        V = Builder.CreateICmp(P0, L, R);
1448
1449      E->VectorizedValue = V;
1450      return V;
1451    }
1452    case Instruction::Select: {
1453      ValueList TrueVec, FalseVec, CondVec;
1454      for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1455        CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1456        TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1457        FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1458      }
1459
1460      setInsertPointAfterBundle(E->Scalars);
1461
1462      Value *Cond = vectorizeTree(CondVec);
1463      Value *True = vectorizeTree(TrueVec);
1464      Value *False = vectorizeTree(FalseVec);
1465
1466      if (Value *V = alreadyVectorized(E->Scalars))
1467        return V;
1468
1469      Value *V = Builder.CreateSelect(Cond, True, False);
1470      E->VectorizedValue = V;
1471      return V;
1472    }
1473    case Instruction::Add:
1474    case Instruction::FAdd:
1475    case Instruction::Sub:
1476    case Instruction::FSub:
1477    case Instruction::Mul:
1478    case Instruction::FMul:
1479    case Instruction::UDiv:
1480    case Instruction::SDiv:
1481    case Instruction::FDiv:
1482    case Instruction::URem:
1483    case Instruction::SRem:
1484    case Instruction::FRem:
1485    case Instruction::Shl:
1486    case Instruction::LShr:
1487    case Instruction::AShr:
1488    case Instruction::And:
1489    case Instruction::Or:
1490    case Instruction::Xor: {
1491      ValueList LHSVL, RHSVL;
1492      if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
1493        reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
1494      else
1495        for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1496          LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1497          RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1498        }
1499
1500      setInsertPointAfterBundle(E->Scalars);
1501
1502      Value *LHS = vectorizeTree(LHSVL);
1503      Value *RHS = vectorizeTree(RHSVL);
1504
1505      if (LHS == RHS && isa<Instruction>(LHS)) {
1506        assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1507      }
1508
1509      if (Value *V = alreadyVectorized(E->Scalars))
1510        return V;
1511
1512      BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1513      Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1514      E->VectorizedValue = V;
1515
1516      if (Instruction *I = dyn_cast<Instruction>(V))
1517        return propagateMetadata(I, E->Scalars);
1518
1519      return V;
1520    }
1521    case Instruction::Load: {
1522      // Loads are inserted at the head of the tree because we don't want to
1523      // sink them all the way down past store instructions.
1524      setInsertPointAfterBundle(E->Scalars);
1525
1526      LoadInst *LI = cast<LoadInst>(VL0);
1527      unsigned AS = LI->getPointerAddressSpace();
1528
1529      Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
1530                                            VecTy->getPointerTo(AS));
1531      unsigned Alignment = LI->getAlignment();
1532      LI = Builder.CreateLoad(VecPtr);
1533      LI->setAlignment(Alignment);
1534      E->VectorizedValue = LI;
1535      return propagateMetadata(LI, E->Scalars);
1536    }
1537    case Instruction::Store: {
1538      StoreInst *SI = cast<StoreInst>(VL0);
1539      unsigned Alignment = SI->getAlignment();
1540      unsigned AS = SI->getPointerAddressSpace();
1541
1542      ValueList ValueOp;
1543      for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1544        ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1545
1546      setInsertPointAfterBundle(E->Scalars);
1547
1548      Value *VecValue = vectorizeTree(ValueOp);
1549      Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
1550                                            VecTy->getPointerTo(AS));
1551      StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1552      S->setAlignment(Alignment);
1553      E->VectorizedValue = S;
1554      return propagateMetadata(S, E->Scalars);
1555    }
1556    default:
1557    llvm_unreachable("unknown inst");
1558  }
1559  return 0;
1560}
1561
1562Value *BoUpSLP::vectorizeTree() {
1563  Builder.SetInsertPoint(F->getEntryBlock().begin());
1564  vectorizeTree(&VectorizableTree[0]);
1565
1566  DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
1567
1568  // Extract all of the elements with the external uses.
1569  for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
1570       it != e; ++it) {
1571    Value *Scalar = it->Scalar;
1572    llvm::User *User = it->User;
1573
1574    // Skip users that we already RAUW. This happens when one instruction
1575    // has multiple uses of the same value.
1576    if (std::find(Scalar->use_begin(), Scalar->use_end(), User) ==
1577        Scalar->use_end())
1578      continue;
1579    assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
1580
1581    int Idx = ScalarToTreeEntry[Scalar];
1582    TreeEntry *E = &VectorizableTree[Idx];
1583    assert(!E->NeedToGather && "Extracting from a gather list");
1584
1585    Value *Vec = E->VectorizedValue;
1586    assert(Vec && "Can't find vectorizable value");
1587
1588    Value *Lane = Builder.getInt32(it->Lane);
1589    // Generate extracts for out-of-tree users.
1590    // Find the insertion point for the extractelement lane.
1591    if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1592      Builder.SetInsertPoint(PN->getParent()->getFirstInsertionPt());
1593      Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1594      CSEBlocks.insert(PN->getParent());
1595      User->replaceUsesOfWith(Scalar, Ex);
1596    } else if (isa<Instruction>(Vec)){
1597      if (PHINode *PH = dyn_cast<PHINode>(User)) {
1598        for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
1599          if (PH->getIncomingValue(i) == Scalar) {
1600            Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
1601            Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1602            CSEBlocks.insert(PH->getIncomingBlock(i));
1603            PH->setOperand(i, Ex);
1604          }
1605        }
1606      } else {
1607        Builder.SetInsertPoint(cast<Instruction>(User));
1608        Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1609        CSEBlocks.insert(cast<Instruction>(User)->getParent());
1610        User->replaceUsesOfWith(Scalar, Ex);
1611     }
1612    } else {
1613      Builder.SetInsertPoint(F->getEntryBlock().begin());
1614      Value *Ex = Builder.CreateExtractElement(Vec, Lane);
1615      CSEBlocks.insert(&F->getEntryBlock());
1616      User->replaceUsesOfWith(Scalar, Ex);
1617    }
1618
1619    DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
1620  }
1621
1622  // For each vectorized value:
1623  for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1624    TreeEntry *Entry = &VectorizableTree[EIdx];
1625
1626    // For each lane:
1627    for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1628      Value *Scalar = Entry->Scalars[Lane];
1629
1630      // No need to handle users of gathered values.
1631      if (Entry->NeedToGather)
1632        continue;
1633
1634      assert(Entry->VectorizedValue && "Can't find vectorizable value");
1635
1636      Type *Ty = Scalar->getType();
1637      if (!Ty->isVoidTy()) {
1638        for (Value::use_iterator User = Scalar->use_begin(),
1639             UE = Scalar->use_end(); User != UE; ++User) {
1640          DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1641          assert(!MustGather.count(*User) &&
1642                 "Replacing gathered value with undef");
1643
1644          assert((ScalarToTreeEntry.count(*User) ||
1645                  // It is legal to replace the reduction users by undef.
1646                  (RdxOps && RdxOps->count(*User))) &&
1647                 "Replacing out-of-tree value with undef");
1648        }
1649        Value *Undef = UndefValue::get(Ty);
1650        Scalar->replaceAllUsesWith(Undef);
1651      }
1652      DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1653      cast<Instruction>(Scalar)->eraseFromParent();
1654    }
1655  }
1656
1657  for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1658    BlocksNumbers[it].forget();
1659  }
1660  Builder.ClearInsertionPoint();
1661
1662  return VectorizableTree[0].VectorizedValue;
1663}
1664
1665class DTCmp {
1666  const DominatorTree *DT;
1667
1668public:
1669  DTCmp(const DominatorTree *DT) : DT(DT) {}
1670  bool operator()(const BasicBlock *A, const BasicBlock *B) const {
1671    return DT->properlyDominates(A, B);
1672  }
1673};
1674
1675void BoUpSLP::optimizeGatherSequence() {
1676  DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1677        << " gather sequences instructions.\n");
1678  // LICM InsertElementInst sequences.
1679  for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1680       e = GatherSeq.end(); it != e; ++it) {
1681    InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1682
1683    if (!Insert)
1684      continue;
1685
1686    // Check if this block is inside a loop.
1687    Loop *L = LI->getLoopFor(Insert->getParent());
1688    if (!L)
1689      continue;
1690
1691    // Check if it has a preheader.
1692    BasicBlock *PreHeader = L->getLoopPreheader();
1693    if (!PreHeader)
1694      continue;
1695
1696    // If the vector or the element that we insert into it are
1697    // instructions that are defined in this basic block then we can't
1698    // hoist this instruction.
1699    Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1700    Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1701    if (CurrVec && L->contains(CurrVec))
1702      continue;
1703    if (NewElem && L->contains(NewElem))
1704      continue;
1705
1706    // We can hoist this instruction. Move it to the pre-header.
1707    Insert->moveBefore(PreHeader->getTerminator());
1708  }
1709
1710  // Sort blocks by domination. This ensures we visit a block after all blocks
1711  // dominating it are visited.
1712  SmallVector<BasicBlock *, 8> CSEWorkList(CSEBlocks.begin(), CSEBlocks.end());
1713  std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(), DTCmp(DT));
1714
1715  // Perform O(N^2) search over the gather sequences and merge identical
1716  // instructions. TODO: We can further optimize this scan if we split the
1717  // instructions into different buckets based on the insert lane.
1718  SmallVector<Instruction *, 16> Visited;
1719  for (SmallVectorImpl<BasicBlock *>::iterator I = CSEWorkList.begin(),
1720                                               E = CSEWorkList.end();
1721       I != E; ++I) {
1722    assert((I == CSEWorkList.begin() || !DT->dominates(*I, *llvm::prior(I))) &&
1723           "Worklist not sorted properly!");
1724    BasicBlock *BB = *I;
1725    // For all instructions in blocks containing gather sequences:
1726    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
1727      Instruction *In = it++;
1728      if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
1729        continue;
1730
1731      // Check if we can replace this instruction with any of the
1732      // visited instructions.
1733      for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
1734                                                    ve = Visited.end();
1735           v != ve; ++v) {
1736        if (In->isIdenticalTo(*v) &&
1737            DT->dominates((*v)->getParent(), In->getParent())) {
1738          In->replaceAllUsesWith(*v);
1739          In->eraseFromParent();
1740          In = 0;
1741          break;
1742        }
1743      }
1744      if (In) {
1745        assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
1746        Visited.push_back(In);
1747      }
1748    }
1749  }
1750  CSEBlocks.clear();
1751  GatherSeq.clear();
1752}
1753
1754/// The SLPVectorizer Pass.
1755struct SLPVectorizer : public FunctionPass {
1756  typedef SmallVector<StoreInst *, 8> StoreList;
1757  typedef MapVector<Value *, StoreList> StoreListMap;
1758
1759  /// Pass identification, replacement for typeid
1760  static char ID;
1761
1762  explicit SLPVectorizer() : FunctionPass(ID) {
1763    initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1764  }
1765
1766  ScalarEvolution *SE;
1767  DataLayout *DL;
1768  TargetTransformInfo *TTI;
1769  AliasAnalysis *AA;
1770  LoopInfo *LI;
1771  DominatorTree *DT;
1772
1773  virtual bool runOnFunction(Function &F) {
1774    SE = &getAnalysis<ScalarEvolution>();
1775    DL = getAnalysisIfAvailable<DataLayout>();
1776    TTI = &getAnalysis<TargetTransformInfo>();
1777    AA = &getAnalysis<AliasAnalysis>();
1778    LI = &getAnalysis<LoopInfo>();
1779    DT = &getAnalysis<DominatorTree>();
1780
1781    StoreRefs.clear();
1782    bool Changed = false;
1783
1784    // If the target claims to have no vector registers don't attempt
1785    // vectorization.
1786    if (!TTI->getNumberOfRegisters(true))
1787      return false;
1788
1789    // Must have DataLayout. We can't require it because some tests run w/o
1790    // triple.
1791    if (!DL)
1792      return false;
1793
1794    // Don't vectorize when the attribute NoImplicitFloat is used.
1795    if (F.hasFnAttribute(Attribute::NoImplicitFloat))
1796      return false;
1797
1798    DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1799
1800    // Use the bollom up slp vectorizer to construct chains that start with
1801    // he store instructions.
1802    BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1803
1804    // Scan the blocks in the function in post order.
1805    for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1806         e = po_end(&F.getEntryBlock()); it != e; ++it) {
1807      BasicBlock *BB = *it;
1808
1809      // Vectorize trees that end at stores.
1810      if (unsigned count = collectStores(BB, R)) {
1811        (void)count;
1812        DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1813        Changed |= vectorizeStoreChains(R);
1814      }
1815
1816      // Vectorize trees that end at reductions.
1817      Changed |= vectorizeChainsInBlock(BB, R);
1818    }
1819
1820    if (Changed) {
1821      R.optimizeGatherSequence();
1822      DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1823      DEBUG(verifyFunction(F));
1824    }
1825    return Changed;
1826  }
1827
1828  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1829    FunctionPass::getAnalysisUsage(AU);
1830    AU.addRequired<ScalarEvolution>();
1831    AU.addRequired<AliasAnalysis>();
1832    AU.addRequired<TargetTransformInfo>();
1833    AU.addRequired<LoopInfo>();
1834    AU.addRequired<DominatorTree>();
1835    AU.addPreserved<LoopInfo>();
1836    AU.addPreserved<DominatorTree>();
1837    AU.setPreservesCFG();
1838  }
1839
1840private:
1841
1842  /// \brief Collect memory references and sort them according to their base
1843  /// object. We sort the stores to their base objects to reduce the cost of the
1844  /// quadratic search on the stores. TODO: We can further reduce this cost
1845  /// if we flush the chain creation every time we run into a memory barrier.
1846  unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1847
1848  /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1849  bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1850
1851  /// \brief Try to vectorize a list of operands.
1852  /// \returns true if a value was vectorized.
1853  bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R);
1854
1855  /// \brief Try to vectorize a chain that may start at the operands of \V;
1856  bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1857
1858  /// \brief Vectorize the stores that were collected in StoreRefs.
1859  bool vectorizeStoreChains(BoUpSLP &R);
1860
1861  /// \brief Scan the basic block and look for patterns that are likely to start
1862  /// a vectorization chain.
1863  bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1864
1865  bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1866                           BoUpSLP &R);
1867
1868  bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1869                       BoUpSLP &R);
1870private:
1871  StoreListMap StoreRefs;
1872};
1873
1874/// \brief Check that the Values in the slice in VL array are still existant in
1875/// the WeakVH array.
1876/// Vectorization of part of the VL array may cause later values in the VL array
1877/// to become invalid. We track when this has happened in the WeakVH array.
1878static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
1879                               SmallVectorImpl<WeakVH> &VH,
1880                               unsigned SliceBegin,
1881                               unsigned SliceSize) {
1882  for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
1883    if (VH[i] != VL[i])
1884      return true;
1885
1886  return false;
1887}
1888
1889bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1890                                          int CostThreshold, BoUpSLP &R) {
1891  unsigned ChainLen = Chain.size();
1892  DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1893        << "\n");
1894  Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1895  unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1896  unsigned VF = MinVecRegSize / Sz;
1897
1898  if (!isPowerOf2_32(Sz) || VF < 2)
1899    return false;
1900
1901  // Keep track of values that were delete by vectorizing in the loop below.
1902  SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
1903
1904  bool Changed = false;
1905  // Look for profitable vectorizable trees at all offsets, starting at zero.
1906  for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1907    if (i + VF > e)
1908      break;
1909
1910    // Check that a previous iteration of this loop did not delete the Value.
1911    if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
1912      continue;
1913
1914    DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1915          << "\n");
1916    ArrayRef<Value *> Operands = Chain.slice(i, VF);
1917
1918    R.buildTree(Operands);
1919
1920    int Cost = R.getTreeCost();
1921
1922    DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1923    if (Cost < CostThreshold) {
1924      DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1925      R.vectorizeTree();
1926
1927      // Move to the next bundle.
1928      i += VF - 1;
1929      Changed = true;
1930    }
1931  }
1932
1933  return Changed;
1934}
1935
1936bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1937                                    int costThreshold, BoUpSLP &R) {
1938  SetVector<Value *> Heads, Tails;
1939  SmallDenseMap<Value *, Value *> ConsecutiveChain;
1940
1941  // We may run into multiple chains that merge into a single chain. We mark the
1942  // stores that we vectorized so that we don't visit the same store twice.
1943  BoUpSLP::ValueSet VectorizedStores;
1944  bool Changed = false;
1945
1946  // Do a quadratic search on all of the given stores and find
1947  // all of the pairs of stores that follow each other.
1948  for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
1949    for (unsigned j = 0; j < e; ++j) {
1950      if (i == j)
1951        continue;
1952
1953      if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1954        Tails.insert(Stores[j]);
1955        Heads.insert(Stores[i]);
1956        ConsecutiveChain[Stores[i]] = Stores[j];
1957      }
1958    }
1959  }
1960
1961  // For stores that start but don't end a link in the chain:
1962  for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1963       it != e; ++it) {
1964    if (Tails.count(*it))
1965      continue;
1966
1967    // We found a store instr that starts a chain. Now follow the chain and try
1968    // to vectorize it.
1969    BoUpSLP::ValueList Operands;
1970    Value *I = *it;
1971    // Collect the chain into a list.
1972    while (Tails.count(I) || Heads.count(I)) {
1973      if (VectorizedStores.count(I))
1974        break;
1975      Operands.push_back(I);
1976      // Move to the next value in the chain.
1977      I = ConsecutiveChain[I];
1978    }
1979
1980    bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1981
1982    // Mark the vectorized stores so that we don't vectorize them again.
1983    if (Vectorized)
1984      VectorizedStores.insert(Operands.begin(), Operands.end());
1985    Changed |= Vectorized;
1986  }
1987
1988  return Changed;
1989}
1990
1991
1992unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1993  unsigned count = 0;
1994  StoreRefs.clear();
1995  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1996    StoreInst *SI = dyn_cast<StoreInst>(it);
1997    if (!SI)
1998      continue;
1999
2000    // Don't touch volatile stores.
2001    if (!SI->isSimple())
2002      continue;
2003
2004    // Check that the pointer points to scalars.
2005    Type *Ty = SI->getValueOperand()->getType();
2006    if (Ty->isAggregateType() || Ty->isVectorTy())
2007      return 0;
2008
2009    // Find the base pointer.
2010    Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
2011
2012    // Save the store locations.
2013    StoreRefs[Ptr].push_back(SI);
2014    count++;
2015  }
2016  return count;
2017}
2018
2019bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
2020  if (!A || !B)
2021    return false;
2022  Value *VL[] = { A, B };
2023  return tryToVectorizeList(VL, R);
2024}
2025
2026bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) {
2027  if (VL.size() < 2)
2028    return false;
2029
2030  DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
2031
2032  // Check that all of the parts are scalar instructions of the same type.
2033  Instruction *I0 = dyn_cast<Instruction>(VL[0]);
2034  if (!I0)
2035    return false;
2036
2037  unsigned Opcode0 = I0->getOpcode();
2038
2039  Type *Ty0 = I0->getType();
2040  unsigned Sz = DL->getTypeSizeInBits(Ty0);
2041  unsigned VF = MinVecRegSize / Sz;
2042
2043  for (int i = 0, e = VL.size(); i < e; ++i) {
2044    Type *Ty = VL[i]->getType();
2045    if (Ty->isAggregateType() || Ty->isVectorTy())
2046      return false;
2047    Instruction *Inst = dyn_cast<Instruction>(VL[i]);
2048    if (!Inst || Inst->getOpcode() != Opcode0)
2049      return false;
2050  }
2051
2052  bool Changed = false;
2053
2054  // Keep track of values that were delete by vectorizing in the loop below.
2055  SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
2056
2057  for (unsigned i = 0, e = VL.size(); i < e; ++i) {
2058    unsigned OpsWidth = 0;
2059
2060    if (i + VF > e)
2061      OpsWidth = e - i;
2062    else
2063      OpsWidth = VF;
2064
2065    if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
2066      break;
2067
2068    // Check that a previous iteration of this loop did not delete the Value.
2069    if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
2070      continue;
2071
2072    DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
2073                 << "\n");
2074    ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
2075
2076    R.buildTree(Ops);
2077    int Cost = R.getTreeCost();
2078
2079    if (Cost < -SLPCostThreshold) {
2080      DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n");
2081      R.vectorizeTree();
2082
2083      // Move to the next bundle.
2084      i += VF - 1;
2085      Changed = true;
2086    }
2087  }
2088
2089  return Changed;
2090}
2091
2092bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
2093  if (!V)
2094    return false;
2095
2096  // Try to vectorize V.
2097  if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
2098    return true;
2099
2100  BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
2101  BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
2102  // Try to skip B.
2103  if (B && B->hasOneUse()) {
2104    BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
2105    BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
2106    if (tryToVectorizePair(A, B0, R)) {
2107      B->moveBefore(V);
2108      return true;
2109    }
2110    if (tryToVectorizePair(A, B1, R)) {
2111      B->moveBefore(V);
2112      return true;
2113    }
2114  }
2115
2116  // Try to skip A.
2117  if (A && A->hasOneUse()) {
2118    BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
2119    BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
2120    if (tryToVectorizePair(A0, B, R)) {
2121      A->moveBefore(V);
2122      return true;
2123    }
2124    if (tryToVectorizePair(A1, B, R)) {
2125      A->moveBefore(V);
2126      return true;
2127    }
2128  }
2129  return 0;
2130}
2131
2132/// \brief Generate a shuffle mask to be used in a reduction tree.
2133///
2134/// \param VecLen The length of the vector to be reduced.
2135/// \param NumEltsToRdx The number of elements that should be reduced in the
2136///        vector.
2137/// \param IsPairwise Whether the reduction is a pairwise or splitting
2138///        reduction. A pairwise reduction will generate a mask of
2139///        <0,2,...> or <1,3,..> while a splitting reduction will generate
2140///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
2141/// \param IsLeft True will generate a mask of even elements, odd otherwise.
2142static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
2143                                   bool IsPairwise, bool IsLeft,
2144                                   IRBuilder<> &Builder) {
2145  assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
2146
2147  SmallVector<Constant *, 32> ShuffleMask(
2148      VecLen, UndefValue::get(Builder.getInt32Ty()));
2149
2150  if (IsPairwise)
2151    // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
2152    for (unsigned i = 0; i != NumEltsToRdx; ++i)
2153      ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
2154  else
2155    // Move the upper half of the vector to the lower half.
2156    for (unsigned i = 0; i != NumEltsToRdx; ++i)
2157      ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
2158
2159  return ConstantVector::get(ShuffleMask);
2160}
2161
2162
2163/// Model horizontal reductions.
2164///
2165/// A horizontal reduction is a tree of reduction operations (currently add and
2166/// fadd) that has operations that can be put into a vector as its leaf.
2167/// For example, this tree:
2168///
2169/// mul mul mul mul
2170///  \  /    \  /
2171///   +       +
2172///    \     /
2173///       +
2174/// This tree has "mul" as its reduced values and "+" as its reduction
2175/// operations. A reduction might be feeding into a store or a binary operation
2176/// feeding a phi.
2177///    ...
2178///    \  /
2179///     +
2180///     |
2181///  phi +=
2182///
2183///  Or:
2184///    ...
2185///    \  /
2186///     +
2187///     |
2188///   *p =
2189///
2190class HorizontalReduction {
2191  SmallPtrSet<Value *, 16> ReductionOps;
2192  SmallVector<Value *, 32> ReducedVals;
2193
2194  BinaryOperator *ReductionRoot;
2195  PHINode *ReductionPHI;
2196
2197  /// The opcode of the reduction.
2198  unsigned ReductionOpcode;
2199  /// The opcode of the values we perform a reduction on.
2200  unsigned ReducedValueOpcode;
2201  /// The width of one full horizontal reduction operation.
2202  unsigned ReduxWidth;
2203  /// Should we model this reduction as a pairwise reduction tree or a tree that
2204  /// splits the vector in halves and adds those halves.
2205  bool IsPairwiseReduction;
2206
2207public:
2208  HorizontalReduction()
2209    : ReductionRoot(0), ReductionPHI(0), ReductionOpcode(0),
2210    ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
2211
2212  /// \brief Try to find a reduction tree.
2213  bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
2214                                 DataLayout *DL) {
2215    assert((!Phi ||
2216            std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
2217           "Thi phi needs to use the binary operator");
2218
2219    // We could have a initial reductions that is not an add.
2220    //  r *= v1 + v2 + v3 + v4
2221    // In such a case start looking for a tree rooted in the first '+'.
2222    if (Phi) {
2223      if (B->getOperand(0) == Phi) {
2224        Phi = 0;
2225        B = dyn_cast<BinaryOperator>(B->getOperand(1));
2226      } else if (B->getOperand(1) == Phi) {
2227        Phi = 0;
2228        B = dyn_cast<BinaryOperator>(B->getOperand(0));
2229      }
2230    }
2231
2232    if (!B)
2233      return false;
2234
2235    Type *Ty = B->getType();
2236    if (Ty->isVectorTy())
2237      return false;
2238
2239    ReductionOpcode = B->getOpcode();
2240    ReducedValueOpcode = 0;
2241    ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
2242    ReductionRoot = B;
2243    ReductionPHI = Phi;
2244
2245    if (ReduxWidth < 4)
2246      return false;
2247
2248    // We currently only support adds.
2249    if (ReductionOpcode != Instruction::Add &&
2250        ReductionOpcode != Instruction::FAdd)
2251      return false;
2252
2253    // Post order traverse the reduction tree starting at B. We only handle true
2254    // trees containing only binary operators.
2255    SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
2256    Stack.push_back(std::make_pair(B, 0));
2257    while (!Stack.empty()) {
2258      BinaryOperator *TreeN = Stack.back().first;
2259      unsigned EdgeToVist = Stack.back().second++;
2260      bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
2261
2262      // Only handle trees in the current basic block.
2263      if (TreeN->getParent() != B->getParent())
2264        return false;
2265
2266      // Each tree node needs to have one user except for the ultimate
2267      // reduction.
2268      if (!TreeN->hasOneUse() && TreeN != B)
2269        return false;
2270
2271      // Postorder vist.
2272      if (EdgeToVist == 2 || IsReducedValue) {
2273        if (IsReducedValue) {
2274          // Make sure that the opcodes of the operations that we are going to
2275          // reduce match.
2276          if (!ReducedValueOpcode)
2277            ReducedValueOpcode = TreeN->getOpcode();
2278          else if (ReducedValueOpcode != TreeN->getOpcode())
2279            return false;
2280          ReducedVals.push_back(TreeN);
2281        } else {
2282          // We need to be able to reassociate the adds.
2283          if (!TreeN->isAssociative())
2284            return false;
2285          ReductionOps.insert(TreeN);
2286        }
2287        // Retract.
2288        Stack.pop_back();
2289        continue;
2290      }
2291
2292      // Visit left or right.
2293      Value *NextV = TreeN->getOperand(EdgeToVist);
2294      BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
2295      if (Next)
2296        Stack.push_back(std::make_pair(Next, 0));
2297      else if (NextV != Phi)
2298        return false;
2299    }
2300    return true;
2301  }
2302
2303  /// \brief Attempt to vectorize the tree found by
2304  /// matchAssociativeReduction.
2305  bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
2306    if (ReducedVals.empty())
2307      return false;
2308
2309    unsigned NumReducedVals = ReducedVals.size();
2310    if (NumReducedVals < ReduxWidth)
2311      return false;
2312
2313    Value *VectorizedTree = 0;
2314    IRBuilder<> Builder(ReductionRoot);
2315    FastMathFlags Unsafe;
2316    Unsafe.setUnsafeAlgebra();
2317    Builder.SetFastMathFlags(Unsafe);
2318    unsigned i = 0;
2319
2320    for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
2321      ArrayRef<Value *> ValsToReduce(&ReducedVals[i], ReduxWidth);
2322      V.buildTree(ValsToReduce, &ReductionOps);
2323
2324      // Estimate cost.
2325      int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
2326      if (Cost >= -SLPCostThreshold)
2327        break;
2328
2329      DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
2330                   << ". (HorRdx)\n");
2331
2332      // Vectorize a tree.
2333      DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
2334      Value *VectorizedRoot = V.vectorizeTree();
2335
2336      // Emit a reduction.
2337      Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
2338      if (VectorizedTree) {
2339        Builder.SetCurrentDebugLocation(Loc);
2340        VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2341                                     ReducedSubTree, "bin.rdx");
2342      } else
2343        VectorizedTree = ReducedSubTree;
2344    }
2345
2346    if (VectorizedTree) {
2347      // Finish the reduction.
2348      for (; i < NumReducedVals; ++i) {
2349        Builder.SetCurrentDebugLocation(
2350          cast<Instruction>(ReducedVals[i])->getDebugLoc());
2351        VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
2352                                     ReducedVals[i]);
2353      }
2354      // Update users.
2355      if (ReductionPHI) {
2356        assert(ReductionRoot != NULL && "Need a reduction operation");
2357        ReductionRoot->setOperand(0, VectorizedTree);
2358        ReductionRoot->setOperand(1, ReductionPHI);
2359      } else
2360        ReductionRoot->replaceAllUsesWith(VectorizedTree);
2361    }
2362    return VectorizedTree != 0;
2363  }
2364
2365private:
2366
2367  /// \brief Calcuate the cost of a reduction.
2368  int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
2369    Type *ScalarTy = FirstReducedVal->getType();
2370    Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
2371
2372    int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
2373    int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
2374
2375    IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
2376    int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
2377
2378    int ScalarReduxCost =
2379        ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
2380
2381    DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
2382                 << " for reduction that starts with " << *FirstReducedVal
2383                 << " (It is a "
2384                 << (IsPairwiseReduction ? "pairwise" : "splitting")
2385                 << " reduction)\n");
2386
2387    return VecReduxCost - ScalarReduxCost;
2388  }
2389
2390  static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
2391                            Value *R, const Twine &Name = "") {
2392    if (Opcode == Instruction::FAdd)
2393      return Builder.CreateFAdd(L, R, Name);
2394    return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
2395  }
2396
2397  /// \brief Emit a horizontal reduction of the vectorized value.
2398  Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
2399    assert(VectorizedValue && "Need to have a vectorized tree node");
2400    Instruction *ValToReduce = dyn_cast<Instruction>(VectorizedValue);
2401    assert(isPowerOf2_32(ReduxWidth) &&
2402           "We only handle power-of-two reductions for now");
2403
2404    Value *TmpVec = ValToReduce;
2405    for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
2406      if (IsPairwiseReduction) {
2407        Value *LeftMask =
2408          createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
2409        Value *RightMask =
2410          createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
2411
2412        Value *LeftShuf = Builder.CreateShuffleVector(
2413          TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
2414        Value *RightShuf = Builder.CreateShuffleVector(
2415          TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
2416          "rdx.shuf.r");
2417        TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
2418                             "bin.rdx");
2419      } else {
2420        Value *UpperHalf =
2421          createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
2422        Value *Shuf = Builder.CreateShuffleVector(
2423          TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
2424        TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
2425      }
2426    }
2427
2428    // The result is in the first element of the vector.
2429    return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2430  }
2431};
2432
2433/// \brief Recognize construction of vectors like
2434///  %ra = insertelement <4 x float> undef, float %s0, i32 0
2435///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
2436///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
2437///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
2438///
2439/// Returns true if it matches
2440///
2441static bool findBuildVector(InsertElementInst *IE,
2442                            SmallVectorImpl<Value *> &Ops) {
2443  if (!isa<UndefValue>(IE->getOperand(0)))
2444    return false;
2445
2446  while (true) {
2447    Ops.push_back(IE->getOperand(1));
2448
2449    if (IE->use_empty())
2450      return false;
2451
2452    InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->use_back());
2453    if (!NextUse)
2454      return true;
2455
2456    // If this isn't the final use, make sure the next insertelement is the only
2457    // use. It's OK if the final constructed vector is used multiple times
2458    if (!IE->hasOneUse())
2459      return false;
2460
2461    IE = NextUse;
2462  }
2463
2464  return false;
2465}
2466
2467static bool PhiTypeSorterFunc(Value *V, Value *V2) {
2468  return V->getType() < V2->getType();
2469}
2470
2471bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
2472  bool Changed = false;
2473  SmallVector<Value *, 4> Incoming;
2474  SmallSet<Value *, 16> VisitedInstrs;
2475
2476  bool HaveVectorizedPhiNodes = true;
2477  while (HaveVectorizedPhiNodes) {
2478    HaveVectorizedPhiNodes = false;
2479
2480    // Collect the incoming values from the PHIs.
2481    Incoming.clear();
2482    for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
2483         ++instr) {
2484      PHINode *P = dyn_cast<PHINode>(instr);
2485      if (!P)
2486        break;
2487
2488      if (!VisitedInstrs.count(P))
2489        Incoming.push_back(P);
2490    }
2491
2492    // Sort by type.
2493    std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
2494
2495    // Try to vectorize elements base on their type.
2496    for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
2497                                           E = Incoming.end();
2498         IncIt != E;) {
2499
2500      // Look for the next elements with the same type.
2501      SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
2502      while (SameTypeIt != E &&
2503             (*SameTypeIt)->getType() == (*IncIt)->getType()) {
2504        VisitedInstrs.insert(*SameTypeIt);
2505        ++SameTypeIt;
2506      }
2507
2508      // Try to vectorize them.
2509      unsigned NumElts = (SameTypeIt - IncIt);
2510      DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
2511      if (NumElts > 1 &&
2512          tryToVectorizeList(ArrayRef<Value *>(IncIt, NumElts), R)) {
2513        // Success start over because instructions might have been changed.
2514        HaveVectorizedPhiNodes = true;
2515        Changed = true;
2516        break;
2517      }
2518
2519      // Start over at the next instruction of a differnt type (or the end).
2520      IncIt = SameTypeIt;
2521    }
2522  }
2523
2524  VisitedInstrs.clear();
2525
2526  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
2527    // We may go through BB multiple times so skip the one we have checked.
2528    if (!VisitedInstrs.insert(it))
2529      continue;
2530
2531    if (isa<DbgInfoIntrinsic>(it))
2532      continue;
2533
2534    // Try to vectorize reductions that use PHINodes.
2535    if (PHINode *P = dyn_cast<PHINode>(it)) {
2536      // Check that the PHI is a reduction PHI.
2537      if (P->getNumIncomingValues() != 2)
2538        return Changed;
2539      Value *Rdx =
2540          (P->getIncomingBlock(0) == BB
2541               ? (P->getIncomingValue(0))
2542               : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
2543      // Check if this is a Binary Operator.
2544      BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
2545      if (!BI)
2546        continue;
2547
2548      // Try to match and vectorize a horizontal reduction.
2549      HorizontalReduction HorRdx;
2550      if (ShouldVectorizeHor &&
2551          HorRdx.matchAssociativeReduction(P, BI, DL) &&
2552          HorRdx.tryToReduce(R, TTI)) {
2553        Changed = true;
2554        it = BB->begin();
2555        e = BB->end();
2556        continue;
2557      }
2558
2559     Value *Inst = BI->getOperand(0);
2560      if (Inst == P)
2561        Inst = BI->getOperand(1);
2562
2563      if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
2564        // We would like to start over since some instructions are deleted
2565        // and the iterator may become invalid value.
2566        Changed = true;
2567        it = BB->begin();
2568        e = BB->end();
2569        continue;
2570      }
2571
2572      continue;
2573    }
2574
2575    // Try to vectorize horizontal reductions feeding into a store.
2576    if (ShouldStartVectorizeHorAtStore)
2577      if (StoreInst *SI = dyn_cast<StoreInst>(it))
2578        if (BinaryOperator *BinOp =
2579                dyn_cast<BinaryOperator>(SI->getValueOperand())) {
2580          HorizontalReduction HorRdx;
2581          if (((HorRdx.matchAssociativeReduction(0, BinOp, DL) &&
2582                HorRdx.tryToReduce(R, TTI)) ||
2583               tryToVectorize(BinOp, R))) {
2584            Changed = true;
2585            it = BB->begin();
2586            e = BB->end();
2587            continue;
2588          }
2589        }
2590
2591    // Try to vectorize trees that start at compare instructions.
2592    if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
2593      if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
2594        Changed = true;
2595        // We would like to start over since some instructions are deleted
2596        // and the iterator may become invalid value.
2597        it = BB->begin();
2598        e = BB->end();
2599        continue;
2600      }
2601
2602      for (int i = 0; i < 2; ++i) {
2603         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
2604            if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
2605              Changed = true;
2606              // We would like to start over since some instructions are deleted
2607              // and the iterator may become invalid value.
2608              it = BB->begin();
2609              e = BB->end();
2610            }
2611         }
2612      }
2613      continue;
2614    }
2615
2616    // Try to vectorize trees that start at insertelement instructions.
2617    if (InsertElementInst *IE = dyn_cast<InsertElementInst>(it)) {
2618      SmallVector<Value *, 8> Ops;
2619      if (!findBuildVector(IE, Ops))
2620        continue;
2621
2622      if (tryToVectorizeList(Ops, R)) {
2623        Changed = true;
2624        it = BB->begin();
2625        e = BB->end();
2626      }
2627
2628      continue;
2629    }
2630  }
2631
2632  return Changed;
2633}
2634
2635bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
2636  bool Changed = false;
2637  // Attempt to sort and vectorize each of the store-groups.
2638  for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
2639       it != e; ++it) {
2640    if (it->second.size() < 2)
2641      continue;
2642
2643    DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
2644          << it->second.size() << ".\n");
2645
2646    // Process the stores in chunks of 16.
2647    for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
2648      unsigned Len = std::min<unsigned>(CE - CI, 16);
2649      ArrayRef<StoreInst *> Chunk(&it->second[CI], Len);
2650      Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R);
2651    }
2652  }
2653  return Changed;
2654}
2655
2656} // end anonymous namespace
2657
2658char SLPVectorizer::ID = 0;
2659static const char lv_name[] = "SLP Vectorizer";
2660INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
2661INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2662INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
2663INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2664INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2665INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
2666
2667namespace llvm {
2668Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
2669}
2670