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