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