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