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