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