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