LoopVectorize: Fix a bug in the initialization of reduction variables. AND needs...
[oota-llvm.git] / lib / Transforms / Vectorize / LoopVectorize.cpp
1 //===- LoopVectorize.cpp - A Loop 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 //
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR. Legalization of the IR is done
12 // in the codegen. However, the vectorizes uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
14 //
15 // The loop vectorizer combines consecutive loop iteration into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
18 //
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 //    of the vectorization.
23 // 3. SingleBlockLoopVectorizer - A unit that performs the actual
24 //    widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 //    of vectorization. It decides on the optimal vector width, which
27 //    can be one, if vectorization is not profitable.
28 //===----------------------------------------------------------------------===//
29 //
30 // The reduction-variable vectorization is based on the paper:
31 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
32 //
33 // Variable uniformity checks are inspired by:
34 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
35 //
36 // Other ideas/concepts are from:
37 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
38 //
39 //===----------------------------------------------------------------------===//
40 #define LV_NAME "loop-vectorize"
41 #define DEBUG_TYPE LV_NAME
42 #include "llvm/Constants.h"
43 #include "llvm/DerivedTypes.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/LLVMContext.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Analysis/LoopPass.h"
48 #include "llvm/Value.h"
49 #include "llvm/Function.h"
50 #include "llvm/Analysis/Verifier.h"
51 #include "llvm/Module.h"
52 #include "llvm/Type.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/ScalarEvolution.h"
58 #include "llvm/Analysis/Dominators.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/Analysis/ScalarEvolutionExpander.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/Analysis/ValueTracking.h"
63 #include "llvm/Transforms/Scalar.h"
64 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
65 #include "llvm/TargetTransformInfo.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/DataLayout.h"
70 #include "llvm/Transforms/Utils/Local.h"
71 #include <algorithm>
72 using namespace llvm;
73
74 static cl::opt<unsigned>
75 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
76           cl::desc("Set the default vectorization width. Zero is autoselect."));
77
78 namespace {
79
80 // Forward declarations.
81 class LoopVectorizationLegality;
82 class LoopVectorizationCostModel;
83
84 /// SingleBlockLoopVectorizer vectorizes loops which contain only one basic
85 /// block to a specified vectorization factor (VF).
86 /// This class performs the widening of scalars into vectors, or multiple
87 /// scalars. This class also implements the following features:
88 /// * It inserts an epilogue loop for handling loops that don't have iteration
89 ///   counts that are known to be a multiple of the vectorization factor.
90 /// * It handles the code generation for reduction variables.
91 /// * Scalarization (implementation using scalars) of un-vectorizable
92 ///   instructions.
93 /// SingleBlockLoopVectorizer does not perform any vectorization-legality
94 /// checks, and relies on the caller to check for the different legality
95 /// aspects. The SingleBlockLoopVectorizer relies on the
96 /// LoopVectorizationLegality class to provide information about the induction
97 /// and reduction variables that were found to a given vectorization factor.
98 class SingleBlockLoopVectorizer {
99 public:
100   /// Ctor.
101   SingleBlockLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
102                             DominatorTree *dt, LPPassManager *Lpm,
103                             unsigned VecWidth):
104   OrigLoop(Orig), SE(Se), LI(Li), DT(dt), LPM(Lpm), VF(VecWidth),
105   Builder(Se->getContext()), Induction(0), OldInduction(0) { }
106
107   // Perform the actual loop widening (vectorization).
108   void vectorize(LoopVectorizationLegality *Legal) {
109     ///Create a new empty loop. Unlink the old loop and connect the new one.
110     createEmptyLoop(Legal);
111     /// Widen each instruction in the old loop to a new one in the new loop.
112     /// Use the Legality module to find the induction and reduction variables.
113     vectorizeLoop(Legal);
114     // register the new loop.
115     updateAnalysis();
116  }
117
118 private:
119   /// Create an empty loop, based on the loop ranges of the old loop.
120   void createEmptyLoop(LoopVectorizationLegality *Legal);
121   /// Copy and widen the instructions from the old loop.
122   void vectorizeLoop(LoopVectorizationLegality *Legal);
123   /// Insert the new loop to the loop hierarchy and pass manager.
124   void updateAnalysis();
125
126   /// This instruction is un-vectorizable. Implement it as a sequence
127   /// of scalars.
128   void scalarizeInstruction(Instruction *Instr);
129
130   /// Create a broadcast instruction. This method generates a broadcast
131   /// instruction (shuffle) for loop invariant values and for the induction
132   /// value. If this is the induction variable then we extend it to N, N+1, ...
133   /// this is needed because each iteration in the loop corresponds to a SIMD
134   /// element.
135   Value *getBroadcastInstrs(Value *V);
136
137   /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
138   /// for each element in the vector. Starting from zero.
139   Value *getConsecutiveVector(Value* Val);
140
141   /// When we go over instructions in the basic block we rely on previous
142   /// values within the current basic block or on loop invariant values.
143   /// When we widen (vectorize) values we place them in the map. If the values
144   /// are not within the map, they have to be loop invariant, so we simply
145   /// broadcast them into a vector.
146   Value *getVectorValue(Value *V);
147
148   /// Get a uniform vector of constant integers. We use this to get
149   /// vectors of ones and zeros for the reduction code.
150   Constant* getUniformVector(unsigned Val, Type* ScalarTy);
151
152   typedef DenseMap<Value*, Value*> ValueMap;
153
154   /// The original loop.
155   Loop *OrigLoop;
156   // Scev analysis to use.
157   ScalarEvolution *SE;
158   // Loop Info.
159   LoopInfo *LI;
160   // Dominator Tree.
161   DominatorTree *DT;
162   // Loop Pass Manager;
163   LPPassManager *LPM;
164   // The vectorization factor to use.
165   unsigned VF;
166
167   // The builder that we use
168   IRBuilder<> Builder;
169
170   // --- Vectorization state ---
171
172   /// The vector-loop preheader.
173   BasicBlock *LoopVectorPreHeader;
174   /// The scalar-loop preheader.
175   BasicBlock *LoopScalarPreHeader;
176   /// Middle Block between the vector and the scalar.
177   BasicBlock *LoopMiddleBlock;
178   ///The ExitBlock of the scalar loop.
179   BasicBlock *LoopExitBlock;
180   ///The vector loop body.
181   BasicBlock *LoopVectorBody;
182   ///The scalar loop body.
183   BasicBlock *LoopScalarBody;
184   ///The first bypass block.
185   BasicBlock *LoopBypassBlock;
186
187   /// The new Induction variable which was added to the new block.
188   PHINode *Induction;
189   /// The induction variable of the old basic block.
190   PHINode *OldInduction;
191   // Maps scalars to widened vectors.
192   ValueMap WidenMap;
193 };
194
195 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
196 /// to what vectorization factor.
197 /// This class does not look at the profitability of vectorization, only the
198 /// legality. This class has two main kinds of checks:
199 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
200 ///   will change the order of memory accesses in a way that will change the
201 ///   correctness of the program.
202 /// * Scalars checks - The code in canVectorizeBlock checks for a number
203 ///   of different conditions, such as the availability of a single induction
204 ///   variable, that all types are supported and vectorize-able, etc.
205 /// This code reflects the capabilities of SingleBlockLoopVectorizer.
206 /// This class is also used by SingleBlockLoopVectorizer for identifying
207 /// induction variable and the different reduction variables.
208 class LoopVectorizationLegality {
209 public:
210   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
211   TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
212
213   /// This represents the kinds of reductions that we support.
214   enum ReductionKind {
215     NoReduction = -1, /// Not a reduction.
216     IntegerAdd  = 0,  /// Sum of numbers.
217     IntegerMult = 1,  /// Product of numbers.
218     IntegerOr   = 2,  /// Bitwise or logical OR of numbers.
219     IntegerAnd  = 3,  /// Bitwise or logical AND of numbers.
220     IntegerXor  = 4   /// Bitwise or logical XOR of numbers.
221   };
222
223   /// This POD struct holds information about reduction variables.
224   struct ReductionDescriptor {
225     // Default C'tor
226     ReductionDescriptor():
227     StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
228
229     // C'tor.
230     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
231     StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
232
233     // The starting value of the reduction.
234     // It does not have to be zero!
235     Value *StartValue;
236     // The instruction who's value is used outside the loop.
237     Instruction *LoopExitInstr;
238     // The kind of the reduction.
239     ReductionKind Kind;
240   };
241
242   /// ReductionList contains the reduction descriptors for all
243   /// of the reductions that were found in the loop.
244   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
245
246   /// Returns true if it is legal to vectorize this loop.
247   /// This does not mean that it is profitable to vectorize this
248   /// loop, only that it is legal to do so.
249   bool canVectorize();
250
251   /// Returns the Induction variable.
252   PHINode *getInduction() {return Induction;}
253
254   /// Returns the reduction variables found in the loop.
255   ReductionList *getReductionVars() { return &Reductions; }
256
257   /// Check if the pointer returned by this GEP is consecutive
258   /// when the index is vectorized. This happens when the last
259   /// index of the GEP is consecutive, like the induction variable.
260   /// This check allows us to vectorize A[idx] into a wide load/store.
261   bool isConsecutiveGep(Value *Ptr);
262
263   /// Returns true if this instruction will remain scalar after vectorization.
264   bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
265
266 private:
267   /// Check if a single basic block loop is vectorizable.
268   /// At this point we know that this is a loop with a constant trip count
269   /// and we only need to check individual instructions.
270   bool canVectorizeBlock(BasicBlock &BB);
271
272   /// When we vectorize loops we may change the order in which
273   /// we read and write from memory. This method checks if it is
274   /// legal to vectorize the code, considering only memory constrains.
275   /// Returns true if BB is vectorizable
276   bool canVectorizeMemory(BasicBlock &BB);
277
278   /// Returns True, if 'Phi' is the kind of reduction variable for type
279   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
280   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
281   /// Returns true if the instruction I can be a reduction variable of type
282   /// 'Kind'.
283   bool isReductionInstr(Instruction *I, ReductionKind Kind);
284   /// Returns True, if 'Phi' is an induction variable.
285   bool isInductionVariable(PHINode *Phi);
286
287   /// The loop that we evaluate.
288   Loop *TheLoop;
289   /// Scev analysis.
290   ScalarEvolution *SE;
291   /// DataLayout analysis.
292   DataLayout *DL;
293
294   //  ---  vectorization state --- //
295
296   /// Holds the induction variable.
297   PHINode *Induction;
298   /// Holds the reduction variables.
299   ReductionList Reductions;
300   /// Allowed outside users. This holds the reduction
301   /// vars which can be accessed from outside the loop.
302   SmallPtrSet<Value*, 4> AllowedExit;
303   /// This set holds the variables which are known to be uniform after
304   /// vectorization.
305   SmallPtrSet<Instruction*, 4> Uniforms;
306 };
307
308 /// LoopVectorizationCostModel - estimates the expected speedups due to
309 /// vectorization.
310 /// In many cases vectorization is not profitable. This can happen because
311 /// of a number of reasons. In this class we mainly attempt to predict
312 /// the expected speedup/slowdowns due to the supported instruction set.
313 /// We use the VectorTargetTransformInfo to query the different backends
314 /// for the cost of different operations.
315 class LoopVectorizationCostModel {
316 public:
317   /// C'tor.
318   LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
319                              LoopVectorizationLegality *Leg,
320                              const VectorTargetTransformInfo *Vtti):
321   TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
322
323   /// Returns the most profitable vectorization factor for the loop that is
324   /// smaller or equal to the VF argument. This method checks every power
325   /// of two up to VF.
326   unsigned findBestVectorizationFactor(unsigned VF = 8);
327
328 private:
329   /// Returns the expected execution cost. The unit of the cost does
330   /// not matter because we use the 'cost' units to compare different
331   /// vector widths. The cost that is returned is *not* normalized by
332   /// the factor width.
333   unsigned expectedCost(unsigned VF);
334
335   /// Returns the execution time cost of an instruction for a given vector
336   /// width. Vector width of one means scalar.
337   unsigned getInstructionCost(Instruction *I, unsigned VF);
338
339   /// A helper function for converting Scalar types to vector types.
340   /// If the incoming type is void, we return void. If the VF is 1, we return
341   /// the scalar type.
342   static Type* ToVectorTy(Type *Scalar, unsigned VF);
343
344   /// The loop that we evaluate.
345   Loop *TheLoop;
346   /// Scev analysis.
347   ScalarEvolution *SE;
348
349   /// Vectorization legality.
350   LoopVectorizationLegality *Legal;
351   /// Vector target information.
352   const VectorTargetTransformInfo *VTTI;
353 };
354
355 struct LoopVectorize : public LoopPass {
356   static char ID; // Pass identification, replacement for typeid
357
358   LoopVectorize() : LoopPass(ID) {
359     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
360   }
361
362   ScalarEvolution *SE;
363   DataLayout *DL;
364   LoopInfo *LI;
365   TargetTransformInfo *TTI;
366   DominatorTree *DT;
367
368   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
369     // We only vectorize innermost loops.
370     if (!L->empty())
371       return false;
372
373     SE = &getAnalysis<ScalarEvolution>();
374     DL = getAnalysisIfAvailable<DataLayout>();
375     LI = &getAnalysis<LoopInfo>();
376     TTI = getAnalysisIfAvailable<TargetTransformInfo>();
377     DT = &getAnalysis<DominatorTree>();
378
379     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
380           L->getHeader()->getParent()->getName() << "\"\n");
381
382     // Check if it is legal to vectorize the loop.
383     LoopVectorizationLegality LVL(L, SE, DL);
384     if (!LVL.canVectorize()) {
385       DEBUG(dbgs() << "LV: Not vectorizing.\n");
386       return false;
387     }
388
389     // Select the preffered vectorization factor.
390     unsigned VF = 1;
391     if (VectorizationFactor == 0) {
392       const VectorTargetTransformInfo *VTTI = 0;
393       if (TTI)
394         VTTI = TTI->getVectorTargetTransformInfo();
395       // Use the cost model.
396       LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
397       VF = CM.findBestVectorizationFactor();
398
399       if (VF == 1) {
400         DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
401         return false;
402       }
403
404     } else {
405       // Use the user command flag.
406       VF = VectorizationFactor;
407     }
408
409     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
410           L->getHeader()->getParent()->getParent()->getModuleIdentifier()<<
411           "\n");
412
413     // If we decided that it is *legal* to vectorizer the loop then do it.
414     SingleBlockLoopVectorizer LB(L, SE, LI, DT, &LPM, VF);
415     LB.vectorize(&LVL);
416
417     DEBUG(verifyFunction(*L->getHeader()->getParent()));
418     return true;
419   }
420
421   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
422     LoopPass::getAnalysisUsage(AU);
423     AU.addRequiredID(LoopSimplifyID);
424     AU.addRequiredID(LCSSAID);
425     AU.addRequired<LoopInfo>();
426     AU.addRequired<ScalarEvolution>();
427     AU.addRequired<DominatorTree>();
428     AU.addPreserved<LoopInfo>();
429     AU.addPreserved<DominatorTree>();
430   }
431
432 };
433
434 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
435   // Instructions that access the old induction variable
436   // actually want to get the new one.
437   if (V == OldInduction)
438     V = Induction;
439   // Create the types.
440   LLVMContext &C = V->getContext();
441   Type *VTy = VectorType::get(V->getType(), VF);
442   Type *I32 = IntegerType::getInt32Ty(C);
443   Constant *Zero = ConstantInt::get(I32, 0);
444   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
445   Value *UndefVal = UndefValue::get(VTy);
446   // Insert the value into a new vector.
447   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
448   // Broadcast the scalar into all locations in the vector.
449   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
450                                              "broadcast");
451   // We are accessing the induction variable. Make sure to promote the
452   // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
453   if (V == Induction)
454     return getConsecutiveVector(Shuf);
455   return Shuf;
456 }
457
458 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
459   assert(Val->getType()->isVectorTy() && "Must be a vector");
460   assert(Val->getType()->getScalarType()->isIntegerTy() &&
461          "Elem must be an integer");
462   // Create the types.
463   Type *ITy = Val->getType()->getScalarType();
464   VectorType *Ty = cast<VectorType>(Val->getType());
465   unsigned VLen = Ty->getNumElements();
466   SmallVector<Constant*, 8> Indices;
467
468   // Create a vector of consecutive numbers from zero to VF.
469   for (unsigned i = 0; i < VLen; ++i)
470     Indices.push_back(ConstantInt::get(ITy, i));
471
472   // Add the consecutive indices to the vector value.
473   Constant *Cv = ConstantVector::get(Indices);
474   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
475   return Builder.CreateAdd(Val, Cv, "induction");
476 }
477
478 bool LoopVectorizationLegality::isConsecutiveGep(Value *Ptr) {
479   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
480   if (!Gep)
481     return false;
482
483   unsigned NumOperands = Gep->getNumOperands();
484   Value *LastIndex = Gep->getOperand(NumOperands - 1);
485
486   // Check that all of the gep indices are uniform except for the last.
487   for (unsigned i = 0; i < NumOperands - 1; ++i)
488     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
489       return false;
490
491   // We can emit wide load/stores only of the last index is the induction
492   // variable.
493   const SCEV *Last = SE->getSCEV(LastIndex);
494   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
495     const SCEV *Step = AR->getStepRecurrence(*SE);
496
497     // The memory is consecutive because the last index is consecutive
498     // and all other indices are loop invariant.
499     if (Step->isOne())
500       return true;
501   }
502
503   return false;
504 }
505
506 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
507   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
508   // If we saved a vectorized copy of V, use it.
509   Value *&MapEntry = WidenMap[V];
510   if (MapEntry)
511     return MapEntry;
512
513   // Broadcast V and save the value for future uses.
514   Value *B = getBroadcastInstrs(V);
515   MapEntry = B;
516   return B;
517 }
518
519 Constant*
520 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
521   SmallVector<Constant*, 8> Indices;
522   // Create a vector of consecutive numbers from zero to VF.
523   for (unsigned i = 0; i < VF; ++i)
524     Indices.push_back(ConstantInt::get(ScalarTy, Val, true));
525
526   // Add the consecutive indices to the vector value.
527   return ConstantVector::get(Indices);
528 }
529
530 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
531   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
532   // Holds vector parameters or scalars, in case of uniform vals.
533   SmallVector<Value*, 8> Params;
534
535   // Find all of the vectorized parameters.
536   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
537     Value *SrcOp = Instr->getOperand(op);
538
539     // If we are accessing the old induction variable, use the new one.
540     if (SrcOp == OldInduction) {
541       Params.push_back(getBroadcastInstrs(Induction));
542       continue;
543     }
544
545     // Try using previously calculated values.
546     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
547
548     // If the src is an instruction that appeared earlier in the basic block
549     // then it should already be vectorized.
550     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
551       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
552       // The parameter is a vector value from earlier.
553       Params.push_back(WidenMap[SrcInst]);
554     } else {
555       // The parameter is a scalar from outside the loop. Maybe even a constant.
556       Params.push_back(SrcOp);
557     }
558   }
559
560   assert(Params.size() == Instr->getNumOperands() &&
561          "Invalid number of operands");
562
563   // Does this instruction return a value ?
564   bool IsVoidRetTy = Instr->getType()->isVoidTy();
565   Value *VecResults = 0;
566
567   // If we have a return value, create an empty vector. We place the scalarized
568   // instructions in this vector.
569   if (!IsVoidRetTy)
570     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
571
572   // For each scalar that we create:
573   for (unsigned i = 0; i < VF; ++i) {
574     Instruction *Cloned = Instr->clone();
575     if (!IsVoidRetTy)
576       Cloned->setName(Instr->getName() + ".cloned");
577     // Replace the operands of the cloned instrucions with extracted scalars.
578     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
579       Value *Op = Params[op];
580       // Param is a vector. Need to extract the right lane.
581       if (Op->getType()->isVectorTy())
582         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
583       Cloned->setOperand(op, Op);
584     }
585
586     // Place the cloned scalar in the new loop.
587     Builder.Insert(Cloned);
588
589     // If the original scalar returns a value we need to place it in a vector
590     // so that future users will be able to use it.
591     if (!IsVoidRetTy)
592       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
593                                                Builder.getInt32(i));
594   }
595
596   if (!IsVoidRetTy)
597     WidenMap[Instr] = VecResults;
598 }
599
600 void
601 SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
602   /*
603    In this function we generate a new loop. The new loop will contain
604    the vectorized instructions while the old loop will continue to run the
605    scalar remainder.
606
607     [ ] <-- vector loop bypass.
608   /  |
609  /   v
610 |   [ ]     <-- vector pre header.
611 |    |
612 |    v
613 |   [  ] \
614 |   [  ]_|   <-- vector loop.
615 |    |
616  \   v
617    >[ ]   <--- middle-block.
618   /  |
619  /   v
620 |   [ ]     <--- new preheader.
621 |    |
622 |    v
623 |   [ ] \
624 |   [ ]_|   <-- old scalar loop to handle remainder.
625  \   |
626   \  v
627    >[ ]     <-- exit block.
628    ...
629    */
630
631   // This is the original scalar-loop preheader.
632   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
633   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
634   assert(ExitBlock && "Must have an exit block");
635
636   assert(OrigLoop->getNumBlocks() == 1 && "Invalid loop");
637   assert(BypassBlock && "Invalid loop structure");
638
639   BasicBlock *VectorPH =
640       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
641   BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
642                                                  "vector.body");
643
644   BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
645                                                   "middle.block");
646   BasicBlock *ScalarPH =
647     MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
648                                  "scalar.preheader");
649   // Find the induction variable.
650   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
651   OldInduction = Legal->getInduction();
652   assert(OldInduction && "We must have a single phi node.");
653   Type *IdxTy = OldInduction->getType();
654
655   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
656   // inside the loop.
657   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
658
659   // Generate the induction variable.
660   Induction = Builder.CreatePHI(IdxTy, 2, "index");
661   Constant *Zero = ConstantInt::get(IdxTy, 0);
662   Constant *Step = ConstantInt::get(IdxTy, VF);
663
664   // Find the loop boundaries.
665   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getHeader());
666   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
667
668   // Get the total trip count from the count by adding 1.
669   ExitCount = SE->getAddExpr(ExitCount,
670                              SE->getConstant(ExitCount->getType(), 1));
671
672   // Expand the trip count and place the new instructions in the preheader.
673   // Notice that the pre-header does not change, only the loop body.
674   SCEVExpander Exp(*SE, "induction");
675   Instruction *Loc = BypassBlock->getTerminator();
676
677   // We may need to extend the index in case there is a type mismatch.
678   // We know that the count starts at zero and does not overflow.
679   // We are using Zext because it should be less expensive.
680   if (ExitCount->getType() != Induction->getType())
681     ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
682
683   // Count holds the overall loop count (N).
684   Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
685   // Now we need to generate the expression for N - (N % VF), which is
686   // the part that the vectorized body will execute.
687   Constant *CIVF = ConstantInt::get(IdxTy, VF);
688   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
689   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
690
691   // Now, compare the new count to zero. If it is zero, jump to the scalar part.
692   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
693                                CountRoundDown, ConstantInt::getNullValue(IdxTy),
694                                "cmp.zero", Loc);
695   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
696   // Remove the old terminator.
697   Loc->eraseFromParent();
698
699   // Add a check in the middle block to see if we have completed
700   // all of the iterations in the first vector loop.
701   // If (N - N%VF) == N, then we *don't* need to run the remainder.
702   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
703                                 CountRoundDown, "cmp.n",
704                                 MiddleBlock->getTerminator());
705
706   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
707   // Remove the old terminator.
708   MiddleBlock->getTerminator()->eraseFromParent();
709
710   // Create i+1 and fill the PHINode.
711   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
712   Induction->addIncoming(Zero, VectorPH);
713   Induction->addIncoming(NextIdx, VecBody);
714   // Create the compare.
715   Value *ICmp = Builder.CreateICmpEQ(NextIdx, CountRoundDown);
716   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
717
718   // Now we have two terminators. Remove the old one from the block.
719   VecBody->getTerminator()->eraseFromParent();
720
721   // Fix the scalar body iteration count.
722   unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
723   OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
724
725   // Get ready to start creating new instructions into the vectorized body.
726   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
727
728   // Register the new loop.
729   Loop* Lp = new Loop();
730   LPM->insertLoop(Lp, OrigLoop->getParentLoop());
731
732   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
733
734   Loop *ParentLoop = OrigLoop->getParentLoop();
735   if (ParentLoop) {
736     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
737     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
738     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
739   }
740
741   // Save the state.
742   LoopVectorPreHeader = VectorPH;
743   LoopScalarPreHeader = ScalarPH;
744   LoopMiddleBlock = MiddleBlock;
745   LoopExitBlock = ExitBlock;
746   LoopVectorBody = VecBody;
747   LoopScalarBody = OldBasicBlock;
748   LoopBypassBlock = BypassBlock;
749 }
750
751
752 static unsigned
753 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
754   switch (K) {
755   case LoopVectorizationLegality::IntegerXor:
756   case LoopVectorizationLegality::IntegerAdd:
757   case LoopVectorizationLegality::IntegerOr:
758     return 0;
759   case LoopVectorizationLegality::IntegerMult:
760     return 1;
761   case LoopVectorizationLegality::IntegerAnd:
762     return -1;
763   default:
764     llvm_unreachable("Unknown reduction kind");
765   }
766 }
767
768 void
769 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
770   //===------------------------------------------------===//
771   //
772   // Notice: any optimization or new instruction that go
773   // into the code below should be also be implemented in
774   // the cost-model.
775   //
776   //===------------------------------------------------===//
777   typedef SmallVector<PHINode*, 4> PhiVector;
778   BasicBlock &BB = *OrigLoop->getHeader();
779   Constant *Zero = ConstantInt::get(
780     IntegerType::getInt32Ty(BB.getContext()), 0);
781
782   // In order to support reduction variables we need to be able to vectorize
783   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
784   // steages. First, we create a new vector PHI node with no incoming edges.
785   // We use this value when we vectorize all of the instructions that use the
786   // PHI. Next, after all of the instructions in the block are complete we
787   // add the new incoming edges to the PHI. At this point all of the
788   // instructions in the basic block are vectorized, so we can use them to
789   // construct the PHI.
790   PhiVector PHIsToFix;
791
792   // For each instruction in the old loop.
793   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
794     Instruction *Inst = it;
795
796     switch (Inst->getOpcode()) {
797       case Instruction::Br:
798         // Nothing to do for PHIs and BR, since we already took care of the
799         // loop control flow instructions.
800         continue;
801       case Instruction::PHI:{
802         PHINode* P = cast<PHINode>(Inst);
803         // Special handling for the induction var.
804         if (OldInduction == Inst)
805           continue;
806         // This is phase one of vectorizing PHIs.
807         // This has to be a reduction variable.
808         assert(Legal->getReductionVars()->count(P) && "Not a Reduction");
809         Type *VecTy = VectorType::get(Inst->getType(), VF);
810         WidenMap[Inst] = Builder.CreatePHI(VecTy, 2, "vec.phi");
811         PHIsToFix.push_back(P);
812         continue;
813       }
814       case Instruction::Add:
815       case Instruction::FAdd:
816       case Instruction::Sub:
817       case Instruction::FSub:
818       case Instruction::Mul:
819       case Instruction::FMul:
820       case Instruction::UDiv:
821       case Instruction::SDiv:
822       case Instruction::FDiv:
823       case Instruction::URem:
824       case Instruction::SRem:
825       case Instruction::FRem:
826       case Instruction::Shl:
827       case Instruction::LShr:
828       case Instruction::AShr:
829       case Instruction::And:
830       case Instruction::Or:
831       case Instruction::Xor: {
832         // Just widen binops.
833         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
834         Value *A = getVectorValue(Inst->getOperand(0));
835         Value *B = getVectorValue(Inst->getOperand(1));
836         // Use this vector value for all users of the original instruction.
837         WidenMap[Inst] = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
838         break;
839       }
840       case Instruction::Select: {
841         // Widen selects.
842         // If the selector is loop invariant we can create a select
843         // instruction with a scalar condition. Otherwise, use vector-select.
844         Value *Cond = Inst->getOperand(0);
845         bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
846
847         // The condition can be loop invariant  but still defined inside the
848         // loop. This means that we can't just use the original 'cond' value.
849         // We have to take the 'vectorized' value and pick the first lane.
850         // Instcombine will make this a no-op.
851         Cond = getVectorValue(Cond);
852         if (InvariantCond)
853           Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
854
855         Value *Op0 = getVectorValue(Inst->getOperand(1));
856         Value *Op1 = getVectorValue(Inst->getOperand(2));
857         WidenMap[Inst] = Builder.CreateSelect(Cond, Op0, Op1);
858         break;
859       }
860
861       case Instruction::ICmp:
862       case Instruction::FCmp: {
863         // Widen compares. Generate vector compares.
864         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
865         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
866         Value *A = getVectorValue(Inst->getOperand(0));
867         Value *B = getVectorValue(Inst->getOperand(1));
868         if (FCmp)
869           WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
870         else
871           WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
872         break;
873       }
874
875       case Instruction::Store: {
876         // Attempt to issue a wide store.
877         StoreInst *SI = dyn_cast<StoreInst>(Inst);
878         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
879         Value *Ptr = SI->getPointerOperand();
880         unsigned Alignment = SI->getAlignment();
881         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
882         // This store does not use GEPs.
883         if (!Legal->isConsecutiveGep(Gep)) {
884           scalarizeInstruction(Inst);
885           break;
886         }
887
888         // The last index does not have to be the induction. It can be
889         // consecutive and be a function of the index. For example A[I+1];
890         unsigned NumOperands = Gep->getNumOperands();
891         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
892         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
893
894         // Create the new GEP with the new induction variable.
895         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
896         Gep2->setOperand(NumOperands - 1, LastIndex);
897         Ptr = Builder.Insert(Gep2);
898         Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
899         Value *Val = getVectorValue(SI->getValueOperand());
900         Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
901         break;
902       }
903       case Instruction::Load: {
904         // Attempt to issue a wide load.
905         LoadInst *LI = dyn_cast<LoadInst>(Inst);
906         Type *RetTy = VectorType::get(LI->getType(), VF);
907         Value *Ptr = LI->getPointerOperand();
908         unsigned Alignment = LI->getAlignment();
909         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
910
911         // We don't have a gep. Scalarize the load.
912         if (!Legal->isConsecutiveGep(Gep)) {
913           scalarizeInstruction(Inst);
914           break;
915         }
916
917         // The last index does not have to be the induction. It can be
918         // consecutive and be a function of the index. For example A[I+1];
919         unsigned NumOperands = Gep->getNumOperands();
920         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
921         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
922
923         // Create the new GEP with the new induction variable.
924         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
925         Gep2->setOperand(NumOperands - 1, LastIndex);
926         Ptr = Builder.Insert(Gep2);
927         Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
928         LI = Builder.CreateLoad(Ptr);
929         LI->setAlignment(Alignment);
930         // Use this vector value for all users of the load.
931         WidenMap[Inst] = LI;
932         break;
933       }
934       case Instruction::ZExt:
935       case Instruction::SExt:
936       case Instruction::FPToUI:
937       case Instruction::FPToSI:
938       case Instruction::FPExt:
939       case Instruction::PtrToInt:
940       case Instruction::IntToPtr:
941       case Instruction::SIToFP:
942       case Instruction::UIToFP:
943       case Instruction::Trunc:
944       case Instruction::FPTrunc:
945       case Instruction::BitCast: {
946         /// Vectorize bitcasts.
947         CastInst *CI = dyn_cast<CastInst>(Inst);
948         Value *A = getVectorValue(Inst->getOperand(0));
949         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
950         WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
951         break;
952       }
953
954       default:
955         /// All other instructions are unsupported. Scalarize them.
956         scalarizeInstruction(Inst);
957         break;
958     }// end of switch.
959   }// end of for_each instr.
960
961   // At this point every instruction in the original loop is widended to
962   // a vector form. We are almost done. Now, we need to fix the PHI nodes
963   // that we vectorized. The PHI nodes are currently empty because we did
964   // not want to introduce cycles. Notice that the remaining PHI nodes
965   // that we need to fix are reduction variables.
966
967   // Create the 'reduced' values for each of the induction vars.
968   // The reduced values are the vector values that we scalarize and combine
969   // after the loop is finished.
970   for (PhiVector::iterator it = PHIsToFix.begin(), e = PHIsToFix.end();
971        it != e; ++it) {
972     PHINode *RdxPhi = *it;
973     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
974     assert(RdxPhi && "Unable to recover vectorized PHI");
975
976     // Find the reduction variable descriptor.
977     assert(Legal->getReductionVars()->count(RdxPhi) &&
978            "Unable to find the reduction variable");
979     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
980       (*Legal->getReductionVars())[RdxPhi];
981
982     // We need to generate a reduction vector from the incoming scalar.
983     // To do so, we need to generate the 'identity' vector and overide
984     // one of the elements with the incoming scalar reduction. We need
985     // to do it in the vector-loop preheader.
986     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
987
988     // This is the vector-clone of the value that leaves the loop.
989     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
990     Type *VecTy = VectorExit->getType();
991
992     // Find the reduction identity variable. Zero for addition, or, xor,
993     // one for multiplication, -1 for And.
994     Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
995                                           VecTy->getScalarType());
996
997     // This vector is the Identity vector where the first element is the
998     // incoming scalar reduction.
999     Value *VectorStart = Builder.CreateInsertElement(Identity,
1000                                                     RdxDesc.StartValue, Zero);
1001
1002
1003     // Fix the vector-loop phi.
1004     // We created the induction variable so we know that the
1005     // preheader is the first entry.
1006     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1007
1008     // Reductions do not have to start at zero. They can start with
1009     // any loop invariant values.
1010     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
1011     unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1012     Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
1013     VecRdxPhi->addIncoming(Val, LoopVectorBody);
1014
1015     // Before each round, move the insertion point right between
1016     // the PHIs and the values we are going to write.
1017     // This allows us to write both PHINodes and the extractelement
1018     // instructions.
1019     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1020
1021     // This PHINode contains the vectorized reduction variable, or
1022     // the initial value vector, if we bypass the vector loop.
1023     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1024     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
1025     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
1026
1027     // Extract the first scalar.
1028     Value *Scalar0 =
1029       Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
1030     // Extract and reduce the remaining vector elements.
1031     for (unsigned i=1; i < VF; ++i) {
1032       Value *Scalar1 =
1033         Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
1034       switch (RdxDesc.Kind) {
1035         case LoopVectorizationLegality::IntegerAdd:
1036           Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
1037           break;
1038         case LoopVectorizationLegality::IntegerMult:
1039           Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
1040           break;
1041         case LoopVectorizationLegality::IntegerOr:
1042           Scalar0 = Builder.CreateOr(Scalar0, Scalar1);
1043           break;
1044         case LoopVectorizationLegality::IntegerAnd:
1045           Scalar0 = Builder.CreateAnd(Scalar0, Scalar1);
1046           break;
1047         case LoopVectorizationLegality::IntegerXor:
1048           Scalar0 = Builder.CreateXor(Scalar0, Scalar1);
1049           break;
1050         default:
1051           llvm_unreachable("Unknown reduction operation");
1052       }
1053     }
1054
1055     // Now, we need to fix the users of the reduction variable
1056     // inside and outside of the scalar remainder loop.
1057     // We know that the loop is in LCSSA form. We need to update the
1058     // PHI nodes in the exit blocks.
1059     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1060          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1061       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1062       if (!LCSSAPhi) continue;
1063
1064       // All PHINodes need to have a single entry edge, or two if
1065       // we already fixed them.
1066       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1067
1068       // We found our reduction value exit-PHI. Update it with the
1069       // incoming bypass edge.
1070       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1071         // Add an edge coming from the bypass.
1072         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1073         break;
1074       }
1075     }// end of the LCSSA phi scan.
1076
1077     // Fix the scalar loop reduction variable with the incoming reduction sum
1078     // from the vector body and from the backedge value.
1079     int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1080     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
1081     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1082     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1083   }// end of for each redux variable.
1084 }
1085
1086 void SingleBlockLoopVectorizer::updateAnalysis() {
1087   // The original basic block.
1088   SE->forgetLoop(OrigLoop);
1089
1090   // Update the dominator tree information.
1091   assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1092          "Entry does not dominate exit.");
1093
1094   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1095   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1096   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1097   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1098   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1099   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1100
1101   DEBUG(DT->verifyAnalysis());
1102 }
1103
1104 bool LoopVectorizationLegality::canVectorize() {
1105   if (!TheLoop->getLoopPreheader()) {
1106     assert(false && "No preheader!!");
1107     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
1108     return  false;
1109   }
1110
1111   // We can only vectorize single basic block loops.
1112   unsigned NumBlocks = TheLoop->getNumBlocks();
1113   if (NumBlocks != 1) {
1114     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
1115     return false;
1116   }
1117
1118   // We need to have a loop header.
1119   BasicBlock *BB = TheLoop->getHeader();
1120   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
1121
1122   // Go over each instruction and look at memory deps.
1123   if (!canVectorizeBlock(*BB)) {
1124     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
1125     return false;
1126   }
1127
1128   // ScalarEvolution needs to be able to find the exit count.
1129   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
1130   if (ExitCount == SE->getCouldNotCompute()) {
1131     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1132     return false;
1133   }
1134
1135   DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
1136
1137   // Okay! We can vectorize. At this point we don't have any other mem analysis
1138   // which may limit our maximum vectorization factor, so just return true with
1139   // no restrictions.
1140   return true;
1141 }
1142
1143 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
1144   // Scan the instructions in the block and look for hazards.
1145   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1146     Instruction *I = it;
1147
1148     PHINode *Phi = dyn_cast<PHINode>(I);
1149     if (Phi) {
1150       // This should not happen because the loop should be normalized.
1151       if (Phi->getNumIncomingValues() != 2) {
1152         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1153         return false;
1154       }
1155       // We only look at integer phi nodes.
1156       if (!Phi->getType()->isIntegerTy()) {
1157         DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
1158         return false;
1159       }
1160
1161       if (isInductionVariable(Phi)) {
1162         if (Induction) {
1163           DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1164           return false;
1165         }
1166         DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1167         Induction = Phi;
1168         continue;
1169       }
1170       if (AddReductionVar(Phi, IntegerAdd)) {
1171         DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1172         continue;
1173       }
1174       if (AddReductionVar(Phi, IntegerMult)) {
1175         DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1176         continue;
1177       }
1178       if (AddReductionVar(Phi, IntegerOr)) {
1179         DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1180         continue;
1181       }
1182       if (AddReductionVar(Phi, IntegerAnd)) {
1183         DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1184         continue;
1185       }
1186       if (AddReductionVar(Phi, IntegerXor)) {
1187         DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1188         continue;
1189       }
1190
1191       DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1192       return false;
1193     }// end of PHI handling
1194
1195     // We still don't handle functions.
1196     CallInst *CI = dyn_cast<CallInst>(I);
1197     if (CI) {
1198       DEBUG(dbgs() << "LV: Found a call site.\n");
1199       return false;
1200     }
1201
1202     // We do not re-vectorize vectors.
1203     if (!VectorType::isValidElementType(I->getType()) &&
1204         !I->getType()->isVoidTy()) {
1205       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1206       return false;
1207     }
1208
1209     // Reduction instructions are allowed to have exit users.
1210     // All other instructions must not have external users.
1211     if (!AllowedExit.count(I))
1212       //Check that all of the users of the loop are inside the BB.
1213       for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1214            it != e; ++it) {
1215         Instruction *U = cast<Instruction>(*it);
1216         // This user may be a reduction exit value.
1217         BasicBlock *Parent = U->getParent();
1218         if (Parent != &BB) {
1219           DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1220           return false;
1221         }
1222     }
1223   } // next instr.
1224
1225   if (!Induction) {
1226       DEBUG(dbgs() << "LV: Did not find an induction var.\n");
1227       return false;
1228   }
1229
1230   // Don't vectorize if the memory dependencies do not allow vectorization.
1231   if (!canVectorizeMemory(BB))
1232     return false;
1233
1234   // We now know that the loop is vectorizable!
1235   // Collect variables that will remain uniform after vectorization.
1236   std::vector<Value*> Worklist;
1237
1238   // Start with the conditional branch and walk up the block.
1239   Worklist.push_back(BB.getTerminator()->getOperand(0));
1240
1241   while (Worklist.size()) {
1242     Instruction *I = dyn_cast<Instruction>(Worklist.back());
1243     Worklist.pop_back();
1244     // Look at instructions inside this block.
1245     if (!I) continue;
1246     if (I->getParent() != &BB) continue;
1247
1248     // Stop when reaching PHI nodes.
1249     if (isa<PHINode>(I)) {
1250       assert(I == Induction && "Found a uniform PHI that is not the induction");
1251       break;
1252     }
1253
1254     // This is a known uniform.
1255     Uniforms.insert(I);
1256
1257     // Insert all operands.
1258     for (int i=0, Op = I->getNumOperands(); i < Op; ++i) {
1259       Worklist.push_back(I->getOperand(i));
1260     }
1261   }
1262
1263   return true;
1264 }
1265
1266 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1267   typedef SmallVector<Value*, 16> ValueVector;
1268   typedef SmallPtrSet<Value*, 16> ValueSet;
1269   // Holds the Load and Store *instructions*.
1270   ValueVector Loads;
1271   ValueVector Stores;
1272
1273   // Scan the BB and collect legal loads and stores.
1274   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1275     Instruction *I = it;
1276
1277     // If this is a load, save it. If this instruction can read from memory
1278     // but is not a load, then we quit. Notice that we don't handle function
1279     // calls that read or write.
1280     if (I->mayReadFromMemory()) {
1281       LoadInst *Ld = dyn_cast<LoadInst>(I);
1282       if (!Ld) return false;
1283       if (!Ld->isSimple()) {
1284         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1285         return false;
1286       }
1287       Loads.push_back(Ld);
1288       continue;
1289     }
1290
1291     // Save store instructions. Abort if other instructions write to memory.
1292     if (I->mayWriteToMemory()) {
1293       StoreInst *St = dyn_cast<StoreInst>(I);
1294       if (!St) return false;
1295       if (!St->isSimple()) {
1296         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1297         return false;
1298       }
1299       Stores.push_back(St);
1300     }
1301   } // next instr.
1302
1303   // Now we have two lists that hold the loads and the stores.
1304   // Next, we find the pointers that they use.
1305
1306   // Check if we see any stores. If there are no stores, then we don't
1307   // care if the pointers are *restrict*.
1308   if (!Stores.size()) {
1309         DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1310         return true;
1311   }
1312
1313   // Holds the read and read-write *pointers* that we find.
1314   ValueVector Reads;
1315   ValueVector ReadWrites;
1316
1317   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1318   // multiple times on the same object. If the ptr is accessed twice, once
1319   // for read and once for write, it will only appear once (on the write
1320   // list). This is okay, since we are going to check for conflicts between
1321   // writes and between reads and writes, but not between reads and reads.
1322   ValueSet Seen;
1323
1324   ValueVector::iterator I, IE;
1325   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1326     StoreInst *ST = dyn_cast<StoreInst>(*I);
1327     assert(ST && "Bad StoreInst");
1328     Value* Ptr = ST->getPointerOperand();
1329     // If we did *not* see this pointer before, insert it to
1330     // the read-write list. At this phase it is only a 'write' list.
1331     if (Seen.insert(Ptr))
1332       ReadWrites.push_back(Ptr);
1333   }
1334
1335   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1336     LoadInst *LD = dyn_cast<LoadInst>(*I);
1337     assert(LD && "Bad LoadInst");
1338     Value* Ptr = LD->getPointerOperand();
1339     // If we did *not* see this pointer before, insert it to the
1340     // read list. If we *did* see it before, then it is already in
1341     // the read-write list. This allows us to vectorize expressions
1342     // such as A[i] += x;  Because the address of A[i] is a read-write
1343     // pointer. This only works if the index of A[i] is consecutive.
1344     // If the address of i is unknown (for example A[B[i]]) then we may
1345     // read a few words, modify, and write a few words, and some of the
1346     // words may be written to the same address.
1347     if (Seen.insert(Ptr) || !isConsecutiveGep(Ptr))
1348       Reads.push_back(Ptr);
1349   }
1350
1351   // Now that the pointers are in two lists (Reads and ReadWrites), we
1352   // can check that there are no conflicts between each of the writes and
1353   // between the writes to the reads.
1354   ValueSet WriteObjects;
1355   ValueVector TempObjects;
1356
1357   // Check that the read-writes do not conflict with other read-write
1358   // pointers.
1359   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1360     GetUnderlyingObjects(*I, TempObjects, DL);
1361     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1362          it != e; ++it) {
1363       if (!isIdentifiedObject(*it)) {
1364         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1365         return false;
1366       }
1367       if (!WriteObjects.insert(*it)) {
1368         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1369               << **it <<"\n");
1370         return false;
1371       }
1372     }
1373     TempObjects.clear();
1374   }
1375
1376   /// Check that the reads don't conflict with the read-writes.
1377   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1378     GetUnderlyingObjects(*I, TempObjects, DL);
1379     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1380          it != e; ++it) {
1381       if (!isIdentifiedObject(*it)) {
1382         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1383         return false;
1384       }
1385       if (WriteObjects.count(*it)) {
1386         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1387               << **it <<"\n");
1388         return false;
1389       }
1390     }
1391     TempObjects.clear();
1392   }
1393
1394   // All is okay.
1395   return true;
1396 }
1397
1398 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1399                                                 ReductionKind Kind) {
1400   if (Phi->getNumIncomingValues() != 2)
1401     return false;
1402
1403   // Find the possible incoming reduction variable.
1404   BasicBlock *BB = Phi->getParent();
1405   int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1406   int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1407   Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1408
1409   // ExitInstruction is the single value which is used outside the loop.
1410   // We only allow for a single reduction value to be used outside the loop.
1411   // This includes users of the reduction, variables (which form a cycle
1412   // which ends in the phi node).
1413   Instruction *ExitInstruction = 0;
1414
1415   // Iter is our iterator. We start with the PHI node and scan for all of the
1416   // users of this instruction. All users must be instructions which can be
1417   // used as reduction variables (such as ADD). We may have a single
1418   // out-of-block user. They cycle must end with the original PHI.
1419   // Also, we can't have multiple block-local users.
1420   Instruction *Iter = Phi;
1421   while (true) {
1422     // Any reduction instr must be of one of the allowed kinds.
1423     if (!isReductionInstr(Iter, Kind))
1424       return false;
1425
1426     // Did we found a user inside this block ?
1427     bool FoundInBlockUser = false;
1428     // Did we reach the initial PHI node ?
1429     bool FoundStartPHI = false;
1430
1431     // If the instruction has no users then this is a broken
1432     // chain and can't be a reduction variable.
1433     if (Iter->use_empty())
1434       return false;
1435
1436     // For each of the *users* of iter.
1437     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1438          it != e; ++it) {
1439       Instruction *U = cast<Instruction>(*it);
1440       // We already know that the PHI is a user.
1441       if (U == Phi) {
1442         FoundStartPHI = true;
1443         continue;
1444       }
1445       // Check if we found the exit user.
1446       BasicBlock *Parent = U->getParent();
1447       if (Parent != BB) {
1448         // We must have a single exit instruction.
1449         if (ExitInstruction != 0)
1450           return false;
1451         ExitInstruction = Iter;
1452       }
1453       // We can't have multiple inside users.
1454       if (FoundInBlockUser)
1455         return false;
1456       FoundInBlockUser = true;
1457       Iter = U;
1458     }
1459
1460     // We found a reduction var if we have reached the original
1461     // phi node and we only have a single instruction with out-of-loop
1462     // users.
1463    if (FoundStartPHI && ExitInstruction) {
1464      // This instruction is allowed to have out-of-loop users.
1465      AllowedExit.insert(ExitInstruction);
1466
1467      // Save the description of this reduction variable.
1468      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1469      Reductions[Phi] = RD;
1470      return true;
1471    }
1472   }
1473 }
1474
1475 bool
1476 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1477                                             ReductionKind Kind) {
1478     switch (I->getOpcode()) {
1479     default:
1480       return false;
1481     case Instruction::PHI:
1482       // possibly.
1483       return true;
1484     case Instruction::Add:
1485     case Instruction::Sub:
1486       return Kind == IntegerAdd;
1487     case Instruction::Mul:
1488     case Instruction::UDiv:
1489     case Instruction::SDiv:
1490       return Kind == IntegerMult;
1491     case Instruction::And:
1492       return Kind == IntegerAnd;
1493     case Instruction::Or:
1494       return Kind == IntegerOr;
1495     case Instruction::Xor:
1496       return Kind == IntegerXor;
1497     }
1498 }
1499
1500 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1501   // Check that the PHI is consecutive and starts at zero.
1502   const SCEV *PhiScev = SE->getSCEV(Phi);
1503   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1504   if (!AR) {
1505     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1506     return false;
1507   }
1508   const SCEV *Step = AR->getStepRecurrence(*SE);
1509   const SCEV *Start = AR->getStart();
1510
1511   if (!Step->isOne() || !Start->isZero()) {
1512     DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
1513     return false;
1514   }
1515   return true;
1516 }
1517
1518 unsigned
1519 LoopVectorizationCostModel::findBestVectorizationFactor(unsigned VF) {
1520   if (!VTTI) {
1521     DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1522     return 1;
1523   }
1524
1525   float Cost = expectedCost(1);
1526   unsigned Width = 1;
1527   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1528   for (unsigned i=2; i <= VF; i*=2) {
1529     // Notice that the vector loop needs to be executed less times, so
1530     // we need to divide the cost of the vector loops by the width of
1531     // the vector elements.
1532     float VectorCost = expectedCost(i) / (float)i;
1533     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1534           (int)VectorCost << ".\n");
1535     if (VectorCost < Cost) {
1536       Cost = VectorCost;
1537       Width = i;
1538     }
1539   }
1540
1541   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1542   return Width;
1543 }
1544
1545 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1546   // We can only estimate the cost of single basic block loops.
1547   assert(1 == TheLoop->getNumBlocks() && "Too many blocks in loop");
1548
1549   BasicBlock *BB = TheLoop->getHeader();
1550   unsigned Cost = 0;
1551
1552   // For each instruction in the old loop.
1553   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1554     Instruction *Inst = it;
1555     unsigned C = getInstructionCost(Inst, VF);
1556     Cost += C;
1557     DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF "<< VF <<
1558           " For instruction: "<< *Inst << "\n");
1559   }
1560
1561   return Cost;
1562 }
1563
1564 unsigned
1565 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
1566   assert(VTTI && "Invalid vector target transformation info");
1567
1568   // If we know that this instruction will remain uniform, check the cost of
1569   // the scalar version.
1570   if (Legal->isUniformAfterVectorization(I))
1571     VF = 1;
1572
1573   Type *RetTy = I->getType();
1574   Type *VectorTy = ToVectorTy(RetTy, VF);
1575
1576
1577   // TODO: We need to estimate the cost of intrinsic calls.
1578   switch (I->getOpcode()) {
1579     case Instruction::GetElementPtr:
1580       // We mark this instruction as zero-cost because scalar GEPs are usually
1581       // lowered to the intruction addressing mode. At the moment we don't
1582       // generate vector geps.
1583       return 0;
1584     case Instruction::Br: {
1585       return VTTI->getCFInstrCost(I->getOpcode());
1586     }
1587     case Instruction::PHI:
1588       return 0;
1589     case Instruction::Add:
1590     case Instruction::FAdd:
1591     case Instruction::Sub:
1592     case Instruction::FSub:
1593     case Instruction::Mul:
1594     case Instruction::FMul:
1595     case Instruction::UDiv:
1596     case Instruction::SDiv:
1597     case Instruction::FDiv:
1598     case Instruction::URem:
1599     case Instruction::SRem:
1600     case Instruction::FRem:
1601     case Instruction::Shl:
1602     case Instruction::LShr:
1603     case Instruction::AShr:
1604     case Instruction::And:
1605     case Instruction::Or:
1606     case Instruction::Xor: {
1607       return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
1608     }
1609     case Instruction::Select: {
1610       SelectInst *SI = cast<SelectInst>(I);
1611       const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
1612       bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
1613       Type *CondTy = SI->getCondition()->getType();
1614       if (ScalarCond)
1615         CondTy = VectorType::get(CondTy, VF);
1616
1617       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
1618     }
1619     case Instruction::ICmp:
1620     case Instruction::FCmp: {
1621       Type *ValTy = I->getOperand(0)->getType();
1622       VectorTy = ToVectorTy(ValTy, VF);
1623       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
1624     }
1625     case Instruction::Store: {
1626       StoreInst *SI = cast<StoreInst>(I);
1627       Type *ValTy = SI->getValueOperand()->getType();
1628       VectorTy = ToVectorTy(ValTy, VF);
1629
1630       if (VF == 1)
1631         return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
1632                               SI->getAlignment(), SI->getPointerAddressSpace());
1633
1634       // Scalarized stores.
1635       if (!Legal->isConsecutiveGep(SI->getPointerOperand())) {
1636         unsigned Cost = 0;
1637         unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
1638                                               ValTy);
1639         // The cost of extracting from the value vector.
1640         Cost += VF * (ExtCost);
1641         // The cost of the scalar stores.
1642         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
1643                                            ValTy->getScalarType(),
1644                                            SI->getAlignment(),
1645                                            SI->getPointerAddressSpace());
1646         return Cost;
1647       }
1648
1649       // Wide stores.
1650       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
1651                                    SI->getPointerAddressSpace());
1652     }
1653     case Instruction::Load: {
1654       LoadInst *LI = cast<LoadInst>(I);
1655
1656       if (VF == 1)
1657         return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
1658                                      LI->getAlignment(),
1659                                      LI->getPointerAddressSpace());
1660
1661       // Scalarized loads.
1662       if (!Legal->isConsecutiveGep(LI->getPointerOperand())) {
1663         unsigned Cost = 0;
1664         unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
1665         // The cost of inserting the loaded value into the result vector.
1666         Cost += VF * (InCost);
1667         // The cost of the scalar stores.
1668         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
1669                                            RetTy->getScalarType(),
1670                                            LI->getAlignment(),
1671                                            LI->getPointerAddressSpace());
1672         return Cost;
1673       }
1674
1675       // Wide loads.
1676       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
1677                                    LI->getPointerAddressSpace());
1678     }
1679     case Instruction::ZExt:
1680     case Instruction::SExt:
1681     case Instruction::FPToUI:
1682     case Instruction::FPToSI:
1683     case Instruction::FPExt:
1684     case Instruction::PtrToInt:
1685     case Instruction::IntToPtr:
1686     case Instruction::SIToFP:
1687     case Instruction::UIToFP:
1688     case Instruction::Trunc:
1689     case Instruction::FPTrunc:
1690     case Instruction::BitCast: {
1691       Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
1692       return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
1693     }
1694     default: {
1695       // We are scalarizing the instruction. Return the cost of the scalar
1696       // instruction, plus the cost of insert and extract into vector
1697       // elements, times the vector width.
1698       unsigned Cost = 0;
1699
1700       bool IsVoid = RetTy->isVoidTy();
1701
1702       unsigned InsCost = (IsVoid ? 0 :
1703                           VTTI->getInstrCost(Instruction::InsertElement,
1704                                              VectorTy));
1705
1706       unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
1707                                             VectorTy);
1708
1709       // The cost of inserting the results plus extracting each one of the
1710       // operands.
1711       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
1712
1713       // The cost of executing VF copies of the scalar instruction.
1714       Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
1715       return Cost;
1716     }
1717   }// end of switch.
1718 }
1719
1720 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
1721   if (Scalar->isVoidTy() || VF == 1)
1722     return Scalar;
1723   return VectorType::get(Scalar, VF);
1724 }
1725
1726 } // namespace
1727
1728 char LoopVectorize::ID = 0;
1729 static const char lv_name[] = "Loop Vectorization";
1730 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
1731 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1732 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1733 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1734 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
1735
1736 namespace llvm {
1737   Pass *createLoopVectorizePass() {
1738     return new LoopVectorize();
1739   }
1740 }
1741