LoopVectorize: Enable vectorization of the fmuladd intrinsic
[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   case Intrinsic::fmuladd:
715     return true;
716   default:
717     return false;
718   }
719   return false;
720 }
721
722 void
723 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
724   //===------------------------------------------------===//
725   //
726   // Notice: any optimization or new instruction that go
727   // into the code below should be also be implemented in
728   // the cost-model.
729   //
730   //===------------------------------------------------===//
731   BasicBlock &BB = *OrigLoop->getHeader();
732   Constant *Zero =
733   ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
734
735   // In order to support reduction variables we need to be able to vectorize
736   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
737   // stages. First, we create a new vector PHI node with no incoming edges.
738   // We use this value when we vectorize all of the instructions that use the
739   // PHI. Next, after all of the instructions in the block are complete we
740   // add the new incoming edges to the PHI. At this point all of the
741   // instructions in the basic block are vectorized, so we can use them to
742   // construct the PHI.
743   PhiVector RdxPHIsToFix;
744
745   // Scan the loop in a topological order to ensure that defs are vectorized
746   // before users.
747   LoopBlocksDFS DFS(OrigLoop);
748   DFS.perform(LI);
749
750   // Vectorize all of the blocks in the original loop.
751   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
752        be = DFS.endRPO(); bb != be; ++bb)
753     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
754
755   // At this point every instruction in the original loop is widened to
756   // a vector form. We are almost done. Now, we need to fix the PHI nodes
757   // that we vectorized. The PHI nodes are currently empty because we did
758   // not want to introduce cycles. Notice that the remaining PHI nodes
759   // that we need to fix are reduction variables.
760
761   // Create the 'reduced' values for each of the induction vars.
762   // The reduced values are the vector values that we scalarize and combine
763   // after the loop is finished.
764   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
765        it != e; ++it) {
766     PHINode *RdxPhi = *it;
767     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
768     assert(RdxPhi && "Unable to recover vectorized PHI");
769
770     // Find the reduction variable descriptor.
771     assert(Legal->getReductionVars()->count(RdxPhi) &&
772            "Unable to find the reduction variable");
773     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
774     (*Legal->getReductionVars())[RdxPhi];
775
776     // We need to generate a reduction vector from the incoming scalar.
777     // To do so, we need to generate the 'identity' vector and overide
778     // one of the elements with the incoming scalar reduction. We need
779     // to do it in the vector-loop preheader.
780     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
781
782     // This is the vector-clone of the value that leaves the loop.
783     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
784     Type *VecTy = VectorExit->getType();
785
786     // Find the reduction identity variable. Zero for addition, or, xor,
787     // one for multiplication, -1 for And.
788     Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
789                                           VecTy->getScalarType());
790
791     // This vector is the Identity vector where the first element is the
792     // incoming scalar reduction.
793     Value *VectorStart = Builder.CreateInsertElement(Identity,
794                                                      RdxDesc.StartValue, Zero);
795
796     // Fix the vector-loop phi.
797     // We created the induction variable so we know that the
798     // preheader is the first entry.
799     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
800
801     // Reductions do not have to start at zero. They can start with
802     // any loop invariant values.
803     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
804     Value *Val =
805     getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
806     VecRdxPhi->addIncoming(Val, LoopVectorBody);
807
808     // Before each round, move the insertion point right between
809     // the PHIs and the values we are going to write.
810     // This allows us to write both PHINodes and the extractelement
811     // instructions.
812     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
813
814     // This PHINode contains the vectorized reduction variable, or
815     // the initial value vector, if we bypass the vector loop.
816     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
817     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
818     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
819
820     // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
821     // and vector ops, reducing the set of values being computed by half each
822     // round.
823     assert(isPowerOf2_32(VF) &&
824            "Reduction emission only supported for pow2 vectors!");
825     Value *TmpVec = NewPhi;
826     SmallVector<Constant*, 32> ShuffleMask(VF, 0);
827     for (unsigned i = VF; i != 1; i >>= 1) {
828       // Move the upper half of the vector to the lower half.
829       for (unsigned j = 0; j != i/2; ++j)
830         ShuffleMask[j] = Builder.getInt32(i/2 + j);
831
832       // Fill the rest of the mask with undef.
833       std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
834                 UndefValue::get(Builder.getInt32Ty()));
835
836       Value *Shuf =
837         Builder.CreateShuffleVector(TmpVec,
838                                     UndefValue::get(TmpVec->getType()),
839                                     ConstantVector::get(ShuffleMask),
840                                     "rdx.shuf");
841
842       // Emit the operation on the shuffled value.
843       switch (RdxDesc.Kind) {
844       case LoopVectorizationLegality::IntegerAdd:
845         TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
846         break;
847       case LoopVectorizationLegality::IntegerMult:
848         TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
849         break;
850       case LoopVectorizationLegality::IntegerOr:
851         TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
852         break;
853       case LoopVectorizationLegality::IntegerAnd:
854         TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
855         break;
856       case LoopVectorizationLegality::IntegerXor:
857         TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
858         break;
859       default:
860         llvm_unreachable("Unknown reduction operation");
861       }
862     }
863
864     // The result is in the first element of the vector.
865     Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
866
867     // Now, we need to fix the users of the reduction variable
868     // inside and outside of the scalar remainder loop.
869     // We know that the loop is in LCSSA form. We need to update the
870     // PHI nodes in the exit blocks.
871     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
872          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
873       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
874       if (!LCSSAPhi) continue;
875
876       // All PHINodes need to have a single entry edge, or two if
877       // we already fixed them.
878       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
879
880       // We found our reduction value exit-PHI. Update it with the
881       // incoming bypass edge.
882       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
883         // Add an edge coming from the bypass.
884         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
885         break;
886       }
887     }// end of the LCSSA phi scan.
888
889     // Fix the scalar loop reduction variable with the incoming reduction sum
890     // from the vector body and from the backedge value.
891     int IncomingEdgeBlockIdx =
892     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
893     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
894     // Pick the other block.
895     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
896     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
897     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
898   }// end of for each redux variable.
899 }
900
901 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
902   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
903          "Invalid edge");
904
905   Value *SrcMask = createBlockInMask(Src);
906
907   // The terminator has to be a branch inst!
908   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
909   assert(BI && "Unexpected terminator found");
910
911   Value *EdgeMask = SrcMask;
912   if (BI->isConditional()) {
913     EdgeMask = getVectorValue(BI->getCondition());
914     if (BI->getSuccessor(0) != Dst)
915       EdgeMask = Builder.CreateNot(EdgeMask);
916   }
917
918   return Builder.CreateAnd(EdgeMask, SrcMask);
919 }
920
921 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
922   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
923
924   // Loop incoming mask is all-one.
925   if (OrigLoop->getHeader() == BB) {
926     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
927     return getVectorValue(C);
928   }
929
930   // This is the block mask. We OR all incoming edges, and with zero.
931   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
932   Value *BlockMask = getVectorValue(Zero);
933
934   // For each pred:
935   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
936     BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
937
938   return BlockMask;
939 }
940
941 void
942 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
943                                           BasicBlock *BB, PhiVector *PV) {
944   Constant *Zero =
945   ConstantInt::get(IntegerType::getInt32Ty(BB->getContext()), 0);
946
947   // For each instruction in the old loop.
948   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
949     switch (it->getOpcode()) {
950     case Instruction::Br:
951       // Nothing to do for PHIs and BR, since we already took care of the
952       // loop control flow instructions.
953       continue;
954     case Instruction::PHI:{
955       PHINode* P = cast<PHINode>(it);
956       // Handle reduction variables:
957       if (Legal->getReductionVars()->count(P)) {
958         // This is phase one of vectorizing PHIs.
959         Type *VecTy = VectorType::get(it->getType(), VF);
960         WidenMap[it] =
961           PHINode::Create(VecTy, 2, "vec.phi",
962                           LoopVectorBody->getFirstInsertionPt());
963         PV->push_back(P);
964         continue;
965       }
966
967       // Check for PHI nodes that are lowered to vector selects.
968       if (P->getParent() != OrigLoop->getHeader()) {
969         // We know that all PHIs in non header blocks are converted into
970         // selects, so we don't have to worry about the insertion order and we
971         // can just use the builder.
972
973         // At this point we generate the predication tree. There may be
974         // duplications since this is a simple recursive scan, but future
975         // optimizations will clean it up.
976         Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
977         WidenMap[P] =
978           Builder.CreateSelect(Cond,
979                                getVectorValue(P->getIncomingValue(0)),
980                                getVectorValue(P->getIncomingValue(1)),
981                                "predphi");
982         continue;
983       }
984
985       // This PHINode must be an induction variable.
986       // Make sure that we know about it.
987       assert(Legal->getInductionVars()->count(P) &&
988              "Not an induction variable");
989
990       LoopVectorizationLegality::InductionInfo II =
991         Legal->getInductionVars()->lookup(P);
992
993       switch (II.IK) {
994       case LoopVectorizationLegality::NoInduction:
995         llvm_unreachable("Unknown induction");
996       case LoopVectorizationLegality::IntInduction: {
997         assert(P == OldInduction && "Unexpected PHI");
998         Value *Broadcasted = getBroadcastInstrs(Induction);
999         // After broadcasting the induction variable we need to make the
1000         // vector consecutive by adding 0, 1, 2 ...
1001         Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1002         WidenMap[OldInduction] = ConsecutiveInduction;
1003         continue;
1004       }
1005       case LoopVectorizationLegality::ReverseIntInduction:
1006       case LoopVectorizationLegality::PtrInduction:
1007         // Handle reverse integer and pointer inductions.
1008         Value *StartIdx = 0;
1009         // If we have a single integer induction variable then use it.
1010         // Otherwise, start counting at zero.
1011         if (OldInduction) {
1012           LoopVectorizationLegality::InductionInfo OldII =
1013             Legal->getInductionVars()->lookup(OldInduction);
1014           StartIdx = OldII.StartValue;
1015         } else {
1016           StartIdx = ConstantInt::get(Induction->getType(), 0);
1017         }
1018         // This is the normalized GEP that starts counting at zero.
1019         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1020                                                  "normalized.idx");
1021
1022         // Handle the reverse integer induction variable case.
1023         if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1024           IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1025           Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1026                                                  "resize.norm.idx");
1027           Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1028                                                  "reverse.idx");
1029
1030           // This is a new value so do not hoist it out.
1031           Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1032           // After broadcasting the induction variable we need to make the
1033           // vector consecutive by adding  ... -3, -2, -1, 0.
1034           Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1035                                                              true);
1036           WidenMap[it] = ConsecutiveInduction;
1037           continue;
1038         }
1039
1040         // Handle the pointer induction variable case.
1041         assert(P->getType()->isPointerTy() && "Unexpected type.");
1042
1043         // This is the vector of results. Notice that we don't generate
1044         // vector geps because scalar geps result in better code.
1045         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1046         for (unsigned int i = 0; i < VF; ++i) {
1047           Constant *Idx = ConstantInt::get(Induction->getType(), i);
1048           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1049                                                "gep.idx");
1050           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1051                                              "next.gep");
1052           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1053                                                Builder.getInt32(i),
1054                                                "insert.gep");
1055         }
1056
1057         WidenMap[it] = VecVal;
1058         continue;
1059       }
1060
1061     }// End of PHI.
1062
1063     case Instruction::Add:
1064     case Instruction::FAdd:
1065     case Instruction::Sub:
1066     case Instruction::FSub:
1067     case Instruction::Mul:
1068     case Instruction::FMul:
1069     case Instruction::UDiv:
1070     case Instruction::SDiv:
1071     case Instruction::FDiv:
1072     case Instruction::URem:
1073     case Instruction::SRem:
1074     case Instruction::FRem:
1075     case Instruction::Shl:
1076     case Instruction::LShr:
1077     case Instruction::AShr:
1078     case Instruction::And:
1079     case Instruction::Or:
1080     case Instruction::Xor: {
1081       // Just widen binops.
1082       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1083       Value *A = getVectorValue(it->getOperand(0));
1084       Value *B = getVectorValue(it->getOperand(1));
1085
1086       // Use this vector value for all users of the original instruction.
1087       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1088       WidenMap[it] = V;
1089
1090       // Update the NSW, NUW and Exact flags.
1091       BinaryOperator *VecOp = cast<BinaryOperator>(V);
1092       if (isa<OverflowingBinaryOperator>(BinOp)) {
1093         VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1094         VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1095       }
1096       if (isa<PossiblyExactOperator>(VecOp))
1097         VecOp->setIsExact(BinOp->isExact());
1098       break;
1099     }
1100     case Instruction::Select: {
1101       // Widen selects.
1102       // If the selector is loop invariant we can create a select
1103       // instruction with a scalar condition. Otherwise, use vector-select.
1104       Value *Cond = it->getOperand(0);
1105       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1106
1107       // The condition can be loop invariant  but still defined inside the
1108       // loop. This means that we can't just use the original 'cond' value.
1109       // We have to take the 'vectorized' value and pick the first lane.
1110       // Instcombine will make this a no-op.
1111       Cond = getVectorValue(Cond);
1112       if (InvariantCond)
1113         Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1114
1115       Value *Op0 = getVectorValue(it->getOperand(1));
1116       Value *Op1 = getVectorValue(it->getOperand(2));
1117       WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1118       break;
1119     }
1120
1121     case Instruction::ICmp:
1122     case Instruction::FCmp: {
1123       // Widen compares. Generate vector compares.
1124       bool FCmp = (it->getOpcode() == Instruction::FCmp);
1125       CmpInst *Cmp = dyn_cast<CmpInst>(it);
1126       Value *A = getVectorValue(it->getOperand(0));
1127       Value *B = getVectorValue(it->getOperand(1));
1128       if (FCmp)
1129         WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1130       else
1131         WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1132       break;
1133     }
1134
1135     case Instruction::Store: {
1136       // Attempt to issue a wide store.
1137       StoreInst *SI = dyn_cast<StoreInst>(it);
1138       Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1139       Value *Ptr = SI->getPointerOperand();
1140       unsigned Alignment = SI->getAlignment();
1141
1142       assert(!Legal->isUniform(Ptr) &&
1143              "We do not allow storing to uniform addresses");
1144
1145       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1146
1147       // This store does not use GEPs.
1148       if (!Legal->isConsecutivePtr(Ptr)) {
1149         scalarizeInstruction(it);
1150         break;
1151       }
1152
1153       if (Gep) {
1154         // The last index does not have to be the induction. It can be
1155         // consecutive and be a function of the index. For example A[I+1];
1156         unsigned NumOperands = Gep->getNumOperands();
1157         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1158         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1159
1160         // Create the new GEP with the new induction variable.
1161         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1162         Gep2->setOperand(NumOperands - 1, LastIndex);
1163         Ptr = Builder.Insert(Gep2);
1164       } else {
1165         // Use the induction element ptr.
1166         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1167         Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1168       }
1169       Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1170       Value *Val = getVectorValue(SI->getValueOperand());
1171       Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1172       break;
1173     }
1174     case Instruction::Load: {
1175       // Attempt to issue a wide load.
1176       LoadInst *LI = dyn_cast<LoadInst>(it);
1177       Type *RetTy = VectorType::get(LI->getType(), VF);
1178       Value *Ptr = LI->getPointerOperand();
1179       unsigned Alignment = LI->getAlignment();
1180       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1181
1182       // If the pointer is loop invariant or if it is non consecutive,
1183       // scalarize the load.
1184       bool Con = Legal->isConsecutivePtr(Ptr);
1185       if (Legal->isUniform(Ptr) || !Con) {
1186         scalarizeInstruction(it);
1187         break;
1188       }
1189
1190       if (Gep) {
1191         // The last index does not have to be the induction. It can be
1192         // consecutive and be a function of the index. For example A[I+1];
1193         unsigned NumOperands = Gep->getNumOperands();
1194         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1195         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1196
1197         // Create the new GEP with the new induction variable.
1198         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1199         Gep2->setOperand(NumOperands - 1, LastIndex);
1200         Ptr = Builder.Insert(Gep2);
1201       } else {
1202         // Use the induction element ptr.
1203         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1204         Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1205       }
1206
1207       Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1208       LI = Builder.CreateLoad(Ptr);
1209       LI->setAlignment(Alignment);
1210       // Use this vector value for all users of the load.
1211       WidenMap[it] = LI;
1212       break;
1213     }
1214     case Instruction::ZExt:
1215     case Instruction::SExt:
1216     case Instruction::FPToUI:
1217     case Instruction::FPToSI:
1218     case Instruction::FPExt:
1219     case Instruction::PtrToInt:
1220     case Instruction::IntToPtr:
1221     case Instruction::SIToFP:
1222     case Instruction::UIToFP:
1223     case Instruction::Trunc:
1224     case Instruction::FPTrunc:
1225     case Instruction::BitCast: {
1226       CastInst *CI = dyn_cast<CastInst>(it);
1227       /// Optimize the special case where the source is the induction
1228       /// variable. Notice that we can only optimize the 'trunc' case
1229       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1230       /// c. other casts depend on pointer size.
1231       if (CI->getOperand(0) == OldInduction &&
1232           it->getOpcode() == Instruction::Trunc) {
1233         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1234                                                CI->getType());
1235         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1236         WidenMap[it] = getConsecutiveVector(Broadcasted);
1237         break;
1238       }
1239       /// Vectorize casts.
1240       Value *A = getVectorValue(it->getOperand(0));
1241       Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1242       WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1243       break;
1244     }
1245
1246     case Instruction::Call: {
1247       assert(isTriviallyVectorizableIntrinsic(it));
1248       Module *M = BB->getParent()->getParent();
1249       IntrinsicInst *II = cast<IntrinsicInst>(it);
1250       Intrinsic::ID ID = II->getIntrinsicID();
1251       SmallVector<Value*, 4> Args;
1252       for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1253         Args.push_back(getVectorValue(II->getArgOperand(i)));
1254       Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1255       Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1256       WidenMap[it] = Builder.CreateCall(F, Args);
1257       break;
1258     }
1259
1260     default:
1261       // All other instructions are unsupported. Scalarize them.
1262       scalarizeInstruction(it);
1263       break;
1264     }// end of switch.
1265   }// end of for_each instr.
1266 }
1267
1268 void InnerLoopVectorizer::updateAnalysis() {
1269   // Forget the original basic block.
1270   SE->forgetLoop(OrigLoop);
1271
1272   // Update the dominator tree information.
1273   assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1274          "Entry does not dominate exit.");
1275
1276   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1277   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1278   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1279   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1280   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1281   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1282
1283   DEBUG(DT->verifyAnalysis());
1284 }
1285
1286 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1287   if (!EnableIfConversion)
1288     return false;
1289
1290   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1291   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1292
1293   // Collect the blocks that need predication.
1294   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1295     BasicBlock *BB = LoopBlocks[i];
1296
1297     // We don't support switch statements inside loops.
1298     if (!isa<BranchInst>(BB->getTerminator()))
1299       return false;
1300
1301     // We must have at most two predecessors because we need to convert
1302     // all PHIs to selects.
1303     unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1304     if (Preds > 2)
1305       return false;
1306
1307     // We must be able to predicate all blocks that need to be predicated.
1308     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1309       return false;
1310   }
1311
1312   // We can if-convert this loop.
1313   return true;
1314 }
1315
1316 bool LoopVectorizationLegality::canVectorize() {
1317   assert(TheLoop->getLoopPreheader() && "No preheader!!");
1318
1319   // We can only vectorize innermost loops.
1320   if (TheLoop->getSubLoopsVector().size())
1321     return false;
1322
1323   // We must have a single backedge.
1324   if (TheLoop->getNumBackEdges() != 1)
1325     return false;
1326
1327   // We must have a single exiting block.
1328   if (!TheLoop->getExitingBlock())
1329     return false;
1330
1331   unsigned NumBlocks = TheLoop->getNumBlocks();
1332
1333   // Check if we can if-convert non single-bb loops.
1334   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1335     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1336     return false;
1337   }
1338
1339   // We need to have a loop header.
1340   BasicBlock *Latch = TheLoop->getLoopLatch();
1341   DEBUG(dbgs() << "LV: Found a loop: " <<
1342         TheLoop->getHeader()->getName() << "\n");
1343
1344   // ScalarEvolution needs to be able to find the exit count.
1345   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1346   if (ExitCount == SE->getCouldNotCompute()) {
1347     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1348     return false;
1349   }
1350
1351   // Do not loop-vectorize loops with a tiny trip count.
1352   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1353   if (TC > 0u && TC < TinyTripCountThreshold) {
1354     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1355           "This loop is not worth vectorizing.\n");
1356     return false;
1357   }
1358
1359   // Check if we can vectorize the instructions and CFG in this loop.
1360   if (!canVectorizeInstrs()) {
1361     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1362     return false;
1363   }
1364
1365   // Go over each instruction and look at memory deps.
1366   if (!canVectorizeMemory()) {
1367     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1368     return false;
1369   }
1370
1371   // Collect all of the variables that remain uniform after vectorization.
1372   collectLoopUniforms();
1373
1374   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1375         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1376         <<"!\n");
1377
1378   // Okay! We can vectorize. At this point we don't have any other mem analysis
1379   // which may limit our maximum vectorization factor, so just return true with
1380   // no restrictions.
1381   return true;
1382 }
1383
1384 bool LoopVectorizationLegality::canVectorizeInstrs() {
1385   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1386   BasicBlock *Header = TheLoop->getHeader();
1387
1388   // For each block in the loop.
1389   for (Loop::block_iterator bb = TheLoop->block_begin(),
1390        be = TheLoop->block_end(); bb != be; ++bb) {
1391
1392     // Scan the instructions in the block and look for hazards.
1393     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1394          ++it) {
1395
1396       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1397         // This should not happen because the loop should be normalized.
1398         if (Phi->getNumIncomingValues() != 2) {
1399           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1400           return false;
1401         }
1402
1403         // Check that this PHI type is allowed.
1404         if (!Phi->getType()->isIntegerTy() &&
1405             !Phi->getType()->isPointerTy()) {
1406           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1407           return false;
1408         }
1409
1410         // If this PHINode is not in the header block, then we know that we
1411         // can convert it to select during if-conversion. No need to check if
1412         // the PHIs in this block are induction or reduction variables.
1413         if (*bb != Header)
1414           continue;
1415
1416         // This is the value coming from the preheader.
1417         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1418         // Check if this is an induction variable.
1419         InductionKind IK = isInductionVariable(Phi);
1420
1421         if (NoInduction != IK) {
1422           // Int inductions are special because we only allow one IV.
1423           if (IK == IntInduction) {
1424             if (Induction) {
1425               DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1426               return false;
1427             }
1428             Induction = Phi;
1429           }
1430
1431           DEBUG(dbgs() << "LV: Found an induction variable.\n");
1432           Inductions[Phi] = InductionInfo(StartValue, IK);
1433           continue;
1434         }
1435
1436         if (AddReductionVar(Phi, IntegerAdd)) {
1437           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1438           continue;
1439         }
1440         if (AddReductionVar(Phi, IntegerMult)) {
1441           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1442           continue;
1443         }
1444         if (AddReductionVar(Phi, IntegerOr)) {
1445           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1446           continue;
1447         }
1448         if (AddReductionVar(Phi, IntegerAnd)) {
1449           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1450           continue;
1451         }
1452         if (AddReductionVar(Phi, IntegerXor)) {
1453           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1454           continue;
1455         }
1456
1457         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1458         return false;
1459       }// end of PHI handling
1460
1461       // We still don't handle functions.
1462       CallInst *CI = dyn_cast<CallInst>(it);
1463       if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1464         DEBUG(dbgs() << "LV: Found a call site.\n");
1465         return false;
1466       }
1467
1468       // Check that the instruction return type is vectorizable.
1469       if (!VectorType::isValidElementType(it->getType()) &&
1470           !it->getType()->isVoidTy()) {
1471         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1472         return false;
1473       }
1474
1475       // Check that the stored type is vectorizable.
1476       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
1477         Type *T = ST->getValueOperand()->getType();
1478         if (!VectorType::isValidElementType(T))
1479           return false;
1480       }
1481
1482       // Reduction instructions are allowed to have exit users.
1483       // All other instructions must not have external users.
1484       if (!AllowedExit.count(it))
1485         //Check that all of the users of the loop are inside the BB.
1486         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1487              I != E; ++I) {
1488           Instruction *U = cast<Instruction>(*I);
1489           // This user may be a reduction exit value.
1490           if (!TheLoop->contains(U)) {
1491             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1492             return false;
1493           }
1494         }
1495     } // next instr.
1496
1497   }
1498
1499   if (!Induction) {
1500     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1501     assert(getInductionVars()->size() && "No induction variables");
1502   }
1503
1504   return true;
1505 }
1506
1507 void LoopVectorizationLegality::collectLoopUniforms() {
1508   // We now know that the loop is vectorizable!
1509   // Collect variables that will remain uniform after vectorization.
1510   std::vector<Value*> Worklist;
1511   BasicBlock *Latch = TheLoop->getLoopLatch();
1512
1513   // Start with the conditional branch and walk up the block.
1514   Worklist.push_back(Latch->getTerminator()->getOperand(0));
1515
1516   while (Worklist.size()) {
1517     Instruction *I = dyn_cast<Instruction>(Worklist.back());
1518     Worklist.pop_back();
1519
1520     // Look at instructions inside this loop.
1521     // Stop when reaching PHI nodes.
1522     // TODO: we need to follow values all over the loop, not only in this block.
1523     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1524       continue;
1525
1526     // This is a known uniform.
1527     Uniforms.insert(I);
1528
1529     // Insert all operands.
1530     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1531       Worklist.push_back(I->getOperand(i));
1532     }
1533   }
1534 }
1535
1536 bool LoopVectorizationLegality::canVectorizeMemory() {
1537   typedef SmallVector<Value*, 16> ValueVector;
1538   typedef SmallPtrSet<Value*, 16> ValueSet;
1539   // Holds the Load and Store *instructions*.
1540   ValueVector Loads;
1541   ValueVector Stores;
1542   PtrRtCheck.Pointers.clear();
1543   PtrRtCheck.Need = false;
1544
1545   // For each block.
1546   for (Loop::block_iterator bb = TheLoop->block_begin(),
1547        be = TheLoop->block_end(); bb != be; ++bb) {
1548
1549     // Scan the BB and collect legal loads and stores.
1550     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1551          ++it) {
1552
1553       // If this is a load, save it. If this instruction can read from memory
1554       // but is not a load, then we quit. Notice that we don't handle function
1555       // calls that read or write.
1556       if (it->mayReadFromMemory()) {
1557         LoadInst *Ld = dyn_cast<LoadInst>(it);
1558         if (!Ld) return false;
1559         if (!Ld->isSimple()) {
1560           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1561           return false;
1562         }
1563         Loads.push_back(Ld);
1564         continue;
1565       }
1566
1567       // Save 'store' instructions. Abort if other instructions write to memory.
1568       if (it->mayWriteToMemory()) {
1569         StoreInst *St = dyn_cast<StoreInst>(it);
1570         if (!St) return false;
1571         if (!St->isSimple()) {
1572           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1573           return false;
1574         }
1575         Stores.push_back(St);
1576       }
1577     } // next instr.
1578   } // next block.
1579
1580   // Now we have two lists that hold the loads and the stores.
1581   // Next, we find the pointers that they use.
1582
1583   // Check if we see any stores. If there are no stores, then we don't
1584   // care if the pointers are *restrict*.
1585   if (!Stores.size()) {
1586     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1587     return true;
1588   }
1589
1590   // Holds the read and read-write *pointers* that we find.
1591   ValueVector Reads;
1592   ValueVector ReadWrites;
1593
1594   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1595   // multiple times on the same object. If the ptr is accessed twice, once
1596   // for read and once for write, it will only appear once (on the write
1597   // list). This is okay, since we are going to check for conflicts between
1598   // writes and between reads and writes, but not between reads and reads.
1599   ValueSet Seen;
1600
1601   ValueVector::iterator I, IE;
1602   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1603     StoreInst *ST = cast<StoreInst>(*I);
1604     Value* Ptr = ST->getPointerOperand();
1605
1606     if (isUniform(Ptr)) {
1607       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1608       return false;
1609     }
1610
1611     // If we did *not* see this pointer before, insert it to
1612     // the read-write list. At this phase it is only a 'write' list.
1613     if (Seen.insert(Ptr))
1614       ReadWrites.push_back(Ptr);
1615   }
1616
1617   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1618     LoadInst *LD = cast<LoadInst>(*I);
1619     Value* Ptr = LD->getPointerOperand();
1620     // If we did *not* see this pointer before, insert it to the
1621     // read list. If we *did* see it before, then it is already in
1622     // the read-write list. This allows us to vectorize expressions
1623     // such as A[i] += x;  Because the address of A[i] is a read-write
1624     // pointer. This only works if the index of A[i] is consecutive.
1625     // If the address of i is unknown (for example A[B[i]]) then we may
1626     // read a few words, modify, and write a few words, and some of the
1627     // words may be written to the same address.
1628     if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1629       Reads.push_back(Ptr);
1630   }
1631
1632   // If we write (or read-write) to a single destination and there are no
1633   // other reads in this loop then is it safe to vectorize.
1634   if (ReadWrites.size() == 1 && Reads.size() == 0) {
1635     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1636     return true;
1637   }
1638
1639   // Find pointers with computable bounds. We are going to use this information
1640   // to place a runtime bound check.
1641   bool CanDoRT = true;
1642   for (I = ReadWrites.begin(), IE = ReadWrites.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   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1651     if (hasComputableBounds(*I)) {
1652       PtrRtCheck.insert(SE, TheLoop, *I);
1653       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1654     } else {
1655       CanDoRT = false;
1656       break;
1657     }
1658
1659   // Check that we did not collect too many pointers or found a
1660   // unsizeable pointer.
1661   if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1662     PtrRtCheck.reset();
1663     CanDoRT = false;
1664   }
1665
1666   if (CanDoRT) {
1667     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1668   }
1669
1670   bool NeedRTCheck = false;
1671
1672   // Now that the pointers are in two lists (Reads and ReadWrites), we
1673   // can check that there are no conflicts between each of the writes and
1674   // between the writes to the reads.
1675   ValueSet WriteObjects;
1676   ValueVector TempObjects;
1677
1678   // Check that the read-writes do not conflict with other read-write
1679   // pointers.
1680   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1681     GetUnderlyingObjects(*I, TempObjects, DL);
1682     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1683          it != e; ++it) {
1684       if (!isIdentifiedObject(*it)) {
1685         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1686         NeedRTCheck = true;
1687       }
1688       if (!WriteObjects.insert(*it)) {
1689         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1690               << **it <<"\n");
1691         return false;
1692       }
1693     }
1694     TempObjects.clear();
1695   }
1696
1697   /// Check that the reads don't conflict with the read-writes.
1698   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1699     GetUnderlyingObjects(*I, TempObjects, DL);
1700     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1701          it != e; ++it) {
1702       if (!isIdentifiedObject(*it)) {
1703         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1704         NeedRTCheck = true;
1705       }
1706       if (WriteObjects.count(*it)) {
1707         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1708               << **it <<"\n");
1709         return false;
1710       }
1711     }
1712     TempObjects.clear();
1713   }
1714
1715   PtrRtCheck.Need = NeedRTCheck;
1716   if (NeedRTCheck && !CanDoRT) {
1717     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1718           "the array bounds.\n");
1719     PtrRtCheck.reset();
1720     return false;
1721   }
1722
1723   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1724         " need a runtime memory check.\n");
1725   return true;
1726 }
1727
1728 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1729                                                 ReductionKind Kind) {
1730   if (Phi->getNumIncomingValues() != 2)
1731     return false;
1732
1733   // Reduction variables are only found in the loop header block.
1734   if (Phi->getParent() != TheLoop->getHeader())
1735     return false;
1736
1737   // Obtain the reduction start value from the value that comes from the loop
1738   // preheader.
1739   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1740
1741   // ExitInstruction is the single value which is used outside the loop.
1742   // We only allow for a single reduction value to be used outside the loop.
1743   // This includes users of the reduction, variables (which form a cycle
1744   // which ends in the phi node).
1745   Instruction *ExitInstruction = 0;
1746
1747   // Iter is our iterator. We start with the PHI node and scan for all of the
1748   // users of this instruction. All users must be instructions that can be
1749   // used as reduction variables (such as ADD). We may have a single
1750   // out-of-block user. The cycle must end with the original PHI.
1751   Instruction *Iter = Phi;
1752   while (true) {
1753     // If the instruction has no users then this is a broken
1754     // chain and can't be a reduction variable.
1755     if (Iter->use_empty())
1756       return false;
1757
1758     // Any reduction instr must be of one of the allowed kinds.
1759     if (!isReductionInstr(Iter, Kind))
1760       return false;
1761
1762     // Did we find a user inside this loop already ?
1763     bool FoundInBlockUser = false;
1764     // Did we reach the initial PHI node already ?
1765     bool FoundStartPHI = false;
1766
1767     // For each of the *users* of iter.
1768     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1769          it != e; ++it) {
1770       Instruction *U = cast<Instruction>(*it);
1771       // We already know that the PHI is a user.
1772       if (U == Phi) {
1773         FoundStartPHI = true;
1774         continue;
1775       }
1776
1777       // Check if we found the exit user.
1778       BasicBlock *Parent = U->getParent();
1779       if (!TheLoop->contains(Parent)) {
1780         // Exit if you find multiple outside users.
1781         if (ExitInstruction != 0)
1782           return false;
1783         ExitInstruction = Iter;
1784       }
1785
1786       // We allow in-loop PHINodes which are not the original reduction PHI
1787       // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1788       // structure) then don't skip this PHI.
1789       if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
1790           U->getParent() != TheLoop->getHeader() &&
1791           TheLoop->contains(U) &&
1792           Iter->getNumUses() > 1)
1793         continue;
1794
1795       // We can't have multiple inside users.
1796       if (FoundInBlockUser)
1797         return false;
1798       FoundInBlockUser = true;
1799       Iter = U;
1800     }
1801
1802     // We found a reduction var if we have reached the original
1803     // phi node and we only have a single instruction with out-of-loop
1804     // users.
1805     if (FoundStartPHI && ExitInstruction) {
1806       // This instruction is allowed to have out-of-loop users.
1807       AllowedExit.insert(ExitInstruction);
1808
1809       // Save the description of this reduction variable.
1810       ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1811       Reductions[Phi] = RD;
1812       return true;
1813     }
1814
1815     // If we've reached the start PHI but did not find an outside user then
1816     // this is dead code. Abort.
1817     if (FoundStartPHI)
1818       return false;
1819   }
1820 }
1821
1822 bool
1823 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1824                                             ReductionKind Kind) {
1825   switch (I->getOpcode()) {
1826   default:
1827     return false;
1828   case Instruction::PHI:
1829     // possibly.
1830     return true;
1831   case Instruction::Add:
1832   case Instruction::Sub:
1833     return Kind == IntegerAdd;
1834   case Instruction::Mul:
1835     return Kind == IntegerMult;
1836   case Instruction::And:
1837     return Kind == IntegerAnd;
1838   case Instruction::Or:
1839     return Kind == IntegerOr;
1840   case Instruction::Xor:
1841     return Kind == IntegerXor;
1842   }
1843 }
1844
1845 LoopVectorizationLegality::InductionKind
1846 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1847   Type *PhiTy = Phi->getType();
1848   // We only handle integer and pointer inductions variables.
1849   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1850     return NoInduction;
1851
1852   // Check that the PHI is consecutive and starts at zero.
1853   const SCEV *PhiScev = SE->getSCEV(Phi);
1854   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1855   if (!AR) {
1856     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1857     return NoInduction;
1858   }
1859   const SCEV *Step = AR->getStepRecurrence(*SE);
1860
1861   // Integer inductions need to have a stride of one.
1862   if (PhiTy->isIntegerTy()) {
1863     if (Step->isOne())
1864       return IntInduction;
1865     if (Step->isAllOnesValue())
1866       return ReverseIntInduction;
1867     return NoInduction;
1868   }
1869
1870   // Calculate the pointer stride and check if it is consecutive.
1871   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1872   if (!C)
1873     return NoInduction;
1874
1875   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1876   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1877   if (C->getValue()->equalsInt(Size))
1878     return PtrInduction;
1879
1880   return NoInduction;
1881 }
1882
1883 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
1884   Value *In0 = const_cast<Value*>(V);
1885   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
1886   if (!PN)
1887     return false;
1888
1889   return Inductions.count(PN);
1890 }
1891
1892 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
1893   assert(TheLoop->contains(BB) && "Unknown block used");
1894
1895   // Blocks that do not dominate the latch need predication.
1896   BasicBlock* Latch = TheLoop->getLoopLatch();
1897   return !DT->dominates(BB, Latch);
1898 }
1899
1900 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1901   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1902     // We don't predicate loads/stores at the moment.
1903     if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1904       return false;
1905
1906     // The instructions below can trap.
1907     switch (it->getOpcode()) {
1908     default: continue;
1909     case Instruction::UDiv:
1910     case Instruction::SDiv:
1911     case Instruction::URem:
1912     case Instruction::SRem:
1913              return false;
1914     }
1915   }
1916
1917   return true;
1918 }
1919
1920 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1921   const SCEV *PhiScev = SE->getSCEV(Ptr);
1922   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1923   if (!AR)
1924     return false;
1925
1926   return AR->isAffine();
1927 }
1928
1929 unsigned
1930 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1931                                                         unsigned UserVF) {
1932   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1933     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1934     return 1;
1935   }
1936
1937   // Find the trip count.
1938   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1939   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1940
1941   unsigned VF = MaxVectorSize;
1942
1943   // If we optimize the program for size, avoid creating the tail loop.
1944   if (OptForSize) {
1945     // If we are unable to calculate the trip count then don't try to vectorize.
1946     if (TC < 2) {
1947       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1948       return 1;
1949     }
1950
1951     // Find the maximum SIMD width that can fit within the trip count.
1952     VF = TC % MaxVectorSize;
1953
1954     if (VF == 0)
1955       VF = MaxVectorSize;
1956
1957     // If the trip count that we found modulo the vectorization factor is not
1958     // zero then we require a tail.
1959     if (VF < 2) {
1960       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1961       return 1;
1962     }
1963   }
1964
1965   if (UserVF != 0) {
1966     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
1967     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
1968
1969     return UserVF;
1970   }
1971
1972   if (!VTTI) {
1973     DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1974     return 1;
1975   }
1976
1977   float Cost = expectedCost(1);
1978   unsigned Width = 1;
1979   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1980   for (unsigned i=2; i <= VF; i*=2) {
1981     // Notice that the vector loop needs to be executed less times, so
1982     // we need to divide the cost of the vector loops by the width of
1983     // the vector elements.
1984     float VectorCost = expectedCost(i) / (float)i;
1985     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1986           (int)VectorCost << ".\n");
1987     if (VectorCost < Cost) {
1988       Cost = VectorCost;
1989       Width = i;
1990     }
1991   }
1992
1993   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1994   return Width;
1995 }
1996
1997 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1998   unsigned Cost = 0;
1999
2000   // For each block.
2001   for (Loop::block_iterator bb = TheLoop->block_begin(),
2002        be = TheLoop->block_end(); bb != be; ++bb) {
2003     unsigned BlockCost = 0;
2004     BasicBlock *BB = *bb;
2005
2006     // For each instruction in the old loop.
2007     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2008       unsigned C = getInstructionCost(it, VF);
2009       Cost += C;
2010       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2011             VF << " For instruction: "<< *it << "\n");
2012     }
2013
2014     // We assume that if-converted blocks have a 50% chance of being executed.
2015     // When the code is scalar then some of the blocks are avoided due to CF.
2016     // When the code is vectorized we execute all code paths.
2017     if (Legal->blockNeedsPredication(*bb) && VF == 1)
2018       BlockCost /= 2;
2019
2020     Cost += BlockCost;
2021   }
2022
2023   return Cost;
2024 }
2025
2026 unsigned
2027 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2028   assert(VTTI && "Invalid vector target transformation info");
2029
2030   // If we know that this instruction will remain uniform, check the cost of
2031   // the scalar version.
2032   if (Legal->isUniformAfterVectorization(I))
2033     VF = 1;
2034
2035   Type *RetTy = I->getType();
2036   Type *VectorTy = ToVectorTy(RetTy, VF);
2037
2038   // TODO: We need to estimate the cost of intrinsic calls.
2039   switch (I->getOpcode()) {
2040   case Instruction::GetElementPtr:
2041     // We mark this instruction as zero-cost because scalar GEPs are usually
2042     // lowered to the intruction addressing mode. At the moment we don't
2043     // generate vector geps.
2044     return 0;
2045   case Instruction::Br: {
2046     return VTTI->getCFInstrCost(I->getOpcode());
2047   }
2048   case Instruction::PHI:
2049     //TODO: IF-converted IFs become selects.
2050     return 0;
2051   case Instruction::Add:
2052   case Instruction::FAdd:
2053   case Instruction::Sub:
2054   case Instruction::FSub:
2055   case Instruction::Mul:
2056   case Instruction::FMul:
2057   case Instruction::UDiv:
2058   case Instruction::SDiv:
2059   case Instruction::FDiv:
2060   case Instruction::URem:
2061   case Instruction::SRem:
2062   case Instruction::FRem:
2063   case Instruction::Shl:
2064   case Instruction::LShr:
2065   case Instruction::AShr:
2066   case Instruction::And:
2067   case Instruction::Or:
2068   case Instruction::Xor:
2069     return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2070   case Instruction::Select: {
2071     SelectInst *SI = cast<SelectInst>(I);
2072     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2073     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2074     Type *CondTy = SI->getCondition()->getType();
2075     if (ScalarCond)
2076       CondTy = VectorType::get(CondTy, VF);
2077
2078     return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2079   }
2080   case Instruction::ICmp:
2081   case Instruction::FCmp: {
2082     Type *ValTy = I->getOperand(0)->getType();
2083     VectorTy = ToVectorTy(ValTy, VF);
2084     return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2085   }
2086   case Instruction::Store: {
2087     StoreInst *SI = cast<StoreInst>(I);
2088     Type *ValTy = SI->getValueOperand()->getType();
2089     VectorTy = ToVectorTy(ValTy, VF);
2090
2091     if (VF == 1)
2092       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2093                                    SI->getAlignment(),
2094                                    SI->getPointerAddressSpace());
2095
2096     // Scalarized stores.
2097     if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2098       unsigned Cost = 0;
2099
2100       // The cost of extracting from the value vector and pointer vector.
2101       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2102       for (unsigned i = 0; i < VF; ++i) {
2103         Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2104                                          VectorTy, i);
2105         Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2106                                          PtrTy, i);
2107       }
2108
2109       // The cost of the scalar stores.
2110       Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2111                                          ValTy->getScalarType(),
2112                                          SI->getAlignment(),
2113                                          SI->getPointerAddressSpace());
2114       return Cost;
2115     }
2116
2117     // Wide stores.
2118     return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2119                                  SI->getPointerAddressSpace());
2120   }
2121   case Instruction::Load: {
2122     LoadInst *LI = cast<LoadInst>(I);
2123
2124     if (VF == 1)
2125       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2126                                    LI->getAlignment(),
2127                                    LI->getPointerAddressSpace());
2128
2129     // Scalarized loads.
2130     if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2131       unsigned Cost = 0;
2132       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2133
2134       // The cost of extracting from the pointer vector.
2135       for (unsigned i = 0; i < VF; ++i)
2136         Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2137                                          PtrTy, i);
2138
2139       // The cost of inserting data to the result vector.
2140       for (unsigned i = 0; i < VF; ++i)
2141         Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2142                                          VectorTy, i);
2143
2144       // The cost of the scalar stores.
2145       Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2146                                          RetTy->getScalarType(),
2147                                          LI->getAlignment(),
2148                                          LI->getPointerAddressSpace());
2149       return Cost;
2150     }
2151
2152     // Wide loads.
2153     return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2154                                  LI->getPointerAddressSpace());
2155   }
2156   case Instruction::ZExt:
2157   case Instruction::SExt:
2158   case Instruction::FPToUI:
2159   case Instruction::FPToSI:
2160   case Instruction::FPExt:
2161   case Instruction::PtrToInt:
2162   case Instruction::IntToPtr:
2163   case Instruction::SIToFP:
2164   case Instruction::UIToFP:
2165   case Instruction::Trunc:
2166   case Instruction::FPTrunc:
2167   case Instruction::BitCast: {
2168     // We optimize the truncation of induction variable.
2169     // The cost of these is the same as the scalar operation.
2170     if (I->getOpcode() == Instruction::Trunc &&
2171         Legal->isInductionVariable(I->getOperand(0)))
2172          return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2173                                        I->getOperand(0)->getType());
2174
2175     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2176     return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2177   }
2178   case Instruction::Call: {
2179     assert(isTriviallyVectorizableIntrinsic(I));
2180     IntrinsicInst *II = cast<IntrinsicInst>(I);
2181     Type *RetTy = ToVectorTy(II->getType(), VF);
2182     SmallVector<Type*, 4> Tys;
2183     for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2184       Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2185     return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2186   }
2187   default: {
2188     // We are scalarizing the instruction. Return the cost of the scalar
2189     // instruction, plus the cost of insert and extract into vector
2190     // elements, times the vector width.
2191     unsigned Cost = 0;
2192
2193     if (!RetTy->isVoidTy() && VF != 1) {
2194       unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2195                                                   VectorTy);
2196       unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2197                                                   VectorTy);
2198
2199       // The cost of inserting the results plus extracting each one of the
2200       // operands.
2201       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2202     }
2203
2204     // The cost of executing VF copies of the scalar instruction. This opcode
2205     // is unknown. Assume that it is the same as 'mul'.
2206     Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2207     return Cost;
2208   }
2209   }// end of switch.
2210 }
2211
2212 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2213   if (Scalar->isVoidTy() || VF == 1)
2214     return Scalar;
2215   return VectorType::get(Scalar, VF);
2216 }
2217
2218 char LoopVectorize::ID = 0;
2219 static const char lv_name[] = "Loop Vectorization";
2220 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2221 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2222 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2223 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2224 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2225
2226 namespace llvm {
2227   Pass *createLoopVectorizePass() {
2228     return new LoopVectorize();
2229   }
2230 }
2231
2232