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