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