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