Remove the Function::getFnAttributes method in favor of using the AttributeSet
[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 #include "LoopVectorize.h"
10 #include "llvm/ADT/StringExtras.h"
11 #include "llvm/Analysis/AliasAnalysis.h"
12 #include "llvm/Analysis/AliasSetTracker.h"
13 #include "llvm/Analysis/Dominators.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/Analysis/LoopIterator.h"
16 #include "llvm/Analysis/LoopPass.h"
17 #include "llvm/Analysis/ScalarEvolutionExpander.h"
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DataLayout.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/TargetTransformInfo.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Vectorize.h"
38 #include "llvm/Type.h"
39 #include "llvm/Value.h"
40
41 static cl::opt<unsigned>
42 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
43                     cl::desc("Sets the SIMD width. Zero is autoselect."));
44
45 static cl::opt<bool>
46 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
47                    cl::desc("Enable if-conversion during vectorization."));
48
49 namespace {
50
51 /// The LoopVectorize Pass.
52 struct LoopVectorize : public LoopPass {
53   /// Pass identification, replacement for typeid
54   static char ID;
55
56   explicit LoopVectorize() : LoopPass(ID) {
57     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
58   }
59
60   ScalarEvolution *SE;
61   DataLayout *DL;
62   LoopInfo *LI;
63   TargetTransformInfo *TTI;
64   DominatorTree *DT;
65
66   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
67     // We only vectorize innermost loops.
68     if (!L->empty())
69       return false;
70
71     SE = &getAnalysis<ScalarEvolution>();
72     DL = getAnalysisIfAvailable<DataLayout>();
73     LI = &getAnalysis<LoopInfo>();
74     TTI = getAnalysisIfAvailable<TargetTransformInfo>();
75     DT = &getAnalysis<DominatorTree>();
76
77     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
78           L->getHeader()->getParent()->getName() << "\"\n");
79
80     // Check if it is legal to vectorize the loop.
81     LoopVectorizationLegality LVL(L, SE, DL, DT);
82     if (!LVL.canVectorize()) {
83       DEBUG(dbgs() << "LV: Not vectorizing.\n");
84       return false;
85     }
86
87     // Select the preffered vectorization factor.
88     const VectorTargetTransformInfo *VTTI = 0;
89     if (TTI)
90       VTTI = TTI->getVectorTargetTransformInfo();
91     // Use the cost model.
92     LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
93
94     // Check the function attribues to find out if this function should be
95     // optimized for size.
96     Function *F = L->getHeader()->getParent();
97     Attribute::AttrKind SzAttr= Attribute::OptimizeForSize;
98     bool OptForSize =
99       F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, SzAttr);
100
101     unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
102
103     if (VF == 1) {
104       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
105       return false;
106     }
107
108     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
109           F->getParent()->getModuleIdentifier()<<"\n");
110
111     // If we decided that it is *legal* to vectorizer the loop then do it.
112     InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
113     LB.vectorize(&LVL);
114
115     DEBUG(verifyFunction(*L->getHeader()->getParent()));
116     return true;
117   }
118
119   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
120     LoopPass::getAnalysisUsage(AU);
121     AU.addRequiredID(LoopSimplifyID);
122     AU.addRequiredID(LCSSAID);
123     AU.addRequired<LoopInfo>();
124     AU.addRequired<ScalarEvolution>();
125     AU.addRequired<DominatorTree>();
126     AU.addPreserved<LoopInfo>();
127     AU.addPreserved<DominatorTree>();
128   }
129
130 };
131
132 }// namespace
133
134 //===----------------------------------------------------------------------===//
135 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
136 // LoopVectorizationCostModel.
137 //===----------------------------------------------------------------------===//
138
139 void
140 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
141                                                        Loop *Lp, Value *Ptr) {
142   const SCEV *Sc = SE->getSCEV(Ptr);
143   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
144   assert(AR && "Invalid addrec expression");
145   const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
146   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
147   Pointers.push_back(Ptr);
148   Starts.push_back(AR->getStart());
149   Ends.push_back(ScEnd);
150 }
151
152 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
153   // Create the types.
154   LLVMContext &C = V->getContext();
155   Type *VTy = VectorType::get(V->getType(), VF);
156   Type *I32 = IntegerType::getInt32Ty(C);
157
158   // Save the current insertion location.
159   Instruction *Loc = Builder.GetInsertPoint();
160
161   // We need to place the broadcast of invariant variables outside the loop.
162   Instruction *Instr = dyn_cast<Instruction>(V);
163   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
164   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
165
166   // Place the code for broadcasting invariant variables in the new preheader.
167   if (Invariant)
168     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
169
170   Constant *Zero = ConstantInt::get(I32, 0);
171   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
172   Value *UndefVal = UndefValue::get(VTy);
173   // Insert the value into a new vector.
174   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
175   // Broadcast the scalar into all locations in the vector.
176   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
177                                             "broadcast");
178
179   // Restore the builder insertion point.
180   if (Invariant)
181     Builder.SetInsertPoint(Loc);
182
183   return Shuf;
184 }
185
186 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, bool Negate) {
187   assert(Val->getType()->isVectorTy() && "Must be a vector");
188   assert(Val->getType()->getScalarType()->isIntegerTy() &&
189          "Elem must be an integer");
190   // Create the types.
191   Type *ITy = Val->getType()->getScalarType();
192   VectorType *Ty = cast<VectorType>(Val->getType());
193   int VLen = Ty->getNumElements();
194   SmallVector<Constant*, 8> Indices;
195
196   // Create a vector of consecutive numbers from zero to VF.
197   for (int i = 0; i < VLen; ++i)
198     Indices.push_back(ConstantInt::get(ITy, Negate ? (-i): i ));
199
200   // Add the consecutive indices to the vector value.
201   Constant *Cv = ConstantVector::get(Indices);
202   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
203   return Builder.CreateAdd(Val, Cv, "induction");
204 }
205
206 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
207   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
208
209   // If this value is a pointer induction variable we know it is consecutive.
210   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
211   if (Phi && Inductions.count(Phi)) {
212     InductionInfo II = Inductions[Phi];
213     if (PtrInduction == II.IK)
214       return 1;
215   }
216
217   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
218   if (!Gep)
219     return 0;
220
221   unsigned NumOperands = Gep->getNumOperands();
222   Value *LastIndex = Gep->getOperand(NumOperands - 1);
223
224   // Check that all of the gep indices are uniform except for the last.
225   for (unsigned i = 0; i < NumOperands - 1; ++i)
226     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
227       return 0;
228
229   // We can emit wide load/stores only if the last index is the induction
230   // variable.
231   const SCEV *Last = SE->getSCEV(LastIndex);
232   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
233     const SCEV *Step = AR->getStepRecurrence(*SE);
234
235     // The memory is consecutive because the last index is consecutive
236     // and all other indices are loop invariant.
237     if (Step->isOne())
238       return 1;
239     if (Step->isAllOnesValue())
240       return -1;
241   }
242
243   return 0;
244 }
245
246 bool LoopVectorizationLegality::isUniform(Value *V) {
247   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
248 }
249
250 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
251   assert(V != Induction && "The new induction variable should not be used.");
252   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
253   // If we saved a vectorized copy of V, use it.
254   Value *&MapEntry = WidenMap[V];
255   if (MapEntry)
256     return MapEntry;
257
258   // Broadcast V and save the value for future uses.
259   Value *B = getBroadcastInstrs(V);
260   MapEntry = B;
261   return B;
262 }
263
264 Constant*
265 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
266   return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
267 }
268
269 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
270   assert(Vec->getType()->isVectorTy() && "Invalid type");
271   SmallVector<Constant*, 8> ShuffleMask;
272   for (unsigned i = 0; i < VF; ++i)
273     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
274
275   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
276                                      ConstantVector::get(ShuffleMask),
277                                      "reverse");
278 }
279
280 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
281   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
282   // Holds vector parameters or scalars, in case of uniform vals.
283   SmallVector<Value*, 8> Params;
284
285   // Find all of the vectorized parameters.
286   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
287     Value *SrcOp = Instr->getOperand(op);
288
289     // If we are accessing the old induction variable, use the new one.
290     if (SrcOp == OldInduction) {
291       Params.push_back(getVectorValue(SrcOp));
292       continue;
293     }
294
295     // Try using previously calculated values.
296     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
297
298     // If the src is an instruction that appeared earlier in the basic block
299     // then it should already be vectorized.
300     if (SrcInst && OrigLoop->contains(SrcInst)) {
301       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
302       // The parameter is a vector value from earlier.
303       Params.push_back(WidenMap[SrcInst]);
304     } else {
305       // The parameter is a scalar from outside the loop. Maybe even a constant.
306       Params.push_back(SrcOp);
307     }
308   }
309
310   assert(Params.size() == Instr->getNumOperands() &&
311          "Invalid number of operands");
312
313   // Does this instruction return a value ?
314   bool IsVoidRetTy = Instr->getType()->isVoidTy();
315   Value *VecResults = 0;
316
317   // If we have a return value, create an empty vector. We place the scalarized
318   // instructions in this vector.
319   if (!IsVoidRetTy)
320     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
321
322   // For each scalar that we create:
323   for (unsigned i = 0; i < VF; ++i) {
324     Instruction *Cloned = Instr->clone();
325     if (!IsVoidRetTy)
326       Cloned->setName(Instr->getName() + ".cloned");
327     // Replace the operands of the cloned instrucions with extracted scalars.
328     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
329       Value *Op = Params[op];
330       // Param is a vector. Need to extract the right lane.
331       if (Op->getType()->isVectorTy())
332         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
333       Cloned->setOperand(op, Op);
334     }
335
336     // Place the cloned scalar in the new loop.
337     Builder.Insert(Cloned);
338
339     // If the original scalar returns a value we need to place it in a vector
340     // so that future users will be able to use it.
341     if (!IsVoidRetTy)
342       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
343                                                Builder.getInt32(i));
344   }
345
346   if (!IsVoidRetTy)
347     WidenMap[Instr] = VecResults;
348 }
349
350 Value*
351 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
352                                      Instruction *Loc) {
353   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
354   Legal->getRuntimePointerCheck();
355
356   if (!PtrRtCheck->Need)
357     return NULL;
358
359   Value *MemoryRuntimeCheck = 0;
360   unsigned NumPointers = PtrRtCheck->Pointers.size();
361   SmallVector<Value* , 2> Starts;
362   SmallVector<Value* , 2> Ends;
363
364   SCEVExpander Exp(*SE, "induction");
365
366   // Use this type for pointer arithmetic.
367   Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
368
369   for (unsigned i = 0; i < NumPointers; ++i) {
370     Value *Ptr = PtrRtCheck->Pointers[i];
371     const SCEV *Sc = SE->getSCEV(Ptr);
372
373     if (SE->isLoopInvariant(Sc, OrigLoop)) {
374       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
375             *Ptr <<"\n");
376       Starts.push_back(Ptr);
377       Ends.push_back(Ptr);
378     } else {
379       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
380
381       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
382       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
383       Starts.push_back(Start);
384       Ends.push_back(End);
385     }
386   }
387
388   for (unsigned i = 0; i < NumPointers; ++i) {
389     for (unsigned j = i+1; j < NumPointers; ++j) {
390       Instruction::CastOps Op = Instruction::BitCast;
391       Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
392       Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
393       Value *End0 =   CastInst::Create(Op, Ends[i],   PtrArithTy, "bc", Loc);
394       Value *End1 =   CastInst::Create(Op, Ends[j],   PtrArithTy, "bc", Loc);
395
396       Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
397                                     Start0, End1, "bound0", Loc);
398       Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
399                                     Start1, End0, "bound1", Loc);
400       Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
401                                                  "found.conflict", Loc);
402       if (MemoryRuntimeCheck)
403         MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
404                                                     MemoryRuntimeCheck,
405                                                     IsConflict,
406                                                     "conflict.rdx", Loc);
407       else
408         MemoryRuntimeCheck = IsConflict;
409
410     }
411   }
412
413   return MemoryRuntimeCheck;
414 }
415
416 void
417 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
418   /*
419    In this function we generate a new loop. The new loop will contain
420    the vectorized instructions while the old loop will continue to run the
421    scalar remainder.
422
423        [ ] <-- vector loop bypass.
424      /  |
425     /   v
426    |   [ ]     <-- vector pre header.
427    |    |
428    |    v
429    |   [  ] \
430    |   [  ]_|   <-- vector loop.
431    |    |
432     \   v
433       >[ ]   <--- middle-block.
434      /  |
435     /   v
436    |   [ ]     <--- new preheader.
437    |    |
438    |    v
439    |   [ ] \
440    |   [ ]_|   <-- old scalar loop to handle remainder.
441     \   |
442      \  v
443       >[ ]     <-- exit block.
444    ...
445    */
446
447   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
448   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
449   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
450   assert(ExitBlock && "Must have an exit block");
451
452   // Some loops have a single integer induction variable, while other loops
453   // don't. One example is c++ iterators that often have multiple pointer
454   // induction variables. In the code below we also support a case where we
455   // don't have a single induction variable.
456   OldInduction = Legal->getInduction();
457   Type *IdxTy = OldInduction ? OldInduction->getType() :
458   DL->getIntPtrType(SE->getContext());
459
460   // Find the loop boundaries.
461   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
462   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
463
464   // Get the total trip count from the count by adding 1.
465   ExitCount = SE->getAddExpr(ExitCount,
466                              SE->getConstant(ExitCount->getType(), 1));
467
468   // Expand the trip count and place the new instructions in the preheader.
469   // Notice that the pre-header does not change, only the loop body.
470   SCEVExpander Exp(*SE, "induction");
471
472   // Count holds the overall loop count (N).
473   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
474                                    BypassBlock->getTerminator());
475
476   // The loop index does not have to start at Zero. Find the original start
477   // value from the induction PHI node. If we don't have an induction variable
478   // then we know that it starts at zero.
479   Value *StartIdx = OldInduction ?
480   OldInduction->getIncomingValueForBlock(BypassBlock):
481   ConstantInt::get(IdxTy, 0);
482
483   assert(BypassBlock && "Invalid loop structure");
484
485   // Generate the code that checks in runtime if arrays overlap.
486   Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
487                                               BypassBlock->getTerminator());
488
489   // Split the single block loop into the two loop structure described above.
490   BasicBlock *VectorPH =
491   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
492   BasicBlock *VecBody =
493   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
494   BasicBlock *MiddleBlock =
495   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
496   BasicBlock *ScalarPH =
497   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
498
499   // This is the location in which we add all of the logic for bypassing
500   // the new vector loop.
501   Instruction *Loc = BypassBlock->getTerminator();
502
503   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
504   // inside the loop.
505   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
506
507   // Generate the induction variable.
508   Induction = Builder.CreatePHI(IdxTy, 2, "index");
509   Constant *Step = ConstantInt::get(IdxTy, VF);
510
511   // We may need to extend the index in case there is a type mismatch.
512   // We know that the count starts at zero and does not overflow.
513   if (Count->getType() != IdxTy) {
514     // The exit count can be of pointer type. Convert it to the correct
515     // integer type.
516     if (ExitCount->getType()->isPointerTy())
517       Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
518     else
519       Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
520   }
521
522   // Add the start index to the loop count to get the new end index.
523   Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
524
525   // Now we need to generate the expression for N - (N % VF), which is
526   // the part that the vectorized body will execute.
527   Constant *CIVF = ConstantInt::get(IdxTy, VF);
528   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
529   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
530   Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
531                                                      "end.idx.rnd.down", Loc);
532
533   // Now, compare the new count to zero. If it is zero skip the vector loop and
534   // jump to the scalar loop.
535   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
536                                IdxEndRoundDown,
537                                StartIdx,
538                                "cmp.zero", Loc);
539
540   // If we are using memory runtime checks, include them in.
541   if (MemoryRuntimeCheck)
542     Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
543                                  "CntOrMem", Loc);
544
545   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
546   // Remove the old terminator.
547   Loc->eraseFromParent();
548
549   // We are going to resume the execution of the scalar loop.
550   // Go over all of the induction variables that we found and fix the
551   // PHIs that are left in the scalar version of the loop.
552   // The starting values of PHI nodes depend on the counter of the last
553   // iteration in the vectorized loop.
554   // If we come from a bypass edge then we need to start from the original
555   // start value.
556
557   // This variable saves the new starting index for the scalar loop.
558   PHINode *ResumeIndex = 0;
559   LoopVectorizationLegality::InductionList::iterator I, E;
560   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
561   for (I = List->begin(), E = List->end(); I != E; ++I) {
562     PHINode *OrigPhi = I->first;
563     LoopVectorizationLegality::InductionInfo II = I->second;
564     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
565                                          MiddleBlock->getTerminator());
566     Value *EndValue = 0;
567     switch (II.IK) {
568     case LoopVectorizationLegality::NoInduction:
569       llvm_unreachable("Unknown induction");
570     case LoopVectorizationLegality::IntInduction: {
571       // Handle the integer induction counter:
572       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
573       assert(OrigPhi == OldInduction && "Unknown integer PHI");
574       // We know what the end value is.
575       EndValue = IdxEndRoundDown;
576       // We also know which PHI node holds it.
577       ResumeIndex = ResumeVal;
578       break;
579     }
580     case LoopVectorizationLegality::ReverseIntInduction: {
581       // Convert the CountRoundDown variable to the PHI size.
582       unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
583       unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
584       Value *CRD = CountRoundDown;
585       if (CRDSize > IISize)
586         CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
587                                II.StartValue->getType(),
588                                "tr.crd", BypassBlock->getTerminator());
589       else if (CRDSize < IISize)
590         CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
591                                II.StartValue->getType(),
592                                "sext.crd", BypassBlock->getTerminator());
593       // Handle reverse integer induction counter:
594       EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
595                                            BypassBlock->getTerminator());
596       break;
597     }
598     case LoopVectorizationLegality::PtrInduction: {
599       // For pointer induction variables, calculate the offset using
600       // the end index.
601       EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
602                                            "ptr.ind.end",
603                                            BypassBlock->getTerminator());
604       break;
605     }
606     }// end of case
607
608     // The new PHI merges the original incoming value, in case of a bypass,
609     // or the value at the end of the vectorized loop.
610     ResumeVal->addIncoming(II.StartValue, BypassBlock);
611     ResumeVal->addIncoming(EndValue, VecBody);
612
613     // Fix the scalar body counter (PHI node).
614     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
615     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
616   }
617
618   // If we are generating a new induction variable then we also need to
619   // generate the code that calculates the exit value. This value is not
620   // simply the end of the counter because we may skip the vectorized body
621   // in case of a runtime check.
622   if (!OldInduction){
623     assert(!ResumeIndex && "Unexpected resume value found");
624     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
625                                   MiddleBlock->getTerminator());
626     ResumeIndex->addIncoming(StartIdx, BypassBlock);
627     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
628   }
629
630   // Make sure that we found the index where scalar loop needs to continue.
631   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
632          "Invalid resume Index");
633
634   // Add a check in the middle block to see if we have completed
635   // all of the iterations in the first vector loop.
636   // If (N - N%VF) == N, then we *don't* need to run the remainder.
637   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
638                                 ResumeIndex, "cmp.n",
639                                 MiddleBlock->getTerminator());
640
641   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
642   // Remove the old terminator.
643   MiddleBlock->getTerminator()->eraseFromParent();
644
645   // Create i+1 and fill the PHINode.
646   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
647   Induction->addIncoming(StartIdx, VectorPH);
648   Induction->addIncoming(NextIdx, VecBody);
649   // Create the compare.
650   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
651   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
652
653   // Now we have two terminators. Remove the old one from the block.
654   VecBody->getTerminator()->eraseFromParent();
655
656   // Get ready to start creating new instructions into the vectorized body.
657   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
658
659   // Create and register the new vector loop.
660   Loop* Lp = new Loop();
661   Loop *ParentLoop = OrigLoop->getParentLoop();
662
663   // Insert the new loop into the loop nest and register the new basic blocks.
664   if (ParentLoop) {
665     ParentLoop->addChildLoop(Lp);
666     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
667     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
668     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
669   } else {
670     LI->addTopLevelLoop(Lp);
671   }
672
673   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
674
675   // Save the state.
676   LoopVectorPreHeader = VectorPH;
677   LoopScalarPreHeader = ScalarPH;
678   LoopMiddleBlock = MiddleBlock;
679   LoopExitBlock = ExitBlock;
680   LoopVectorBody = VecBody;
681   LoopScalarBody = OldBasicBlock;
682   LoopBypassBlock = BypassBlock;
683 }
684
685 /// This function returns the identity element (or neutral element) for
686 /// the operation K.
687 static unsigned
688 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
689   switch (K) {
690   case LoopVectorizationLegality::IntegerXor:
691   case LoopVectorizationLegality::IntegerAdd:
692   case LoopVectorizationLegality::IntegerOr:
693     // Adding, Xoring, Oring zero to a number does not change it.
694     return 0;
695   case LoopVectorizationLegality::IntegerMult:
696     // Multiplying a number by 1 does not change it.
697     return 1;
698   case LoopVectorizationLegality::IntegerAnd:
699     // AND-ing a number with an all-1 value does not change it.
700     return -1;
701   default:
702     llvm_unreachable("Unknown reduction kind");
703   }
704 }
705
706 static bool
707 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
708   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
709   if (!II)
710     return false;
711   switch (II->getIntrinsicID()) {
712   case Intrinsic::sqrt:
713   case Intrinsic::sin:
714   case Intrinsic::cos:
715   case Intrinsic::exp:
716   case Intrinsic::exp2:
717   case Intrinsic::log:
718   case Intrinsic::log10:
719   case Intrinsic::log2:
720   case Intrinsic::fabs:
721   case Intrinsic::floor:
722   case Intrinsic::ceil:
723   case Intrinsic::trunc:
724   case Intrinsic::rint:
725   case Intrinsic::nearbyint:
726   case Intrinsic::pow:
727   case Intrinsic::fma:
728   case Intrinsic::fmuladd:
729     return true;
730   default:
731     return false;
732   }
733   return false;
734 }
735
736 void
737 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
738   //===------------------------------------------------===//
739   //
740   // Notice: any optimization or new instruction that go
741   // into the code below should be also be implemented in
742   // the cost-model.
743   //
744   //===------------------------------------------------===//
745   BasicBlock &BB = *OrigLoop->getHeader();
746   Constant *Zero =
747   ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
748
749   // In order to support reduction variables we need to be able to vectorize
750   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
751   // stages. First, we create a new vector PHI node with no incoming edges.
752   // We use this value when we vectorize all of the instructions that use the
753   // PHI. Next, after all of the instructions in the block are complete we
754   // add the new incoming edges to the PHI. At this point all of the
755   // instructions in the basic block are vectorized, so we can use them to
756   // construct the PHI.
757   PhiVector RdxPHIsToFix;
758
759   // Scan the loop in a topological order to ensure that defs are vectorized
760   // before users.
761   LoopBlocksDFS DFS(OrigLoop);
762   DFS.perform(LI);
763
764   // Vectorize all of the blocks in the original loop.
765   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
766        be = DFS.endRPO(); bb != be; ++bb)
767     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
768
769   // At this point every instruction in the original loop is widened to
770   // a vector form. We are almost done. Now, we need to fix the PHI nodes
771   // that we vectorized. The PHI nodes are currently empty because we did
772   // not want to introduce cycles. Notice that the remaining PHI nodes
773   // that we need to fix are reduction variables.
774
775   // Create the 'reduced' values for each of the induction vars.
776   // The reduced values are the vector values that we scalarize and combine
777   // after the loop is finished.
778   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
779        it != e; ++it) {
780     PHINode *RdxPhi = *it;
781     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
782     assert(RdxPhi && "Unable to recover vectorized PHI");
783
784     // Find the reduction variable descriptor.
785     assert(Legal->getReductionVars()->count(RdxPhi) &&
786            "Unable to find the reduction variable");
787     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
788     (*Legal->getReductionVars())[RdxPhi];
789
790     // We need to generate a reduction vector from the incoming scalar.
791     // To do so, we need to generate the 'identity' vector and overide
792     // one of the elements with the incoming scalar reduction. We need
793     // to do it in the vector-loop preheader.
794     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
795
796     // This is the vector-clone of the value that leaves the loop.
797     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
798     Type *VecTy = VectorExit->getType();
799
800     // Find the reduction identity variable. Zero for addition, or, xor,
801     // one for multiplication, -1 for And.
802     Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
803                                           VecTy->getScalarType());
804
805     // This vector is the Identity vector where the first element is the
806     // incoming scalar reduction.
807     Value *VectorStart = Builder.CreateInsertElement(Identity,
808                                                      RdxDesc.StartValue, Zero);
809
810     // Fix the vector-loop phi.
811     // We created the induction variable so we know that the
812     // preheader is the first entry.
813     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
814
815     // Reductions do not have to start at zero. They can start with
816     // any loop invariant values.
817     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
818     Value *Val =
819     getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
820     VecRdxPhi->addIncoming(Val, LoopVectorBody);
821
822     // Before each round, move the insertion point right between
823     // the PHIs and the values we are going to write.
824     // This allows us to write both PHINodes and the extractelement
825     // instructions.
826     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
827
828     // This PHINode contains the vectorized reduction variable, or
829     // the initial value vector, if we bypass the vector loop.
830     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
831     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
832     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
833
834     // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
835     // and vector ops, reducing the set of values being computed by half each
836     // round.
837     assert(isPowerOf2_32(VF) &&
838            "Reduction emission only supported for pow2 vectors!");
839     Value *TmpVec = NewPhi;
840     SmallVector<Constant*, 32> ShuffleMask(VF, 0);
841     for (unsigned i = VF; i != 1; i >>= 1) {
842       // Move the upper half of the vector to the lower half.
843       for (unsigned j = 0; j != i/2; ++j)
844         ShuffleMask[j] = Builder.getInt32(i/2 + j);
845
846       // Fill the rest of the mask with undef.
847       std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
848                 UndefValue::get(Builder.getInt32Ty()));
849
850       Value *Shuf =
851         Builder.CreateShuffleVector(TmpVec,
852                                     UndefValue::get(TmpVec->getType()),
853                                     ConstantVector::get(ShuffleMask),
854                                     "rdx.shuf");
855
856       // Emit the operation on the shuffled value.
857       switch (RdxDesc.Kind) {
858       case LoopVectorizationLegality::IntegerAdd:
859         TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
860         break;
861       case LoopVectorizationLegality::IntegerMult:
862         TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
863         break;
864       case LoopVectorizationLegality::IntegerOr:
865         TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
866         break;
867       case LoopVectorizationLegality::IntegerAnd:
868         TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
869         break;
870       case LoopVectorizationLegality::IntegerXor:
871         TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
872         break;
873       default:
874         llvm_unreachable("Unknown reduction operation");
875       }
876     }
877
878     // The result is in the first element of the vector.
879     Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
880
881     // Now, we need to fix the users of the reduction variable
882     // inside and outside of the scalar remainder loop.
883     // We know that the loop is in LCSSA form. We need to update the
884     // PHI nodes in the exit blocks.
885     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
886          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
887       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
888       if (!LCSSAPhi) continue;
889
890       // All PHINodes need to have a single entry edge, or two if
891       // we already fixed them.
892       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
893
894       // We found our reduction value exit-PHI. Update it with the
895       // incoming bypass edge.
896       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
897         // Add an edge coming from the bypass.
898         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
899         break;
900       }
901     }// end of the LCSSA phi scan.
902
903     // Fix the scalar loop reduction variable with the incoming reduction sum
904     // from the vector body and from the backedge value.
905     int IncomingEdgeBlockIdx =
906     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
907     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
908     // Pick the other block.
909     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
910     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
911     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
912   }// end of for each redux variable.
913
914   // The Loop exit block may have single value PHI nodes where the incoming
915   // value is 'undef'. While vectorizing we only handled real values that
916   // were defined inside the loop. Here we handle the 'undef case'.
917   // See PR14725.
918   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
919        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
920     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
921     if (!LCSSAPhi) continue;
922     if (LCSSAPhi->getNumIncomingValues() == 1)
923       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
924                             LoopMiddleBlock);
925   }
926 }
927
928 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
929   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
930          "Invalid edge");
931
932   Value *SrcMask = createBlockInMask(Src);
933
934   // The terminator has to be a branch inst!
935   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
936   assert(BI && "Unexpected terminator found");
937
938   Value *EdgeMask = SrcMask;
939   if (BI->isConditional()) {
940     EdgeMask = getVectorValue(BI->getCondition());
941     if (BI->getSuccessor(0) != Dst)
942       EdgeMask = Builder.CreateNot(EdgeMask);
943   }
944
945   return Builder.CreateAnd(EdgeMask, SrcMask);
946 }
947
948 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
949   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
950
951   // Loop incoming mask is all-one.
952   if (OrigLoop->getHeader() == BB) {
953     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
954     return getVectorValue(C);
955   }
956
957   // This is the block mask. We OR all incoming edges, and with zero.
958   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
959   Value *BlockMask = getVectorValue(Zero);
960
961   // For each pred:
962   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
963     BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
964
965   return BlockMask;
966 }
967
968 void
969 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
970                                           BasicBlock *BB, PhiVector *PV) {
971   Constant *Zero = Builder.getInt32(0);
972
973   // For each instruction in the old loop.
974   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
975     switch (it->getOpcode()) {
976     case Instruction::Br:
977       // Nothing to do for PHIs and BR, since we already took care of the
978       // loop control flow instructions.
979       continue;
980     case Instruction::PHI:{
981       PHINode* P = cast<PHINode>(it);
982       // Handle reduction variables:
983       if (Legal->getReductionVars()->count(P)) {
984         // This is phase one of vectorizing PHIs.
985         Type *VecTy = VectorType::get(it->getType(), VF);
986         WidenMap[it] =
987           PHINode::Create(VecTy, 2, "vec.phi",
988                           LoopVectorBody->getFirstInsertionPt());
989         PV->push_back(P);
990         continue;
991       }
992
993       // Check for PHI nodes that are lowered to vector selects.
994       if (P->getParent() != OrigLoop->getHeader()) {
995         // We know that all PHIs in non header blocks are converted into
996         // selects, so we don't have to worry about the insertion order and we
997         // can just use the builder.
998
999         // At this point we generate the predication tree. There may be
1000         // duplications since this is a simple recursive scan, but future
1001         // optimizations will clean it up.
1002         Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
1003         WidenMap[P] =
1004           Builder.CreateSelect(Cond,
1005                                getVectorValue(P->getIncomingValue(0)),
1006                                getVectorValue(P->getIncomingValue(1)),
1007                                "predphi");
1008         continue;
1009       }
1010
1011       // This PHINode must be an induction variable.
1012       // Make sure that we know about it.
1013       assert(Legal->getInductionVars()->count(P) &&
1014              "Not an induction variable");
1015
1016       LoopVectorizationLegality::InductionInfo II =
1017         Legal->getInductionVars()->lookup(P);
1018
1019       switch (II.IK) {
1020       case LoopVectorizationLegality::NoInduction:
1021         llvm_unreachable("Unknown induction");
1022       case LoopVectorizationLegality::IntInduction: {
1023         assert(P == OldInduction && "Unexpected PHI");
1024         Value *Broadcasted = getBroadcastInstrs(Induction);
1025         // After broadcasting the induction variable we need to make the
1026         // vector consecutive by adding 0, 1, 2 ...
1027         Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1028         WidenMap[OldInduction] = ConsecutiveInduction;
1029         continue;
1030       }
1031       case LoopVectorizationLegality::ReverseIntInduction:
1032       case LoopVectorizationLegality::PtrInduction:
1033         // Handle reverse integer and pointer inductions.
1034         Value *StartIdx = 0;
1035         // If we have a single integer induction variable then use it.
1036         // Otherwise, start counting at zero.
1037         if (OldInduction) {
1038           LoopVectorizationLegality::InductionInfo OldII =
1039             Legal->getInductionVars()->lookup(OldInduction);
1040           StartIdx = OldII.StartValue;
1041         } else {
1042           StartIdx = ConstantInt::get(Induction->getType(), 0);
1043         }
1044         // This is the normalized GEP that starts counting at zero.
1045         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1046                                                  "normalized.idx");
1047
1048         // Handle the reverse integer induction variable case.
1049         if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1050           IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1051           Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1052                                                  "resize.norm.idx");
1053           Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1054                                                  "reverse.idx");
1055
1056           // This is a new value so do not hoist it out.
1057           Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1058           // After broadcasting the induction variable we need to make the
1059           // vector consecutive by adding  ... -3, -2, -1, 0.
1060           Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1061                                                              true);
1062           WidenMap[it] = ConsecutiveInduction;
1063           continue;
1064         }
1065
1066         // Handle the pointer induction variable case.
1067         assert(P->getType()->isPointerTy() && "Unexpected type.");
1068
1069         // This is the vector of results. Notice that we don't generate
1070         // vector geps because scalar geps result in better code.
1071         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1072         for (unsigned int i = 0; i < VF; ++i) {
1073           Constant *Idx = ConstantInt::get(Induction->getType(), i);
1074           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1075                                                "gep.idx");
1076           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1077                                              "next.gep");
1078           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1079                                                Builder.getInt32(i),
1080                                                "insert.gep");
1081         }
1082
1083         WidenMap[it] = VecVal;
1084         continue;
1085       }
1086
1087     }// End of PHI.
1088
1089     case Instruction::Add:
1090     case Instruction::FAdd:
1091     case Instruction::Sub:
1092     case Instruction::FSub:
1093     case Instruction::Mul:
1094     case Instruction::FMul:
1095     case Instruction::UDiv:
1096     case Instruction::SDiv:
1097     case Instruction::FDiv:
1098     case Instruction::URem:
1099     case Instruction::SRem:
1100     case Instruction::FRem:
1101     case Instruction::Shl:
1102     case Instruction::LShr:
1103     case Instruction::AShr:
1104     case Instruction::And:
1105     case Instruction::Or:
1106     case Instruction::Xor: {
1107       // Just widen binops.
1108       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1109       Value *A = getVectorValue(it->getOperand(0));
1110       Value *B = getVectorValue(it->getOperand(1));
1111
1112       // Use this vector value for all users of the original instruction.
1113       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1114       WidenMap[it] = V;
1115
1116       // Update the NSW, NUW and Exact flags.
1117       BinaryOperator *VecOp = cast<BinaryOperator>(V);
1118       if (isa<OverflowingBinaryOperator>(BinOp)) {
1119         VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1120         VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1121       }
1122       if (isa<PossiblyExactOperator>(VecOp))
1123         VecOp->setIsExact(BinOp->isExact());
1124       break;
1125     }
1126     case Instruction::Select: {
1127       // Widen selects.
1128       // If the selector is loop invariant we can create a select
1129       // instruction with a scalar condition. Otherwise, use vector-select.
1130       Value *Cond = it->getOperand(0);
1131       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1132
1133       // The condition can be loop invariant  but still defined inside the
1134       // loop. This means that we can't just use the original 'cond' value.
1135       // We have to take the 'vectorized' value and pick the first lane.
1136       // Instcombine will make this a no-op.
1137       Cond = getVectorValue(Cond);
1138       if (InvariantCond)
1139         Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1140
1141       Value *Op0 = getVectorValue(it->getOperand(1));
1142       Value *Op1 = getVectorValue(it->getOperand(2));
1143       WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1144       break;
1145     }
1146
1147     case Instruction::ICmp:
1148     case Instruction::FCmp: {
1149       // Widen compares. Generate vector compares.
1150       bool FCmp = (it->getOpcode() == Instruction::FCmp);
1151       CmpInst *Cmp = dyn_cast<CmpInst>(it);
1152       Value *A = getVectorValue(it->getOperand(0));
1153       Value *B = getVectorValue(it->getOperand(1));
1154       if (FCmp)
1155         WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1156       else
1157         WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1158       break;
1159     }
1160
1161     case Instruction::Store: {
1162       // Attempt to issue a wide store.
1163       StoreInst *SI = dyn_cast<StoreInst>(it);
1164       Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1165       Value *Ptr = SI->getPointerOperand();
1166       unsigned Alignment = SI->getAlignment();
1167
1168       assert(!Legal->isUniform(Ptr) &&
1169              "We do not allow storing to uniform addresses");
1170
1171
1172       int Stride = Legal->isConsecutivePtr(Ptr);
1173       bool Reverse = Stride < 0;
1174       if (Stride == 0) {
1175         scalarizeInstruction(it);
1176         break;
1177       }
1178
1179       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1180       if (Gep) {
1181         // The last index does not have to be the induction. It can be
1182         // consecutive and be a function of the index. For example A[I+1];
1183         unsigned NumOperands = Gep->getNumOperands();
1184         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1185         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1186
1187         // Create the new GEP with the new induction variable.
1188         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1189         Gep2->setOperand(NumOperands - 1, LastIndex);
1190         Ptr = Builder.Insert(Gep2);
1191       } else {
1192         // Use the induction element ptr.
1193         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1194         Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1195       }
1196
1197       // If the address is consecutive but reversed, then the
1198       // wide load needs to start at the last vector element.
1199       if (Reverse)
1200         Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1201
1202       Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1203       Value *Val = getVectorValue(SI->getValueOperand());
1204       if (Reverse)
1205         Val = reverseVector(Val);
1206       Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1207       break;
1208     }
1209     case Instruction::Load: {
1210       // Attempt to issue a wide load.
1211       LoadInst *LI = dyn_cast<LoadInst>(it);
1212       Type *RetTy = VectorType::get(LI->getType(), VF);
1213       Value *Ptr = LI->getPointerOperand();
1214       unsigned Alignment = LI->getAlignment();
1215
1216       // If the pointer is loop invariant or if it is non consecutive,
1217       // scalarize the load.
1218       int Stride = Legal->isConsecutivePtr(Ptr);
1219       bool Reverse = Stride < 0;
1220       if (Legal->isUniform(Ptr) || Stride == 0) {
1221         scalarizeInstruction(it);
1222         break;
1223       }
1224
1225       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1226       if (Gep) {
1227         // The last index does not have to be the induction. It can be
1228         // consecutive and be a function of the index. For example A[I+1];
1229         unsigned NumOperands = Gep->getNumOperands();
1230         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1231         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1232
1233         // Create the new GEP with the new induction variable.
1234         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1235         Gep2->setOperand(NumOperands - 1, LastIndex);
1236         Ptr = Builder.Insert(Gep2);
1237       } else {
1238         // Use the induction element ptr.
1239         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1240         Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1241       }
1242       // If the address is consecutive but reversed, then the
1243       // wide load needs to start at the last vector element.
1244       if (Reverse)
1245         Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1246
1247       Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1248       LI = Builder.CreateLoad(Ptr);
1249       LI->setAlignment(Alignment);
1250
1251       // Use this vector value for all users of the load.
1252       WidenMap[it] = Reverse ? reverseVector(LI) :  LI;
1253       break;
1254     }
1255     case Instruction::ZExt:
1256     case Instruction::SExt:
1257     case Instruction::FPToUI:
1258     case Instruction::FPToSI:
1259     case Instruction::FPExt:
1260     case Instruction::PtrToInt:
1261     case Instruction::IntToPtr:
1262     case Instruction::SIToFP:
1263     case Instruction::UIToFP:
1264     case Instruction::Trunc:
1265     case Instruction::FPTrunc:
1266     case Instruction::BitCast: {
1267       CastInst *CI = dyn_cast<CastInst>(it);
1268       /// Optimize the special case where the source is the induction
1269       /// variable. Notice that we can only optimize the 'trunc' case
1270       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1271       /// c. other casts depend on pointer size.
1272       if (CI->getOperand(0) == OldInduction &&
1273           it->getOpcode() == Instruction::Trunc) {
1274         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1275                                                CI->getType());
1276         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1277         WidenMap[it] = getConsecutiveVector(Broadcasted);
1278         break;
1279       }
1280       /// Vectorize casts.
1281       Value *A = getVectorValue(it->getOperand(0));
1282       Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1283       WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1284       break;
1285     }
1286
1287     case Instruction::Call: {
1288       assert(isTriviallyVectorizableIntrinsic(it));
1289       Module *M = BB->getParent()->getParent();
1290       IntrinsicInst *II = cast<IntrinsicInst>(it);
1291       Intrinsic::ID ID = II->getIntrinsicID();
1292       SmallVector<Value*, 4> Args;
1293       for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1294         Args.push_back(getVectorValue(II->getArgOperand(i)));
1295       Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1296       Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1297       WidenMap[it] = Builder.CreateCall(F, Args);
1298       break;
1299     }
1300
1301     default:
1302       // All other instructions are unsupported. Scalarize them.
1303       scalarizeInstruction(it);
1304       break;
1305     }// end of switch.
1306   }// end of for_each instr.
1307 }
1308
1309 void InnerLoopVectorizer::updateAnalysis() {
1310   // Forget the original basic block.
1311   SE->forgetLoop(OrigLoop);
1312
1313   // Update the dominator tree information.
1314   assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1315          "Entry does not dominate exit.");
1316
1317   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1318   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1319   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1320   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1321   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1322   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1323
1324   DEBUG(DT->verifyAnalysis());
1325 }
1326
1327 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1328   if (!EnableIfConversion)
1329     return false;
1330
1331   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1332   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1333
1334   // Collect the blocks that need predication.
1335   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1336     BasicBlock *BB = LoopBlocks[i];
1337
1338     // We don't support switch statements inside loops.
1339     if (!isa<BranchInst>(BB->getTerminator()))
1340       return false;
1341
1342     // We must have at most two predecessors because we need to convert
1343     // all PHIs to selects.
1344     unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1345     if (Preds > 2)
1346       return false;
1347
1348     // We must be able to predicate all blocks that need to be predicated.
1349     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1350       return false;
1351   }
1352
1353   // We can if-convert this loop.
1354   return true;
1355 }
1356
1357 bool LoopVectorizationLegality::canVectorize() {
1358   assert(TheLoop->getLoopPreheader() && "No preheader!!");
1359
1360   // We can only vectorize innermost loops.
1361   if (TheLoop->getSubLoopsVector().size())
1362     return false;
1363
1364   // We must have a single backedge.
1365   if (TheLoop->getNumBackEdges() != 1)
1366     return false;
1367
1368   // We must have a single exiting block.
1369   if (!TheLoop->getExitingBlock())
1370     return false;
1371
1372   unsigned NumBlocks = TheLoop->getNumBlocks();
1373
1374   // Check if we can if-convert non single-bb loops.
1375   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1376     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1377     return false;
1378   }
1379
1380   // We need to have a loop header.
1381   BasicBlock *Latch = TheLoop->getLoopLatch();
1382   DEBUG(dbgs() << "LV: Found a loop: " <<
1383         TheLoop->getHeader()->getName() << "\n");
1384
1385   // ScalarEvolution needs to be able to find the exit count.
1386   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1387   if (ExitCount == SE->getCouldNotCompute()) {
1388     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1389     return false;
1390   }
1391
1392   // Do not loop-vectorize loops with a tiny trip count.
1393   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1394   if (TC > 0u && TC < TinyTripCountThreshold) {
1395     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1396           "This loop is not worth vectorizing.\n");
1397     return false;
1398   }
1399
1400   // Check if we can vectorize the instructions and CFG in this loop.
1401   if (!canVectorizeInstrs()) {
1402     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1403     return false;
1404   }
1405
1406   // Go over each instruction and look at memory deps.
1407   if (!canVectorizeMemory()) {
1408     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1409     return false;
1410   }
1411
1412   // Collect all of the variables that remain uniform after vectorization.
1413   collectLoopUniforms();
1414
1415   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1416         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1417         <<"!\n");
1418
1419   // Okay! We can vectorize. At this point we don't have any other mem analysis
1420   // which may limit our maximum vectorization factor, so just return true with
1421   // no restrictions.
1422   return true;
1423 }
1424
1425 bool LoopVectorizationLegality::canVectorizeInstrs() {
1426   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1427   BasicBlock *Header = TheLoop->getHeader();
1428
1429   // For each block in the loop.
1430   for (Loop::block_iterator bb = TheLoop->block_begin(),
1431        be = TheLoop->block_end(); bb != be; ++bb) {
1432
1433     // Scan the instructions in the block and look for hazards.
1434     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1435          ++it) {
1436
1437       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1438         // This should not happen because the loop should be normalized.
1439         if (Phi->getNumIncomingValues() != 2) {
1440           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1441           return false;
1442         }
1443
1444         // Check that this PHI type is allowed.
1445         if (!Phi->getType()->isIntegerTy() &&
1446             !Phi->getType()->isPointerTy()) {
1447           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1448           return false;
1449         }
1450
1451         // If this PHINode is not in the header block, then we know that we
1452         // can convert it to select during if-conversion. No need to check if
1453         // the PHIs in this block are induction or reduction variables.
1454         if (*bb != Header)
1455           continue;
1456
1457         // This is the value coming from the preheader.
1458         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1459         // Check if this is an induction variable.
1460         InductionKind IK = isInductionVariable(Phi);
1461
1462         if (NoInduction != IK) {
1463           // Int inductions are special because we only allow one IV.
1464           if (IK == IntInduction) {
1465             if (Induction) {
1466               DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1467               return false;
1468             }
1469             Induction = Phi;
1470           }
1471
1472           DEBUG(dbgs() << "LV: Found an induction variable.\n");
1473           Inductions[Phi] = InductionInfo(StartValue, IK);
1474           continue;
1475         }
1476
1477         if (AddReductionVar(Phi, IntegerAdd)) {
1478           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1479           continue;
1480         }
1481         if (AddReductionVar(Phi, IntegerMult)) {
1482           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1483           continue;
1484         }
1485         if (AddReductionVar(Phi, IntegerOr)) {
1486           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1487           continue;
1488         }
1489         if (AddReductionVar(Phi, IntegerAnd)) {
1490           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1491           continue;
1492         }
1493         if (AddReductionVar(Phi, IntegerXor)) {
1494           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1495           continue;
1496         }
1497
1498         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1499         return false;
1500       }// end of PHI handling
1501
1502       // We still don't handle functions.
1503       CallInst *CI = dyn_cast<CallInst>(it);
1504       if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1505         DEBUG(dbgs() << "LV: Found a call site.\n");
1506         return false;
1507       }
1508
1509       // Check that the instruction return type is vectorizable.
1510       if (!VectorType::isValidElementType(it->getType()) &&
1511           !it->getType()->isVoidTy()) {
1512         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1513         return false;
1514       }
1515
1516       // Check that the stored type is vectorizable.
1517       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
1518         Type *T = ST->getValueOperand()->getType();
1519         if (!VectorType::isValidElementType(T))
1520           return false;
1521       }
1522
1523       // Reduction instructions are allowed to have exit users.
1524       // All other instructions must not have external users.
1525       if (!AllowedExit.count(it))
1526         //Check that all of the users of the loop are inside the BB.
1527         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1528              I != E; ++I) {
1529           Instruction *U = cast<Instruction>(*I);
1530           // This user may be a reduction exit value.
1531           if (!TheLoop->contains(U)) {
1532             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1533             return false;
1534           }
1535         }
1536     } // next instr.
1537
1538   }
1539
1540   if (!Induction) {
1541     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1542     assert(getInductionVars()->size() && "No induction variables");
1543   }
1544
1545   return true;
1546 }
1547
1548 void LoopVectorizationLegality::collectLoopUniforms() {
1549   // We now know that the loop is vectorizable!
1550   // Collect variables that will remain uniform after vectorization.
1551   std::vector<Value*> Worklist;
1552   BasicBlock *Latch = TheLoop->getLoopLatch();
1553
1554   // Start with the conditional branch and walk up the block.
1555   Worklist.push_back(Latch->getTerminator()->getOperand(0));
1556
1557   while (Worklist.size()) {
1558     Instruction *I = dyn_cast<Instruction>(Worklist.back());
1559     Worklist.pop_back();
1560
1561     // Look at instructions inside this loop.
1562     // Stop when reaching PHI nodes.
1563     // TODO: we need to follow values all over the loop, not only in this block.
1564     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1565       continue;
1566
1567     // This is a known uniform.
1568     Uniforms.insert(I);
1569
1570     // Insert all operands.
1571     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1572       Worklist.push_back(I->getOperand(i));
1573     }
1574   }
1575 }
1576
1577 bool LoopVectorizationLegality::canVectorizeMemory() {
1578   typedef SmallVector<Value*, 16> ValueVector;
1579   typedef SmallPtrSet<Value*, 16> ValueSet;
1580   // Holds the Load and Store *instructions*.
1581   ValueVector Loads;
1582   ValueVector Stores;
1583   PtrRtCheck.Pointers.clear();
1584   PtrRtCheck.Need = false;
1585
1586   // For each block.
1587   for (Loop::block_iterator bb = TheLoop->block_begin(),
1588        be = TheLoop->block_end(); bb != be; ++bb) {
1589
1590     // Scan the BB and collect legal loads and stores.
1591     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1592          ++it) {
1593
1594       // If this is a load, save it. If this instruction can read from memory
1595       // but is not a load, then we quit. Notice that we don't handle function
1596       // calls that read or write.
1597       if (it->mayReadFromMemory()) {
1598         LoadInst *Ld = dyn_cast<LoadInst>(it);
1599         if (!Ld) return false;
1600         if (!Ld->isSimple()) {
1601           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1602           return false;
1603         }
1604         Loads.push_back(Ld);
1605         continue;
1606       }
1607
1608       // Save 'store' instructions. Abort if other instructions write to memory.
1609       if (it->mayWriteToMemory()) {
1610         StoreInst *St = dyn_cast<StoreInst>(it);
1611         if (!St) return false;
1612         if (!St->isSimple()) {
1613           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1614           return false;
1615         }
1616         Stores.push_back(St);
1617       }
1618     } // next instr.
1619   } // next block.
1620
1621   // Now we have two lists that hold the loads and the stores.
1622   // Next, we find the pointers that they use.
1623
1624   // Check if we see any stores. If there are no stores, then we don't
1625   // care if the pointers are *restrict*.
1626   if (!Stores.size()) {
1627     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1628     return true;
1629   }
1630
1631   // Holds the read and read-write *pointers* that we find.
1632   ValueVector Reads;
1633   ValueVector ReadWrites;
1634
1635   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1636   // multiple times on the same object. If the ptr is accessed twice, once
1637   // for read and once for write, it will only appear once (on the write
1638   // list). This is okay, since we are going to check for conflicts between
1639   // writes and between reads and writes, but not between reads and reads.
1640   ValueSet Seen;
1641
1642   ValueVector::iterator I, IE;
1643   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1644     StoreInst *ST = cast<StoreInst>(*I);
1645     Value* Ptr = ST->getPointerOperand();
1646
1647     if (isUniform(Ptr)) {
1648       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1649       return false;
1650     }
1651
1652     // If we did *not* see this pointer before, insert it to
1653     // the read-write list. At this phase it is only a 'write' list.
1654     if (Seen.insert(Ptr))
1655       ReadWrites.push_back(Ptr);
1656   }
1657
1658   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1659     LoadInst *LD = cast<LoadInst>(*I);
1660     Value* Ptr = LD->getPointerOperand();
1661     // If we did *not* see this pointer before, insert it to the
1662     // read list. If we *did* see it before, then it is already in
1663     // the read-write list. This allows us to vectorize expressions
1664     // such as A[i] += x;  Because the address of A[i] is a read-write
1665     // pointer. This only works if the index of A[i] is consecutive.
1666     // If the address of i is unknown (for example A[B[i]]) then we may
1667     // read a few words, modify, and write a few words, and some of the
1668     // words may be written to the same address.
1669     if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
1670       Reads.push_back(Ptr);
1671   }
1672
1673   // If we write (or read-write) to a single destination and there are no
1674   // other reads in this loop then is it safe to vectorize.
1675   if (ReadWrites.size() == 1 && Reads.size() == 0) {
1676     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1677     return true;
1678   }
1679
1680   // Find pointers with computable bounds. We are going to use this information
1681   // to place a runtime bound check.
1682   bool CanDoRT = true;
1683   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1684     if (hasComputableBounds(*I)) {
1685       PtrRtCheck.insert(SE, TheLoop, *I);
1686       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1687     } else {
1688       CanDoRT = false;
1689       break;
1690     }
1691   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1692     if (hasComputableBounds(*I)) {
1693       PtrRtCheck.insert(SE, TheLoop, *I);
1694       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1695     } else {
1696       CanDoRT = false;
1697       break;
1698     }
1699
1700   // Check that we did not collect too many pointers or found a
1701   // unsizeable pointer.
1702   if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1703     PtrRtCheck.reset();
1704     CanDoRT = false;
1705   }
1706
1707   if (CanDoRT) {
1708     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1709   }
1710
1711   bool NeedRTCheck = false;
1712
1713   // Now that the pointers are in two lists (Reads and ReadWrites), we
1714   // can check that there are no conflicts between each of the writes and
1715   // between the writes to the reads.
1716   ValueSet WriteObjects;
1717   ValueVector TempObjects;
1718
1719   // Check that the read-writes do not conflict with other read-write
1720   // pointers.
1721   bool AllWritesIdentified = true;
1722   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1723     GetUnderlyingObjects(*I, TempObjects, DL);
1724     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1725          it != e; ++it) {
1726       if (!isIdentifiedObject(*it)) {
1727         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1728         NeedRTCheck = true;
1729         AllWritesIdentified = false;
1730       }
1731       if (!WriteObjects.insert(*it)) {
1732         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1733               << **it <<"\n");
1734         return false;
1735       }
1736     }
1737     TempObjects.clear();
1738   }
1739
1740   /// Check that the reads don't conflict with the read-writes.
1741   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1742     GetUnderlyingObjects(*I, TempObjects, DL);
1743     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1744          it != e; ++it) {
1745       // If all of the writes are identified then we don't care if the read
1746       // pointer is identified or not.
1747       if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
1748         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1749         NeedRTCheck = true;
1750       }
1751       if (WriteObjects.count(*it)) {
1752         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1753               << **it <<"\n");
1754         return false;
1755       }
1756     }
1757     TempObjects.clear();
1758   }
1759
1760   PtrRtCheck.Need = NeedRTCheck;
1761   if (NeedRTCheck && !CanDoRT) {
1762     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1763           "the array bounds.\n");
1764     PtrRtCheck.reset();
1765     return false;
1766   }
1767
1768   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1769         " need a runtime memory check.\n");
1770   return true;
1771 }
1772
1773 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1774                                                 ReductionKind Kind) {
1775   if (Phi->getNumIncomingValues() != 2)
1776     return false;
1777
1778   // Reduction variables are only found in the loop header block.
1779   if (Phi->getParent() != TheLoop->getHeader())
1780     return false;
1781
1782   // Obtain the reduction start value from the value that comes from the loop
1783   // preheader.
1784   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1785
1786   // ExitInstruction is the single value which is used outside the loop.
1787   // We only allow for a single reduction value to be used outside the loop.
1788   // This includes users of the reduction, variables (which form a cycle
1789   // which ends in the phi node).
1790   Instruction *ExitInstruction = 0;
1791
1792   // Iter is our iterator. We start with the PHI node and scan for all of the
1793   // users of this instruction. All users must be instructions that can be
1794   // used as reduction variables (such as ADD). We may have a single
1795   // out-of-block user. The cycle must end with the original PHI.
1796   Instruction *Iter = Phi;
1797   while (true) {
1798     // If the instruction has no users then this is a broken
1799     // chain and can't be a reduction variable.
1800     if (Iter->use_empty())
1801       return false;
1802
1803     // Any reduction instr must be of one of the allowed kinds.
1804     if (!isReductionInstr(Iter, Kind))
1805       return false;
1806
1807     // Did we find a user inside this loop already ?
1808     bool FoundInBlockUser = false;
1809     // Did we reach the initial PHI node already ?
1810     bool FoundStartPHI = false;
1811
1812     // For each of the *users* of iter.
1813     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1814          it != e; ++it) {
1815       Instruction *U = cast<Instruction>(*it);
1816       // We already know that the PHI is a user.
1817       if (U == Phi) {
1818         FoundStartPHI = true;
1819         continue;
1820       }
1821
1822       // Check if we found the exit user.
1823       BasicBlock *Parent = U->getParent();
1824       if (!TheLoop->contains(Parent)) {
1825         // Exit if you find multiple outside users.
1826         if (ExitInstruction != 0)
1827           return false;
1828         ExitInstruction = Iter;
1829       }
1830
1831       // We allow in-loop PHINodes which are not the original reduction PHI
1832       // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1833       // structure) then don't skip this PHI.
1834       if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
1835           U->getParent() != TheLoop->getHeader() &&
1836           TheLoop->contains(U) &&
1837           Iter->getNumUses() > 1)
1838         continue;
1839
1840       // We can't have multiple inside users.
1841       if (FoundInBlockUser)
1842         return false;
1843       FoundInBlockUser = true;
1844       Iter = U;
1845     }
1846
1847     // We found a reduction var if we have reached the original
1848     // phi node and we only have a single instruction with out-of-loop
1849     // users.
1850     if (FoundStartPHI && ExitInstruction) {
1851       // This instruction is allowed to have out-of-loop users.
1852       AllowedExit.insert(ExitInstruction);
1853
1854       // Save the description of this reduction variable.
1855       ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1856       Reductions[Phi] = RD;
1857       return true;
1858     }
1859
1860     // If we've reached the start PHI but did not find an outside user then
1861     // this is dead code. Abort.
1862     if (FoundStartPHI)
1863       return false;
1864   }
1865 }
1866
1867 bool
1868 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1869                                             ReductionKind Kind) {
1870   switch (I->getOpcode()) {
1871   default:
1872     return false;
1873   case Instruction::PHI:
1874     // possibly.
1875     return true;
1876   case Instruction::Add:
1877   case Instruction::Sub:
1878     return Kind == IntegerAdd;
1879   case Instruction::Mul:
1880     return Kind == IntegerMult;
1881   case Instruction::And:
1882     return Kind == IntegerAnd;
1883   case Instruction::Or:
1884     return Kind == IntegerOr;
1885   case Instruction::Xor:
1886     return Kind == IntegerXor;
1887   }
1888 }
1889
1890 LoopVectorizationLegality::InductionKind
1891 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1892   Type *PhiTy = Phi->getType();
1893   // We only handle integer and pointer inductions variables.
1894   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1895     return NoInduction;
1896
1897   // Check that the PHI is consecutive and starts at zero.
1898   const SCEV *PhiScev = SE->getSCEV(Phi);
1899   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1900   if (!AR) {
1901     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1902     return NoInduction;
1903   }
1904   const SCEV *Step = AR->getStepRecurrence(*SE);
1905
1906   // Integer inductions need to have a stride of one.
1907   if (PhiTy->isIntegerTy()) {
1908     if (Step->isOne())
1909       return IntInduction;
1910     if (Step->isAllOnesValue())
1911       return ReverseIntInduction;
1912     return NoInduction;
1913   }
1914
1915   // Calculate the pointer stride and check if it is consecutive.
1916   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1917   if (!C)
1918     return NoInduction;
1919
1920   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1921   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1922   if (C->getValue()->equalsInt(Size))
1923     return PtrInduction;
1924
1925   return NoInduction;
1926 }
1927
1928 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
1929   Value *In0 = const_cast<Value*>(V);
1930   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
1931   if (!PN)
1932     return false;
1933
1934   return Inductions.count(PN);
1935 }
1936
1937 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
1938   assert(TheLoop->contains(BB) && "Unknown block used");
1939
1940   // Blocks that do not dominate the latch need predication.
1941   BasicBlock* Latch = TheLoop->getLoopLatch();
1942   return !DT->dominates(BB, Latch);
1943 }
1944
1945 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1946   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1947     // We don't predicate loads/stores at the moment.
1948     if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1949       return false;
1950
1951     // The instructions below can trap.
1952     switch (it->getOpcode()) {
1953     default: continue;
1954     case Instruction::UDiv:
1955     case Instruction::SDiv:
1956     case Instruction::URem:
1957     case Instruction::SRem:
1958              return false;
1959     }
1960   }
1961
1962   return true;
1963 }
1964
1965 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1966   const SCEV *PhiScev = SE->getSCEV(Ptr);
1967   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1968   if (!AR)
1969     return false;
1970
1971   return AR->isAffine();
1972 }
1973
1974 unsigned
1975 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1976                                                         unsigned UserVF) {
1977   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1978     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1979     return 1;
1980   }
1981
1982   // Find the trip count.
1983   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1984   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1985
1986   unsigned VF = MaxVectorSize;
1987
1988   // If we optimize the program for size, avoid creating the tail loop.
1989   if (OptForSize) {
1990     // If we are unable to calculate the trip count then don't try to vectorize.
1991     if (TC < 2) {
1992       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1993       return 1;
1994     }
1995
1996     // Find the maximum SIMD width that can fit within the trip count.
1997     VF = TC % MaxVectorSize;
1998
1999     if (VF == 0)
2000       VF = MaxVectorSize;
2001
2002     // If the trip count that we found modulo the vectorization factor is not
2003     // zero then we require a tail.
2004     if (VF < 2) {
2005       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2006       return 1;
2007     }
2008   }
2009
2010   if (UserVF != 0) {
2011     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2012     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2013
2014     return UserVF;
2015   }
2016
2017   if (!VTTI) {
2018     DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2019     return 1;
2020   }
2021
2022   float Cost = expectedCost(1);
2023   unsigned Width = 1;
2024   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2025   for (unsigned i=2; i <= VF; i*=2) {
2026     // Notice that the vector loop needs to be executed less times, so
2027     // we need to divide the cost of the vector loops by the width of
2028     // the vector elements.
2029     float VectorCost = expectedCost(i) / (float)i;
2030     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2031           (int)VectorCost << ".\n");
2032     if (VectorCost < Cost) {
2033       Cost = VectorCost;
2034       Width = i;
2035     }
2036   }
2037
2038   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2039   return Width;
2040 }
2041
2042 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2043   unsigned Cost = 0;
2044
2045   // For each block.
2046   for (Loop::block_iterator bb = TheLoop->block_begin(),
2047        be = TheLoop->block_end(); bb != be; ++bb) {
2048     unsigned BlockCost = 0;
2049     BasicBlock *BB = *bb;
2050
2051     // For each instruction in the old loop.
2052     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2053       unsigned C = getInstructionCost(it, VF);
2054       Cost += C;
2055       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2056             VF << " For instruction: "<< *it << "\n");
2057     }
2058
2059     // We assume that if-converted blocks have a 50% chance of being executed.
2060     // When the code is scalar then some of the blocks are avoided due to CF.
2061     // When the code is vectorized we execute all code paths.
2062     if (Legal->blockNeedsPredication(*bb) && VF == 1)
2063       BlockCost /= 2;
2064
2065     Cost += BlockCost;
2066   }
2067
2068   return Cost;
2069 }
2070
2071 unsigned
2072 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2073   assert(VTTI && "Invalid vector target transformation info");
2074
2075   // If we know that this instruction will remain uniform, check the cost of
2076   // the scalar version.
2077   if (Legal->isUniformAfterVectorization(I))
2078     VF = 1;
2079
2080   Type *RetTy = I->getType();
2081   Type *VectorTy = ToVectorTy(RetTy, VF);
2082
2083   // TODO: We need to estimate the cost of intrinsic calls.
2084   switch (I->getOpcode()) {
2085   case Instruction::GetElementPtr:
2086     // We mark this instruction as zero-cost because scalar GEPs are usually
2087     // lowered to the intruction addressing mode. At the moment we don't
2088     // generate vector geps.
2089     return 0;
2090   case Instruction::Br: {
2091     return VTTI->getCFInstrCost(I->getOpcode());
2092   }
2093   case Instruction::PHI:
2094     //TODO: IF-converted IFs become selects.
2095     return 0;
2096   case Instruction::Add:
2097   case Instruction::FAdd:
2098   case Instruction::Sub:
2099   case Instruction::FSub:
2100   case Instruction::Mul:
2101   case Instruction::FMul:
2102   case Instruction::UDiv:
2103   case Instruction::SDiv:
2104   case Instruction::FDiv:
2105   case Instruction::URem:
2106   case Instruction::SRem:
2107   case Instruction::FRem:
2108   case Instruction::Shl:
2109   case Instruction::LShr:
2110   case Instruction::AShr:
2111   case Instruction::And:
2112   case Instruction::Or:
2113   case Instruction::Xor:
2114     return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2115   case Instruction::Select: {
2116     SelectInst *SI = cast<SelectInst>(I);
2117     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2118     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2119     Type *CondTy = SI->getCondition()->getType();
2120     if (ScalarCond)
2121       CondTy = VectorType::get(CondTy, VF);
2122
2123     return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2124   }
2125   case Instruction::ICmp:
2126   case Instruction::FCmp: {
2127     Type *ValTy = I->getOperand(0)->getType();
2128     VectorTy = ToVectorTy(ValTy, VF);
2129     return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2130   }
2131   case Instruction::Store: {
2132     StoreInst *SI = cast<StoreInst>(I);
2133     Type *ValTy = SI->getValueOperand()->getType();
2134     VectorTy = ToVectorTy(ValTy, VF);
2135
2136     if (VF == 1)
2137       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2138                                    SI->getAlignment(),
2139                                    SI->getPointerAddressSpace());
2140
2141     // Scalarized stores.
2142     int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2143     bool Reverse = Stride < 0;
2144     if (0 == Stride) {
2145       unsigned Cost = 0;
2146
2147       // The cost of extracting from the value vector and pointer vector.
2148       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2149       for (unsigned i = 0; i < VF; ++i) {
2150         Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2151                                          VectorTy, i);
2152         Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2153                                          PtrTy, i);
2154       }
2155
2156       // The cost of the scalar stores.
2157       Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2158                                          ValTy->getScalarType(),
2159                                          SI->getAlignment(),
2160                                          SI->getPointerAddressSpace());
2161       return Cost;
2162     }
2163
2164     // Wide stores.
2165     unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2166                                           SI->getAlignment(),
2167                                           SI->getPointerAddressSpace());
2168     if (Reverse)
2169       Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2170                                    VectorTy, 0);
2171     return Cost;
2172   }
2173   case Instruction::Load: {
2174     LoadInst *LI = cast<LoadInst>(I);
2175
2176     if (VF == 1)
2177       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2178                                    LI->getAlignment(),
2179                                    LI->getPointerAddressSpace());
2180
2181     // Scalarized loads.
2182     int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2183     bool Reverse = Stride < 0;
2184     if (0 == Stride) {
2185       unsigned Cost = 0;
2186       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2187
2188       // The cost of extracting from the pointer vector.
2189       for (unsigned i = 0; i < VF; ++i)
2190         Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2191                                          PtrTy, i);
2192
2193       // The cost of inserting data to the result vector.
2194       for (unsigned i = 0; i < VF; ++i)
2195         Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2196                                          VectorTy, i);
2197
2198       // The cost of the scalar stores.
2199       Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2200                                          RetTy->getScalarType(),
2201                                          LI->getAlignment(),
2202                                          LI->getPointerAddressSpace());
2203       return Cost;
2204     }
2205
2206     // Wide loads.
2207     unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2208                                           LI->getAlignment(),
2209                                           LI->getPointerAddressSpace());
2210     if (Reverse)
2211       Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2212                                    VectorTy, 0);
2213     return Cost;
2214   }
2215   case Instruction::ZExt:
2216   case Instruction::SExt:
2217   case Instruction::FPToUI:
2218   case Instruction::FPToSI:
2219   case Instruction::FPExt:
2220   case Instruction::PtrToInt:
2221   case Instruction::IntToPtr:
2222   case Instruction::SIToFP:
2223   case Instruction::UIToFP:
2224   case Instruction::Trunc:
2225   case Instruction::FPTrunc:
2226   case Instruction::BitCast: {
2227     // We optimize the truncation of induction variable.
2228     // The cost of these is the same as the scalar operation.
2229     if (I->getOpcode() == Instruction::Trunc &&
2230         Legal->isInductionVariable(I->getOperand(0)))
2231          return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2232                                        I->getOperand(0)->getType());
2233
2234     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2235     return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2236   }
2237   case Instruction::Call: {
2238     assert(isTriviallyVectorizableIntrinsic(I));
2239     IntrinsicInst *II = cast<IntrinsicInst>(I);
2240     Type *RetTy = ToVectorTy(II->getType(), VF);
2241     SmallVector<Type*, 4> Tys;
2242     for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2243       Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2244     return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2245   }
2246   default: {
2247     // We are scalarizing the instruction. Return the cost of the scalar
2248     // instruction, plus the cost of insert and extract into vector
2249     // elements, times the vector width.
2250     unsigned Cost = 0;
2251
2252     if (!RetTy->isVoidTy() && VF != 1) {
2253       unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2254                                                   VectorTy);
2255       unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2256                                                   VectorTy);
2257
2258       // The cost of inserting the results plus extracting each one of the
2259       // operands.
2260       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2261     }
2262
2263     // The cost of executing VF copies of the scalar instruction. This opcode
2264     // is unknown. Assume that it is the same as 'mul'.
2265     Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2266     return Cost;
2267   }
2268   }// end of switch.
2269 }
2270
2271 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2272   if (Scalar->isVoidTy() || VF == 1)
2273     return Scalar;
2274   return VectorType::get(Scalar, VF);
2275 }
2276
2277 char LoopVectorize::ID = 0;
2278 static const char lv_name[] = "Loop Vectorization";
2279 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2280 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2281 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2282 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2283 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2284
2285 namespace llvm {
2286   Pass *createLoopVectorizePass() {
2287     return new LoopVectorize();
2288   }
2289 }
2290
2291