Fix PR16571, which is a bug in the code that checks that all of the types in the...
[oota-llvm.git] / lib / Transforms / Vectorize / SLPVectorizer.cpp
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/AliasAnalysis.h"
29 #include "llvm/Analysis/TargetTransformInfo.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
46 using namespace llvm;
47
48 static 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 namespace {
53
54 static const unsigned MinVecRegSize = 128;
55
56 static const unsigned RecursionMaxDepth = 12;
57
58 /// RAII pattern to save the insertion point of the IR builder.
59 class BuilderLocGuard {
60 public:
61   BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()) {}
62   ~BuilderLocGuard() { if (Loc) Builder.SetInsertPoint(Loc); }
63
64 private:
65   // Prevent copying.
66   BuilderLocGuard(const BuilderLocGuard &);
67   BuilderLocGuard &operator=(const BuilderLocGuard &);
68   IRBuilder<> &Builder;
69   AssertingVH<Instruction> Loc;
70 };
71
72 /// A helper class for numbering instructions in multible blocks.
73 /// Numbers starts at zero for each basic block.
74 struct BlockNumbering {
75
76   BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {}
77
78   BlockNumbering() : BB(0), Valid(false) {}
79
80   void numberInstructions() {
81     unsigned Loc = 0;
82     InstrIdx.clear();
83     InstrVec.clear();
84     // Number the instructions in the block.
85     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
86       InstrIdx[it] = Loc++;
87       InstrVec.push_back(it);
88       assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation");
89     }
90     Valid = true;
91   }
92
93   int getIndex(Instruction *I) {
94     assert(I->getParent() == BB && "Invalid instruction");
95     if (!Valid)
96       numberInstructions();
97     assert(InstrIdx.count(I) && "Unknown instruction");
98     return InstrIdx[I];
99   }
100
101   Instruction *getInstruction(unsigned loc) {
102     if (!Valid)
103       numberInstructions();
104     assert(InstrVec.size() > loc && "Invalid Index");
105     return InstrVec[loc];
106   }
107
108   void forget() { Valid = false; }
109
110 private:
111   /// The block we are numbering.
112   BasicBlock *BB;
113   /// Is the block numbered.
114   bool Valid;
115   /// Maps instructions to numbers and back.
116   SmallDenseMap<Instruction *, int> InstrIdx;
117   /// Maps integers to Instructions.
118   std::vector<Instruction *> InstrVec;
119 };
120
121 /// \returns the parent basic block if all of the instructions in \p VL
122 /// are in the same block or null otherwise.
123 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
124   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
125   if (!I0)
126     return 0;
127   BasicBlock *BB = I0->getParent();
128   for (int i = 1, e = VL.size(); i < e; i++) {
129     Instruction *I = dyn_cast<Instruction>(VL[i]);
130     if (!I)
131       return 0;
132
133     if (BB != I->getParent())
134       return 0;
135   }
136   return BB;
137 }
138
139 /// \returns True if all of the values in \p VL are constants.
140 static bool allConstant(ArrayRef<Value *> VL) {
141   for (unsigned i = 0, e = VL.size(); i < e; ++i)
142     if (!isa<Constant>(VL[i]))
143       return false;
144   return true;
145 }
146
147 /// \returns True if all of the values in \p VL are identical.
148 static bool isSplat(ArrayRef<Value *> VL) {
149   for (unsigned i = 1, e = VL.size(); i < e; ++i)
150     if (VL[i] != VL[0])
151       return false;
152   return true;
153 }
154
155 /// \returns The opcode if all of the Instructions in \p VL have the same
156 /// opcode, or zero.
157 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
158   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
159   if (!I0)
160     return 0;
161   unsigned Opcode = I0->getOpcode();
162   for (int i = 1, e = VL.size(); i < e; i++) {
163     Instruction *I = dyn_cast<Instruction>(VL[i]);
164     if (!I || Opcode != I->getOpcode())
165       return 0;
166   }
167   return Opcode;
168 }
169
170 /// \returns The type that all of the values in \p VL have or null if there
171 /// are different types.
172 static Type* getSameType(ArrayRef<Value *> VL) {
173   Type *Ty = VL[0]->getType();
174   for (int i = 1, e = VL.size(); i < e; i++)
175     if (VL[i]->getType() != Ty)
176       return 0;
177
178   return Ty;
179 }
180
181 /// \returns True if the ExtractElement instructions in VL can be vectorized
182 /// to use the original vector.
183 static bool CanReuseExtract(ArrayRef<Value *> VL) {
184   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
185   // Check if all of the extracts come from the same vector and from the
186   // correct offset.
187   Value *VL0 = VL[0];
188   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
189   Value *Vec = E0->getOperand(0);
190
191   // We have to extract from the same vector type.
192   unsigned NElts = Vec->getType()->getVectorNumElements();
193
194   if (NElts != VL.size())
195     return false;
196
197   // Check that all of the indices extract from the correct offset.
198   ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
199   if (!CI || CI->getZExtValue())
200     return false;
201
202   for (unsigned i = 1, e = VL.size(); i < e; ++i) {
203     ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
204     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
205
206     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
207       return false;
208   }
209
210   return true;
211 }
212
213 /// Bottom Up SLP Vectorizer.
214 class BoUpSLP {
215 public:
216   typedef SmallVector<Value *, 8> ValueList;
217   typedef SmallVector<Instruction *, 16> InstrList;
218   typedef SmallPtrSet<Value *, 16> ValueSet;
219   typedef SmallVector<StoreInst *, 8> StoreList;
220
221   BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl,
222           TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li,
223           DominatorTree *Dt) :
224     F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt),
225     Builder(Se->getContext()) {
226       // Setup the block numbering utility for all of the blocks in the
227       // function.
228       for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
229         BasicBlock *BB = it;
230         BlocksNumbers[BB] = BlockNumbering(BB);
231       }
232     }
233
234   /// \brief Vectorize the tree that starts with the elements in \p VL.
235   void vectorizeTree();
236
237   /// \returns the vectorization cost of the subtree that starts at \p VL.
238   /// A negative number means that this is profitable.
239   int getTreeCost();
240
241   /// Construct a vectorizable tree that starts at \p Roots.
242   void buildTree(ArrayRef<Value *> Roots);
243
244   /// Clear the internal data structures that are created by 'buildTree'.
245   void deleteTree() {
246     VectorizableTree.clear();
247     ScalarToTreeEntry.clear();
248     MustGather.clear();
249     MemBarrierIgnoreList.clear();
250   }
251
252   /// \returns the scalarization cost for this list of values. Assuming that
253   /// this subtree gets vectorized, we may need to extract the values from the
254   /// roots. This method calculates the cost of extracting the values.
255   int getGatherCost(ArrayRef<Value *> VL);
256
257   /// \returns true if the memory operations A and B are consecutive.
258   bool isConsecutiveAccess(Value *A, Value *B);
259
260   /// \brief Perform LICM and CSE on the newly generated gather sequences.
261   void optimizeGatherSequence();
262 private:
263   struct TreeEntry;
264
265   /// \returns the cost of the vectorizable entry.
266   int getEntryCost(TreeEntry *E);
267
268   /// This is the recursive part of buildTree.
269   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
270
271   /// Vectorizer a single entry in the tree.
272   Value *vectorizeTree(TreeEntry *E);
273
274   /// Vectorizer a single entry in the tree, starting in \p VL.
275   Value *vectorizeTree(ArrayRef<Value *> VL);
276
277   /// \brief Take the pointer operand from the Load/Store instruction.
278   /// \returns NULL if this is not a valid Load/Store instruction.
279   static Value *getPointerOperand(Value *I);
280
281   /// \brief Take the address space operand from the Load/Store instruction.
282   /// \returns -1 if this is not a valid Load/Store instruction.
283   static unsigned getAddressSpaceOperand(Value *I);
284
285   /// \returns the scalarization cost for this type. Scalarization in this
286   /// context means the creation of vectors from a group of scalars.
287   int getGatherCost(Type *Ty);
288
289   /// \returns the AA location that is being access by the instruction.
290   AliasAnalysis::Location getLocation(Instruction *I);
291
292   /// \brief Checks if it is possible to sink an instruction from
293   /// \p Src to \p Dst.
294   /// \returns the pointer to the barrier instruction if we can't sink.
295   Value *getSinkBarrier(Instruction *Src, Instruction *Dst);
296
297   /// \returns the index of the last instrucion in the BB from \p VL.
298   int getLastIndex(ArrayRef<Value *> VL);
299
300   /// \returns the Instrucion in the bundle \p VL.
301   Instruction *getLastInstruction(ArrayRef<Value *> VL);
302
303   /// \returns the Instruction at index \p Index which is in Block \p BB.
304   Instruction *getInstructionForIndex(unsigned Index, BasicBlock *BB);
305
306   /// \returns the index of the first User of \p VL.
307   int getFirstUserIndex(ArrayRef<Value *> VL);
308
309   /// \returns a vector from a collection of scalars in \p VL.
310   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
311
312   struct TreeEntry {
313     TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0),
314     NeedToGather(0) {}
315
316     /// \returns true if the scalars in VL are equal to this entry.
317     bool isSame(ArrayRef<Value *> VL) {
318       assert(VL.size() == Scalars.size() && "Invalid size");
319       for (int i = 0, e = VL.size(); i != e; ++i)
320         if (VL[i] != Scalars[i])
321           return false;
322       return true;
323     }
324
325     /// A vector of scalars.
326     ValueList Scalars;
327
328     /// The Scalars are vectorized into this value. It is initialized to Null.
329     Value *VectorizedValue;
330
331     /// The index in the basic block of the last scalar.
332     int LastScalarIndex;
333
334     /// Do we need to gather this sequence ?
335     bool NeedToGather;
336   };
337
338   /// Create a new VectorizableTree entry.
339   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
340     VectorizableTree.push_back(TreeEntry());
341     int idx = VectorizableTree.size() - 1;
342     TreeEntry *Last = &VectorizableTree[idx];
343     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
344     Last->NeedToGather = !Vectorized;
345     if (Vectorized) {
346       Last->LastScalarIndex = getLastIndex(VL);
347       for (int i = 0, e = VL.size(); i != e; ++i) {
348         assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
349         ScalarToTreeEntry[VL[i]] = idx;
350       }
351     } else {
352       Last->LastScalarIndex = 0;
353       MustGather.insert(VL.begin(), VL.end());
354     }
355     return Last;
356   }
357
358   /// -- Vectorization State --
359   /// Holds all of the tree entries.
360   std::vector<TreeEntry> VectorizableTree;
361
362   /// Maps a specific scalar to its tree entry.
363   SmallDenseMap<Value*, int> ScalarToTreeEntry;
364
365   /// A list of scalars that we found that we need to keep as scalars.
366   ValueSet MustGather;
367
368   /// A list of instructions to ignore while sinking
369   /// memory instructions. This map must be reset between runs of getCost.
370   ValueSet MemBarrierIgnoreList;
371
372   /// Holds all of the instructions that we gathered.
373   SetVector<Instruction *> GatherSeq;
374
375   /// Numbers instructions in different blocks.
376   std::map<BasicBlock *, BlockNumbering> BlocksNumbers;
377
378   // Analysis and block reference.
379   Function *F;
380   ScalarEvolution *SE;
381   DataLayout *DL;
382   TargetTransformInfo *TTI;
383   AliasAnalysis *AA;
384   LoopInfo *LI;
385   DominatorTree *DT;
386   /// Instruction builder to construct the vectorized tree.
387   IRBuilder<> Builder;
388 };
389
390 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
391   deleteTree();
392   if (!getSameType(Roots))
393     return;
394   buildTree_rec(Roots, 0);
395 }
396
397
398 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
399   bool SameTy = getSameType(VL); (void)SameTy;
400   assert(SameTy && "Invalid types!");
401
402   if (Depth == RecursionMaxDepth) {
403     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
404     newTreeEntry(VL, false);
405     return;
406   }
407
408   // Don't handle vectors.
409   if (VL[0]->getType()->isVectorTy()) {
410     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
411     newTreeEntry(VL, false);
412     return;
413   }
414
415   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
416     if (SI->getValueOperand()->getType()->isVectorTy()) {
417       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
418       newTreeEntry(VL, false);
419       return;
420     }
421
422   // If all of the operands are identical or constant we have a simple solution.
423   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) ||
424       !getSameOpcode(VL)) {
425     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
426     newTreeEntry(VL, false);
427     return;
428   }
429
430   // We now know that this is a vector of instructions of the same type from
431   // the same block.
432
433   // Check if this is a duplicate of another entry.
434   if (ScalarToTreeEntry.count(VL[0])) {
435     int Idx = ScalarToTreeEntry[VL[0]];
436     TreeEntry *E = &VectorizableTree[Idx];
437     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
438       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
439       if (E->Scalars[i] != VL[i]) {
440         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
441         newTreeEntry(VL, false);
442         return;
443       }
444     }
445     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
446     return;
447   }
448
449   // Check that none of the instructions in the bundle are already in the tree.
450   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
451     if (ScalarToTreeEntry.count(VL[i])) {
452       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
453             ") is already in tree.\n");
454       newTreeEntry(VL, false);
455       return;
456     }
457   }
458
459   // If any of the scalars appears in the table OR it is marked as a value that
460   // needs to stat scalar then we need to gather the scalars.
461   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
462     if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) {
463       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n");
464       newTreeEntry(VL, false);
465       return;
466     }
467   }
468
469   // Check that all of the users of the scalars that we want to vectorize are
470   // schedulable.
471   Instruction *VL0 = cast<Instruction>(VL[0]);
472   int MyLastIndex = getLastIndex(VL);
473   BasicBlock *BB = cast<Instruction>(VL0)->getParent();
474
475   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
476     Instruction *Scalar = cast<Instruction>(VL[i]);
477     DEBUG(dbgs() << "SLP: Checking users of  " << *Scalar << ". \n");
478     for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end();
479          U != UE; ++U) {
480       DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n");
481       Instruction *User = dyn_cast<Instruction>(*U);
482       if (!User) {
483         DEBUG(dbgs() << "SLP: Gathering due unknown user. \n");
484         newTreeEntry(VL, false);
485         return;
486       }
487
488       // We don't care if the user is in a different basic block.
489       BasicBlock *UserBlock = User->getParent();
490       if (UserBlock != BB) {
491         DEBUG(dbgs() << "SLP: User from a different basic block "
492               << *User << ". \n");
493         continue;
494       }
495
496       // If this is a PHINode within this basic block then we can place the
497       // extract wherever we want.
498       if (isa<PHINode>(*User)) {
499         DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n");
500         continue;
501       }
502
503       // Check if this is a safe in-tree user.
504       if (ScalarToTreeEntry.count(User)) {
505         int Idx = ScalarToTreeEntry[User];
506         int VecLocation = VectorizableTree[Idx].LastScalarIndex;
507         if (VecLocation <= MyLastIndex) {
508           DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n");
509           newTreeEntry(VL, false);
510           return;
511         }
512         DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" <<
513               VecLocation << " vector value (" << *Scalar << ") at #"
514               << MyLastIndex << ".\n");
515         continue;
516       }
517
518       // Make sure that we can schedule this unknown user.
519       BlockNumbering &BN = BlocksNumbers[BB];
520       int UserIndex = BN.getIndex(User);
521       if (UserIndex < MyLastIndex) {
522
523         DEBUG(dbgs() << "SLP: Can't schedule extractelement for "
524               << *User << ". \n");
525         newTreeEntry(VL, false);
526         return;
527       }
528     }
529   }
530
531   // Check that every instructions appears once in this bundle.
532   for (unsigned i = 0, e = VL.size(); i < e; ++i)
533     for (unsigned j = i+1; j < e; ++j)
534       if (VL[i] == VL[j]) {
535         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
536         newTreeEntry(VL, false);
537         return;
538       }
539
540   // Check that instructions in this bundle don't reference other instructions.
541   // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4.
542   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
543     for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
544          U != UE; ++U) {
545       for (unsigned j = 0; j < e; ++j) {
546         if (i != j && *U == VL[j]) {
547           DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n");
548           newTreeEntry(VL, false);
549           return;
550         }
551       }
552     }
553   }
554
555   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
556
557   unsigned Opcode = getSameOpcode(VL);
558
559   // Check if it is safe to sink the loads or the stores.
560   if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
561     Instruction *Last = getLastInstruction(VL);
562
563     for (unsigned i = 0, e = VL.size(); i < e; ++i) {
564       if (VL[i] == Last)
565         continue;
566       Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last);
567       if (Barrier) {
568         DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last
569               << "\n because of " << *Barrier << ".  Gathering.\n");
570         newTreeEntry(VL, false);
571         return;
572       }
573     }
574   }
575
576   switch (Opcode) {
577     case Instruction::PHI: {
578       PHINode *PH = dyn_cast<PHINode>(VL0);
579       newTreeEntry(VL, true);
580       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
581
582       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
583         ValueList Operands;
584         // Prepare the operand vector.
585         for (unsigned j = 0; j < VL.size(); ++j)
586           Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i));
587
588         buildTree_rec(Operands, Depth + 1);
589       }
590       return;
591     }
592     case Instruction::ExtractElement: {
593       bool Reuse = CanReuseExtract(VL);
594       if (Reuse) {
595         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
596       }
597       newTreeEntry(VL, Reuse);
598       return;
599     }
600     case Instruction::Load: {
601       // Check if the loads are consecutive or of we need to swizzle them.
602       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
603         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
604           newTreeEntry(VL, false);
605           DEBUG(dbgs() << "SLP: Need to swizzle loads.\n");
606           return;
607         }
608
609       newTreeEntry(VL, true);
610       DEBUG(dbgs() << "SLP: added a vector of loads.\n");
611       return;
612     }
613     case Instruction::ZExt:
614     case Instruction::SExt:
615     case Instruction::FPToUI:
616     case Instruction::FPToSI:
617     case Instruction::FPExt:
618     case Instruction::PtrToInt:
619     case Instruction::IntToPtr:
620     case Instruction::SIToFP:
621     case Instruction::UIToFP:
622     case Instruction::Trunc:
623     case Instruction::FPTrunc:
624     case Instruction::BitCast: {
625       Type *SrcTy = VL0->getOperand(0)->getType();
626       for (unsigned i = 0; i < VL.size(); ++i) {
627         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
628         if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
629           newTreeEntry(VL, false);
630           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
631           return;
632         }
633       }
634       newTreeEntry(VL, true);
635       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
636
637       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
638         ValueList Operands;
639         // Prepare the operand vector.
640         for (unsigned j = 0; j < VL.size(); ++j)
641           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
642
643         buildTree_rec(Operands, Depth+1);
644       }
645       return;
646     }
647     case Instruction::ICmp:
648     case Instruction::FCmp: {
649       // Check that all of the compares have the same predicate.
650       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
651       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
652         CmpInst *Cmp = cast<CmpInst>(VL[i]);
653         if (Cmp->getPredicate() != P0) {
654           newTreeEntry(VL, false);
655           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
656           return;
657         }
658       }
659
660       newTreeEntry(VL, true);
661       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
662
663       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
664         ValueList Operands;
665         // Prepare the operand vector.
666         for (unsigned j = 0; j < VL.size(); ++j)
667           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
668
669         buildTree_rec(Operands, Depth+1);
670       }
671       return;
672     }
673     case Instruction::Select:
674     case Instruction::Add:
675     case Instruction::FAdd:
676     case Instruction::Sub:
677     case Instruction::FSub:
678     case Instruction::Mul:
679     case Instruction::FMul:
680     case Instruction::UDiv:
681     case Instruction::SDiv:
682     case Instruction::FDiv:
683     case Instruction::URem:
684     case Instruction::SRem:
685     case Instruction::FRem:
686     case Instruction::Shl:
687     case Instruction::LShr:
688     case Instruction::AShr:
689     case Instruction::And:
690     case Instruction::Or:
691     case Instruction::Xor: {
692       newTreeEntry(VL, true);
693       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
694
695       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
696         ValueList Operands;
697         // Prepare the operand vector.
698         for (unsigned j = 0; j < VL.size(); ++j)
699           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
700
701         buildTree_rec(Operands, Depth+1);
702       }
703       return;
704     }
705     case Instruction::Store: {
706       // Check if the stores are consecutive or of we need to swizzle them.
707       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
708         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
709           newTreeEntry(VL, false);
710           DEBUG(dbgs() << "SLP: Non consecutive store.\n");
711           return;
712         }
713
714       newTreeEntry(VL, true);
715       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
716
717       ValueList Operands;
718       for (unsigned j = 0; j < VL.size(); ++j)
719         Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
720
721       // We can ignore these values because we are sinking them down.
722       MemBarrierIgnoreList.insert(VL.begin(), VL.end());
723       buildTree_rec(Operands, Depth + 1);
724       return;
725     }
726     default:
727       newTreeEntry(VL, false);
728       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
729       return;
730   }
731 }
732
733 int BoUpSLP::getEntryCost(TreeEntry *E) {
734   ArrayRef<Value*> VL = E->Scalars;
735
736   Type *ScalarTy = VL[0]->getType();
737   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
738     ScalarTy = SI->getValueOperand()->getType();
739   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
740
741   if (E->NeedToGather) {
742     if (allConstant(VL))
743       return 0;
744     if (isSplat(VL)) {
745       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
746     }
747     return getGatherCost(E->Scalars);
748   }
749
750   assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) &&
751          "Invalid VL");
752   Instruction *VL0 = cast<Instruction>(VL[0]);
753   unsigned Opcode = VL0->getOpcode();
754   switch (Opcode) {
755     case Instruction::PHI: {
756       return 0;
757     }
758     case Instruction::ExtractElement: {
759       if (CanReuseExtract(VL))
760         return 0;
761       return getGatherCost(VecTy);
762     }
763     case Instruction::ZExt:
764     case Instruction::SExt:
765     case Instruction::FPToUI:
766     case Instruction::FPToSI:
767     case Instruction::FPExt:
768     case Instruction::PtrToInt:
769     case Instruction::IntToPtr:
770     case Instruction::SIToFP:
771     case Instruction::UIToFP:
772     case Instruction::Trunc:
773     case Instruction::FPTrunc:
774     case Instruction::BitCast: {
775       Type *SrcTy = VL0->getOperand(0)->getType();
776
777       // Calculate the cost of this instruction.
778       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
779                                                          VL0->getType(), SrcTy);
780
781       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
782       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
783       return VecCost - ScalarCost;
784     }
785     case Instruction::FCmp:
786     case Instruction::ICmp:
787     case Instruction::Select:
788     case Instruction::Add:
789     case Instruction::FAdd:
790     case Instruction::Sub:
791     case Instruction::FSub:
792     case Instruction::Mul:
793     case Instruction::FMul:
794     case Instruction::UDiv:
795     case Instruction::SDiv:
796     case Instruction::FDiv:
797     case Instruction::URem:
798     case Instruction::SRem:
799     case Instruction::FRem:
800     case Instruction::Shl:
801     case Instruction::LShr:
802     case Instruction::AShr:
803     case Instruction::And:
804     case Instruction::Or:
805     case Instruction::Xor: {
806       // Calculate the cost of this instruction.
807       int ScalarCost = 0;
808       int VecCost = 0;
809       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
810           Opcode == Instruction::Select) {
811         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
812         ScalarCost = VecTy->getNumElements() *
813         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
814         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
815       } else {
816         ScalarCost = VecTy->getNumElements() *
817         TTI->getArithmeticInstrCost(Opcode, ScalarTy);
818         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy);
819       }
820       return VecCost - ScalarCost;
821     }
822     case Instruction::Load: {
823       // Cost of wide load - cost of scalar loads.
824       int ScalarLdCost = VecTy->getNumElements() *
825       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
826       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
827       return VecLdCost - ScalarLdCost;
828     }
829     case Instruction::Store: {
830       // We know that we can merge the stores. Calculate the cost.
831       int ScalarStCost = VecTy->getNumElements() *
832       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
833       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
834       return VecStCost - ScalarStCost;
835     }
836     default:
837       llvm_unreachable("Unknown instruction");
838   }
839 }
840
841 int BoUpSLP::getTreeCost() {
842   int Cost = 0;
843   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
844         VectorizableTree.size() << ".\n");
845
846   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
847     int C = getEntryCost(&VectorizableTree[i]);
848     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
849           << *VectorizableTree[i].Scalars[0] << " .\n");
850     Cost += C;
851   }
852   DEBUG(dbgs() << "SLP: Total Cost " << Cost << ".\n");
853   return  Cost;
854 }
855
856 int BoUpSLP::getGatherCost(Type *Ty) {
857   int Cost = 0;
858   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
859     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
860   return Cost;
861 }
862
863 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
864   // Find the type of the operands in VL.
865   Type *ScalarTy = VL[0]->getType();
866   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
867     ScalarTy = SI->getValueOperand()->getType();
868   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
869   // Find the cost of inserting/extracting values from the vector.
870   return getGatherCost(VecTy);
871 }
872
873 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) {
874   if (StoreInst *SI = dyn_cast<StoreInst>(I))
875     return AA->getLocation(SI);
876   if (LoadInst *LI = dyn_cast<LoadInst>(I))
877     return AA->getLocation(LI);
878   return AliasAnalysis::Location();
879 }
880
881 Value *BoUpSLP::getPointerOperand(Value *I) {
882   if (LoadInst *LI = dyn_cast<LoadInst>(I))
883     return LI->getPointerOperand();
884   if (StoreInst *SI = dyn_cast<StoreInst>(I))
885     return SI->getPointerOperand();
886   return 0;
887 }
888
889 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
890   if (LoadInst *L = dyn_cast<LoadInst>(I))
891     return L->getPointerAddressSpace();
892   if (StoreInst *S = dyn_cast<StoreInst>(I))
893     return S->getPointerAddressSpace();
894   return -1;
895 }
896
897 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
898   Value *PtrA = getPointerOperand(A);
899   Value *PtrB = getPointerOperand(B);
900   unsigned ASA = getAddressSpaceOperand(A);
901   unsigned ASB = getAddressSpaceOperand(B);
902
903   // Check that the address spaces match and that the pointers are valid.
904   if (!PtrA || !PtrB || (ASA != ASB))
905     return false;
906
907   // Check that A and B are of the same type.
908   if (PtrA->getType() != PtrB->getType())
909     return false;
910
911   // Calculate the distance.
912   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
913   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
914   const SCEV *OffsetSCEV = SE->getMinusSCEV(PtrSCEVA, PtrSCEVB);
915   const SCEVConstant *ConstOffSCEV = dyn_cast<SCEVConstant>(OffsetSCEV);
916
917   // Non constant distance.
918   if (!ConstOffSCEV)
919     return false;
920
921   int64_t Offset = ConstOffSCEV->getValue()->getSExtValue();
922   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
923   // The Instructions are connsecutive if the size of the first load/store is
924   // the same as the offset.
925   int64_t Sz = DL->getTypeStoreSize(Ty);
926   return ((-Offset) == Sz);
927 }
928
929 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) {
930   assert(Src->getParent() == Dst->getParent() && "Not the same BB");
931   BasicBlock::iterator I = Src, E = Dst;
932   /// Scan all of the instruction from SRC to DST and check if
933   /// the source may alias.
934   for (++I; I != E; ++I) {
935     // Ignore store instructions that are marked as 'ignore'.
936     if (MemBarrierIgnoreList.count(I))
937       continue;
938     if (Src->mayWriteToMemory()) /* Write */ {
939       if (!I->mayReadOrWriteMemory())
940         continue;
941     } else /* Read */ {
942       if (!I->mayWriteToMemory())
943         continue;
944     }
945     AliasAnalysis::Location A = getLocation(&*I);
946     AliasAnalysis::Location B = getLocation(Src);
947
948     if (!A.Ptr || !B.Ptr || AA->alias(A, B))
949       return I;
950   }
951   return 0;
952 }
953
954 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) {
955   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
956   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
957   BlockNumbering &BN = BlocksNumbers[BB];
958
959   int MaxIdx = BN.getIndex(BB->getFirstNonPHI());
960   for (unsigned i = 0, e = VL.size(); i < e; ++i)
961     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
962   return MaxIdx;
963 }
964
965 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) {
966   BasicBlock *BB = cast<Instruction>(VL[0])->getParent();
967   assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block");
968   BlockNumbering &BN = BlocksNumbers[BB];
969
970   int MaxIdx = BN.getIndex(cast<Instruction>(VL[0]));
971   for (unsigned i = 1, e = VL.size(); i < e; ++i)
972     MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i])));
973   Instruction *I = BN.getInstruction(MaxIdx);
974   assert(I && "bad location");
975   return I;
976 }
977
978 Instruction *BoUpSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) {
979   BlockNumbering &BN = BlocksNumbers[BB];
980   return BN.getInstruction(Index);
981 }
982
983 int BoUpSLP::getFirstUserIndex(ArrayRef<Value *> VL) {
984   BasicBlock *BB = getSameBlock(VL);
985   assert(BB && "All instructions must come from the same block");
986   BlockNumbering &BN = BlocksNumbers[BB];
987
988   // Find the first user of the values.
989   int FirstUser = BN.getIndex(BB->getTerminator());
990   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
991     for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end();
992          U != UE; ++U) {
993       Instruction *Instr = dyn_cast<Instruction>(*U);
994
995       if (!Instr || Instr->getParent() != BB)
996         continue;
997
998       FirstUser = std::min(FirstUser, BN.getIndex(Instr));
999     }
1000   }
1001   return FirstUser;
1002 }
1003
1004 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
1005   Value *Vec = UndefValue::get(Ty);
1006   // Generate the 'InsertElement' instruction.
1007   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
1008     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
1009     if (Instruction *I = dyn_cast<Instruction>(Vec))
1010       GatherSeq.insert(I);
1011   }
1012
1013   return Vec;
1014 }
1015
1016 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
1017   if (ScalarToTreeEntry.count(VL[0])) {
1018     int Idx = ScalarToTreeEntry[VL[0]];
1019     TreeEntry *E = &VectorizableTree[Idx];
1020     if (E->isSame(VL))
1021       return vectorizeTree(E);
1022   }
1023
1024   Type *ScalarTy = VL[0]->getType();
1025   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1026     ScalarTy = SI->getValueOperand()->getType();
1027   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1028
1029   return Gather(VL, VecTy);
1030 }
1031
1032 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
1033   BuilderLocGuard Guard(Builder);
1034
1035   if (E->VectorizedValue) {
1036     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
1037     return E->VectorizedValue;
1038   }
1039
1040   Type *ScalarTy = E->Scalars[0]->getType();
1041   if (StoreInst *SI = dyn_cast<StoreInst>(E->Scalars[0]))
1042     ScalarTy = SI->getValueOperand()->getType();
1043   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
1044
1045   if (E->NeedToGather) {
1046     return Gather(E->Scalars, VecTy);
1047   }
1048
1049   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
1050   unsigned Opcode = VL0->getOpcode();
1051   assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode");
1052
1053   switch (Opcode) {
1054     case Instruction::PHI: {
1055       PHINode *PH = dyn_cast<PHINode>(VL0);
1056       Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt());
1057       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
1058       E->VectorizedValue = NewPhi;
1059
1060       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1061         ValueList Operands;
1062         BasicBlock *IBB = PH->getIncomingBlock(i);
1063
1064         // Prepare the operand vector.
1065         for (unsigned j = 0; j < E->Scalars.size(); ++j)
1066           Operands.push_back(cast<PHINode>(E->Scalars[j])->
1067                              getIncomingValueForBlock(IBB));
1068
1069         Builder.SetInsertPoint(IBB->getTerminator());
1070         Value *Vec = vectorizeTree(Operands);
1071         NewPhi->addIncoming(Vec, IBB);
1072       }
1073
1074       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
1075              "Invalid number of incoming values");
1076       return NewPhi;
1077     }
1078
1079     case Instruction::ExtractElement: {
1080       if (CanReuseExtract(E->Scalars)) {
1081         Value *V = VL0->getOperand(0);
1082         E->VectorizedValue = V;
1083         return V;
1084       }
1085       return Gather(E->Scalars, VecTy);
1086     }
1087     case Instruction::ZExt:
1088     case Instruction::SExt:
1089     case Instruction::FPToUI:
1090     case Instruction::FPToSI:
1091     case Instruction::FPExt:
1092     case Instruction::PtrToInt:
1093     case Instruction::IntToPtr:
1094     case Instruction::SIToFP:
1095     case Instruction::UIToFP:
1096     case Instruction::Trunc:
1097     case Instruction::FPTrunc:
1098     case Instruction::BitCast: {
1099       ValueList INVL;
1100       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1101         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1102
1103       Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1104       Value *InVec = vectorizeTree(INVL);
1105       CastInst *CI = dyn_cast<CastInst>(VL0);
1106       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
1107       E->VectorizedValue = V;
1108       return V;
1109     }
1110     case Instruction::FCmp:
1111     case Instruction::ICmp: {
1112       ValueList LHSV, RHSV;
1113       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1114         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1115         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1116       }
1117
1118       Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1119       Value *L = vectorizeTree(LHSV);
1120       Value *R = vectorizeTree(RHSV);
1121       Value *V;
1122
1123       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1124       if (Opcode == Instruction::FCmp)
1125         V = Builder.CreateFCmp(P0, L, R);
1126       else
1127         V = Builder.CreateICmp(P0, L, R);
1128
1129       E->VectorizedValue = V;
1130       return V;
1131     }
1132     case Instruction::Select: {
1133       ValueList TrueVec, FalseVec, CondVec;
1134       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1135         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1136         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1137         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
1138       }
1139
1140       Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1141       Value *Cond = vectorizeTree(CondVec);
1142       Value *True = vectorizeTree(TrueVec);
1143       Value *False = vectorizeTree(FalseVec);
1144       Value *V = Builder.CreateSelect(Cond, True, False);
1145       E->VectorizedValue = V;
1146       return V;
1147     }
1148     case Instruction::Add:
1149     case Instruction::FAdd:
1150     case Instruction::Sub:
1151     case Instruction::FSub:
1152     case Instruction::Mul:
1153     case Instruction::FMul:
1154     case Instruction::UDiv:
1155     case Instruction::SDiv:
1156     case Instruction::FDiv:
1157     case Instruction::URem:
1158     case Instruction::SRem:
1159     case Instruction::FRem:
1160     case Instruction::Shl:
1161     case Instruction::LShr:
1162     case Instruction::AShr:
1163     case Instruction::And:
1164     case Instruction::Or:
1165     case Instruction::Xor: {
1166       ValueList LHSVL, RHSVL;
1167       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
1168         LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
1169         RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
1170       }
1171
1172       Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1173       Value *LHS = vectorizeTree(LHSVL);
1174       Value *RHS = vectorizeTree(RHSVL);
1175
1176       if (LHS == RHS && isa<Instruction>(LHS)) {
1177         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
1178       }
1179
1180       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
1181       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
1182       E->VectorizedValue = V;
1183       return V;
1184     }
1185     case Instruction::Load: {
1186       // Loads are inserted at the head of the tree because we don't want to
1187       // sink them all the way down past store instructions.
1188       Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1189       LoadInst *LI = cast<LoadInst>(VL0);
1190       Value *VecPtr =
1191       Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo());
1192       unsigned Alignment = LI->getAlignment();
1193       LI = Builder.CreateLoad(VecPtr);
1194       LI->setAlignment(Alignment);
1195       E->VectorizedValue = LI;
1196       return LI;
1197     }
1198     case Instruction::Store: {
1199       StoreInst *SI = cast<StoreInst>(VL0);
1200       unsigned Alignment = SI->getAlignment();
1201
1202       ValueList ValueOp;
1203       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
1204         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
1205
1206       Builder.SetInsertPoint(getLastInstruction(E->Scalars));
1207       Value *VecValue = vectorizeTree(ValueOp);
1208       Value *VecPtr =
1209       Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo());
1210       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
1211       S->setAlignment(Alignment);
1212       E->VectorizedValue = S;
1213       return S;
1214     }
1215     default:
1216     llvm_unreachable("unknown inst");
1217   }
1218   return 0;
1219 }
1220
1221 void BoUpSLP::vectorizeTree() {
1222   Builder.SetInsertPoint(F->getEntryBlock().begin());
1223   vectorizeTree(&VectorizableTree[0]);
1224
1225   // For each vectorized value:
1226   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
1227     TreeEntry *Entry = &VectorizableTree[EIdx];
1228
1229     // For each lane:
1230     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1231       Value *Scalar = Entry->Scalars[Lane];
1232
1233       // No need to handle users of gathered values.
1234       if (Entry->NeedToGather)
1235         continue;
1236
1237       Value *Vec = Entry->VectorizedValue;
1238       assert(Vec && "Can't find vectorizable value");
1239
1240       SmallVector<User*, 16> Users(Scalar->use_begin(), Scalar->use_end());
1241
1242       for (SmallVector<User*, 16>::iterator User = Users.begin(),
1243            UE = Users.end(); User != UE; ++User) {
1244         DEBUG(dbgs() << "SLP: \tupdating user  " << **User << ".\n");
1245
1246         bool Gathered = MustGather.count(*User);
1247
1248         // Skip in-tree scalars that become vectors.
1249         if (ScalarToTreeEntry.count(*User) && !Gathered) {
1250           DEBUG(dbgs() << "SLP: \tUser will be removed soon:" <<
1251                 **User << ".\n");
1252           int Idx = ScalarToTreeEntry[*User]; (void) Idx;
1253           assert(!VectorizableTree[Idx].NeedToGather && "bad state ?");
1254           continue;
1255         }
1256
1257         if (!isa<Instruction>(*User))
1258           continue;
1259
1260         // Generate extracts for out-of-tree users.
1261         // Find the insertion point for the extractelement lane.
1262         Instruction *Loc = 0;
1263         if (PHINode *PN = dyn_cast<PHINode>(Vec)) {
1264           Loc = PN->getParent()->getFirstInsertionPt();
1265         } else if (Instruction *Iv = dyn_cast<Instruction>(Vec)){
1266           Loc = ++((BasicBlock::iterator)*Iv);
1267         } else {
1268           Loc = F->getEntryBlock().begin();
1269         }
1270
1271         Builder.SetInsertPoint(Loc);
1272         Value *Ex = Builder.CreateExtractElement(Vec, Builder.getInt32(Lane));
1273         (*User)->replaceUsesOfWith(Scalar, Ex);
1274         DEBUG(dbgs() << "SLP: \tupdated user:" << **User << ".\n");
1275       }
1276
1277       Type *Ty = Scalar->getType();
1278       if (!Ty->isVoidTy()) {
1279         for (Value::use_iterator User = Scalar->use_begin(), UE = Scalar->use_end();
1280              User != UE; ++User) {
1281           DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n");
1282           assert(!MustGather.count(*User) &&
1283                  "Replacing gathered value with undef");
1284           assert(ScalarToTreeEntry.count(*User) &&
1285                  "Replacing out-of-tree value with undef");
1286         }
1287         Value *Undef = UndefValue::get(Ty);
1288         Scalar->replaceAllUsesWith(Undef);
1289       }
1290       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
1291       cast<Instruction>(Scalar)->eraseFromParent();
1292     }
1293   }
1294
1295   for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) {
1296     BlocksNumbers[it].forget();
1297   }
1298   Builder.ClearInsertionPoint();
1299 }
1300
1301 void BoUpSLP::optimizeGatherSequence() {
1302   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
1303         << " gather sequences instructions.\n");
1304   // LICM InsertElementInst sequences.
1305   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
1306        e = GatherSeq.end(); it != e; ++it) {
1307     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
1308
1309     if (!Insert)
1310       continue;
1311
1312     // Check if this block is inside a loop.
1313     Loop *L = LI->getLoopFor(Insert->getParent());
1314     if (!L)
1315       continue;
1316
1317     // Check if it has a preheader.
1318     BasicBlock *PreHeader = L->getLoopPreheader();
1319     if (!PreHeader)
1320       continue;
1321
1322     // If the vector or the element that we insert into it are
1323     // instructions that are defined in this basic block then we can't
1324     // hoist this instruction.
1325     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
1326     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
1327     if (CurrVec && L->contains(CurrVec))
1328       continue;
1329     if (NewElem && L->contains(NewElem))
1330       continue;
1331
1332     // We can hoist this instruction. Move it to the pre-header.
1333     Insert->moveBefore(PreHeader->getTerminator());
1334   }
1335
1336   // Perform O(N^2) search over the gather sequences and merge identical
1337   // instructions. TODO: We can further optimize this scan if we split the
1338   // instructions into different buckets based on the insert lane.
1339   SmallPtrSet<Instruction*, 16> Visited;
1340   SmallVector<Instruction*, 16> ToRemove;
1341   ReversePostOrderTraversal<Function*> RPOT(F);
1342   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
1343        E = RPOT.end(); I != E; ++I) {
1344     BasicBlock *BB = *I;
1345     // For all instructions in the function:
1346     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1347       InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
1348       if (!Insert || !GatherSeq.count(Insert))
1349         continue;
1350
1351       // Check if we can replace this instruction with any of the
1352       // visited instructions.
1353       for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(),
1354            ve = Visited.end(); v != ve; ++v) {
1355         if (Insert->isIdenticalTo(*v) &&
1356             DT->dominates((*v)->getParent(), Insert->getParent())) {
1357           Insert->replaceAllUsesWith(*v);
1358           ToRemove.push_back(Insert);
1359           Insert = 0;
1360           break;
1361         }
1362       }
1363       if (Insert)
1364         Visited.insert(Insert);
1365     }
1366   }
1367
1368   // Erase all of the instructions that we RAUWed.
1369   for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(),
1370        ve = ToRemove.end(); v != ve; ++v) {
1371     assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses");
1372     (*v)->eraseFromParent();
1373   }
1374 }
1375
1376 /// The SLPVectorizer Pass.
1377 struct SLPVectorizer : public FunctionPass {
1378   typedef SmallVector<StoreInst *, 8> StoreList;
1379   typedef MapVector<Value *, StoreList> StoreListMap;
1380
1381   /// Pass identification, replacement for typeid
1382   static char ID;
1383
1384   explicit SLPVectorizer() : FunctionPass(ID) {
1385     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
1386   }
1387
1388   ScalarEvolution *SE;
1389   DataLayout *DL;
1390   TargetTransformInfo *TTI;
1391   AliasAnalysis *AA;
1392   LoopInfo *LI;
1393   DominatorTree *DT;
1394
1395   virtual bool runOnFunction(Function &F) {
1396     SE = &getAnalysis<ScalarEvolution>();
1397     DL = getAnalysisIfAvailable<DataLayout>();
1398     TTI = &getAnalysis<TargetTransformInfo>();
1399     AA = &getAnalysis<AliasAnalysis>();
1400     LI = &getAnalysis<LoopInfo>();
1401     DT = &getAnalysis<DominatorTree>();
1402
1403     StoreRefs.clear();
1404     bool Changed = false;
1405
1406     // Must have DataLayout. We can't require it because some tests run w/o
1407     // triple.
1408     if (!DL)
1409       return false;
1410
1411     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
1412
1413     // Use the bollom up slp vectorizer to construct chains that start with
1414     // he store instructions.
1415     BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT);
1416
1417     // Scan the blocks in the function in post order.
1418     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
1419          e = po_end(&F.getEntryBlock()); it != e; ++it) {
1420       BasicBlock *BB = *it;
1421
1422       // Vectorize trees that end at reductions.
1423       Changed |= vectorizeChainsInBlock(BB, R);
1424
1425       // Vectorize trees that end at stores.
1426       if (unsigned count = collectStores(BB, R)) {
1427         (void)count;
1428         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
1429         Changed |= vectorizeStoreChains(R);
1430       }
1431     }
1432
1433     if (Changed) {
1434       R.optimizeGatherSequence();
1435       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
1436       DEBUG(verifyFunction(F));
1437     }
1438     return Changed;
1439   }
1440
1441   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1442     FunctionPass::getAnalysisUsage(AU);
1443     AU.addRequired<ScalarEvolution>();
1444     AU.addRequired<AliasAnalysis>();
1445     AU.addRequired<TargetTransformInfo>();
1446     AU.addRequired<LoopInfo>();
1447     AU.addRequired<DominatorTree>();
1448     AU.addPreserved<LoopInfo>();
1449     AU.addPreserved<DominatorTree>();
1450     AU.setPreservesCFG();
1451   }
1452
1453 private:
1454
1455   /// \brief Collect memory references and sort them according to their base
1456   /// object. We sort the stores to their base objects to reduce the cost of the
1457   /// quadratic search on the stores. TODO: We can further reduce this cost
1458   /// if we flush the chain creation every time we run into a memory barrier.
1459   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
1460
1461   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
1462   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
1463
1464   /// \brief Try to vectorize a list of operands. If \p NeedExtracts is true
1465   /// then we calculate the cost of extracting the scalars from the vector.
1466   /// \returns true if a value was vectorized.
1467   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, bool NeedExtracts);
1468
1469   /// \brief Try to vectorize a chain that may start at the operands of \V;
1470   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
1471
1472   /// \brief Vectorize the stores that were collected in StoreRefs.
1473   bool vectorizeStoreChains(BoUpSLP &R);
1474
1475   /// \brief Scan the basic block and look for patterns that are likely to start
1476   /// a vectorization chain.
1477   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
1478
1479   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
1480                            BoUpSLP &R);
1481
1482   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
1483                        BoUpSLP &R);
1484 private:
1485   StoreListMap StoreRefs;
1486 };
1487
1488 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
1489                                           int CostThreshold, BoUpSLP &R) {
1490   unsigned ChainLen = Chain.size();
1491   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
1492         << "\n");
1493   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
1494   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
1495   unsigned VF = MinVecRegSize / Sz;
1496
1497   if (!isPowerOf2_32(Sz) || VF < 2)
1498     return false;
1499
1500   bool Changed = false;
1501   // Look for profitable vectorizable trees at all offsets, starting at zero.
1502   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
1503     if (i + VF > e)
1504       break;
1505     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
1506           << "\n");
1507     ArrayRef<Value *> Operands = Chain.slice(i, VF);
1508
1509     R.buildTree(Operands);
1510
1511     int Cost = R.getTreeCost();
1512
1513     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
1514     if (Cost < CostThreshold) {
1515       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
1516       R.vectorizeTree();
1517
1518       // Move to the next bundle.
1519       i += VF - 1;
1520       Changed = true;
1521     }
1522   }
1523
1524   if (Changed || ChainLen > VF)
1525     return Changed;
1526
1527   // Handle short chains. This helps us catch types such as <3 x float> that
1528   // are smaller than vector size.
1529   R.buildTree(Chain);
1530
1531   int Cost = R.getTreeCost();
1532
1533   if (Cost < CostThreshold) {
1534     DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost
1535           << " for size = " << ChainLen << "\n");
1536     R.vectorizeTree();
1537     return true;
1538   }
1539
1540   return false;
1541 }
1542
1543 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
1544                                       int costThreshold, BoUpSLP &R) {
1545   SetVector<Value *> Heads, Tails;
1546   SmallDenseMap<Value *, Value *> ConsecutiveChain;
1547
1548   // We may run into multiple chains that merge into a single chain. We mark the
1549   // stores that we vectorized so that we don't visit the same store twice.
1550   BoUpSLP::ValueSet VectorizedStores;
1551   bool Changed = false;
1552
1553   // Do a quadratic search on all of the given stores and find
1554   // all of the pairs of loads that follow each other.
1555   for (unsigned i = 0, e = Stores.size(); i < e; ++i)
1556     for (unsigned j = 0; j < e; ++j) {
1557       if (i == j)
1558         continue;
1559
1560       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
1561         Tails.insert(Stores[j]);
1562         Heads.insert(Stores[i]);
1563         ConsecutiveChain[Stores[i]] = Stores[j];
1564       }
1565     }
1566
1567   // For stores that start but don't end a link in the chain:
1568   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
1569        it != e; ++it) {
1570     if (Tails.count(*it))
1571       continue;
1572
1573     // We found a store instr that starts a chain. Now follow the chain and try
1574     // to vectorize it.
1575     BoUpSLP::ValueList Operands;
1576     Value *I = *it;
1577     // Collect the chain into a list.
1578     while (Tails.count(I) || Heads.count(I)) {
1579       if (VectorizedStores.count(I))
1580         break;
1581       Operands.push_back(I);
1582       // Move to the next value in the chain.
1583       I = ConsecutiveChain[I];
1584     }
1585
1586     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
1587
1588     // Mark the vectorized stores so that we don't vectorize them again.
1589     if (Vectorized)
1590       VectorizedStores.insert(Operands.begin(), Operands.end());
1591     Changed |= Vectorized;
1592   }
1593
1594   return Changed;
1595 }
1596
1597
1598 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
1599   unsigned count = 0;
1600   StoreRefs.clear();
1601   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1602     StoreInst *SI = dyn_cast<StoreInst>(it);
1603     if (!SI)
1604       continue;
1605
1606     // Check that the pointer points to scalars.
1607     Type *Ty = SI->getValueOperand()->getType();
1608     if (Ty->isAggregateType() || Ty->isVectorTy())
1609       return 0;
1610
1611     // Find the base of the GEP.
1612     Value *Ptr = SI->getPointerOperand();
1613     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
1614       Ptr = GEP->getPointerOperand();
1615
1616     // Save the store locations.
1617     StoreRefs[Ptr].push_back(SI);
1618     count++;
1619   }
1620   return count;
1621 }
1622
1623 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
1624   if (!A || !B)
1625     return false;
1626   Value *VL[] = { A, B };
1627   return tryToVectorizeList(VL, R, true);
1628 }
1629
1630 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
1631                                        bool NeedExtracts) {
1632   if (VL.size() < 2)
1633     return false;
1634
1635   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
1636
1637   // Check that all of the parts are scalar instructions of the same type.
1638   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
1639   if (!I0)
1640     return 0;
1641
1642   unsigned Opcode0 = I0->getOpcode();
1643
1644   for (int i = 0, e = VL.size(); i < e; ++i) {
1645     Type *Ty = VL[i]->getType();
1646     if (Ty->isAggregateType() || Ty->isVectorTy())
1647       return 0;
1648     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
1649     if (!Inst || Inst->getOpcode() != Opcode0)
1650       return 0;
1651   }
1652
1653   R.buildTree(VL);
1654   int Cost = R.getTreeCost();
1655
1656   int ExtrCost = NeedExtracts ? R.getGatherCost(VL) : 0;
1657   DEBUG(dbgs() << "SLP: Cost of pair:" << Cost
1658                << " Cost of extract:" << ExtrCost << ".\n");
1659   if ((Cost + ExtrCost) >= -SLPCostThreshold)
1660     return false;
1661   DEBUG(dbgs() << "SLP: Vectorizing pair.\n");
1662   R.vectorizeTree();
1663   return true;
1664 }
1665
1666 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
1667   if (!V)
1668     return false;
1669
1670   // Try to vectorize V.
1671   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
1672     return true;
1673
1674   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
1675   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
1676   // Try to skip B.
1677   if (B && B->hasOneUse()) {
1678     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
1679     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
1680     if (tryToVectorizePair(A, B0, R)) {
1681       B->moveBefore(V);
1682       return true;
1683     }
1684     if (tryToVectorizePair(A, B1, R)) {
1685       B->moveBefore(V);
1686       return true;
1687     }
1688   }
1689
1690   // Try to skip A.
1691   if (A && A->hasOneUse()) {
1692     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
1693     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
1694     if (tryToVectorizePair(A0, B, R)) {
1695       A->moveBefore(V);
1696       return true;
1697     }
1698     if (tryToVectorizePair(A1, B, R)) {
1699       A->moveBefore(V);
1700       return true;
1701     }
1702   }
1703   return 0;
1704 }
1705
1706 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
1707   bool Changed = false;
1708   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1709     if (isa<DbgInfoIntrinsic>(it))
1710       continue;
1711
1712     // Try to vectorize reductions that use PHINodes.
1713     if (PHINode *P = dyn_cast<PHINode>(it)) {
1714       // Check that the PHI is a reduction PHI.
1715       if (P->getNumIncomingValues() != 2)
1716         return Changed;
1717       Value *Rdx =
1718           (P->getIncomingBlock(0) == BB
1719                ? (P->getIncomingValue(0))
1720                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0));
1721       // Check if this is a Binary Operator.
1722       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
1723       if (!BI)
1724         continue;
1725
1726       Value *Inst = BI->getOperand(0);
1727       if (Inst == P)
1728         Inst = BI->getOperand(1);
1729
1730       Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R);
1731       continue;
1732     }
1733
1734     // Try to vectorize trees that start at compare instructions.
1735     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
1736       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
1737         Changed |= true;
1738         continue;
1739       }
1740       for (int i = 0; i < 2; ++i)
1741         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i)))
1742           Changed |=
1743               tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R);
1744       continue;
1745     }
1746   }
1747
1748   // Scan the PHINodes in our successors in search for pairing hints.
1749   for (succ_iterator it = succ_begin(BB), e = succ_end(BB); it != e; ++it) {
1750     BasicBlock *Succ = *it;
1751     SmallVector<Value *, 4> Incoming;
1752
1753     // Collect the incoming values from the PHIs.
1754     for (BasicBlock::iterator instr = Succ->begin(), ie = Succ->end();
1755          instr != ie; ++instr) {
1756       PHINode *P = dyn_cast<PHINode>(instr);
1757
1758       if (!P)
1759         break;
1760
1761       Value *V = P->getIncomingValueForBlock(BB);
1762       if (Instruction *I = dyn_cast<Instruction>(V))
1763         if (I->getParent() == BB)
1764           Incoming.push_back(I);
1765     }
1766
1767     if (Incoming.size() > 1)
1768       Changed |= tryToVectorizeList(Incoming, R, true);
1769   }
1770
1771   return Changed;
1772 }
1773
1774 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
1775   bool Changed = false;
1776   // Attempt to sort and vectorize each of the store-groups.
1777   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
1778        it != e; ++it) {
1779     if (it->second.size() < 2)
1780       continue;
1781
1782     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
1783                  << it->second.size() << ".\n");
1784
1785     Changed |= vectorizeStores(it->second, -SLPCostThreshold, R);
1786   }
1787   return Changed;
1788 }
1789
1790 } // end anonymous namespace
1791
1792 char SLPVectorizer::ID = 0;
1793 static const char lv_name[] = "SLP Vectorizer";
1794 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
1795 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1796 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1797 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1798 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1799 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
1800
1801 namespace llvm {
1802 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
1803 }