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