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