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