Make DataLayout Non-Optional in the Module
[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 //
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
14 //
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
18 //
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 //    of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 //    widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 //    of vectorization. It decides on the optimal vector width, which
27 //    can be one, if vectorization is not profitable.
28 //
29 //===----------------------------------------------------------------------===//
30 //
31 // The reduction-variable vectorization is based on the paper:
32 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33 //
34 // Variable uniformity checks are inspired by:
35 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
36 //
37 // Other ideas/concepts are from:
38 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39 //
40 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
41 //  Vectorizing Compilers.
42 //
43 //===----------------------------------------------------------------------===//
44
45 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/AssumptionCache.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/CodeMetrics.h"
61 #include "llvm/Analysis/LoopAccessAnalysis.h"
62 #include "llvm/Analysis/LoopInfo.h"
63 #include "llvm/Analysis/LoopIterator.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolution.h"
66 #include "llvm/Analysis/ScalarEvolutionExpander.h"
67 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
68 #include "llvm/Analysis/TargetTransformInfo.h"
69 #include "llvm/Analysis/ValueTracking.h"
70 #include "llvm/IR/Constants.h"
71 #include "llvm/IR/DataLayout.h"
72 #include "llvm/IR/DebugInfo.h"
73 #include "llvm/IR/DerivedTypes.h"
74 #include "llvm/IR/DiagnosticInfo.h"
75 #include "llvm/IR/Dominators.h"
76 #include "llvm/IR/Function.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/Value.h"
85 #include "llvm/IR/ValueHandle.h"
86 #include "llvm/IR/Verifier.h"
87 #include "llvm/Pass.h"
88 #include "llvm/Support/BranchProbability.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Transforms/Scalar.h"
93 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
94 #include "llvm/Transforms/Utils/Local.h"
95 #include "llvm/Transforms/Utils/VectorUtils.h"
96 #include <algorithm>
97 #include <map>
98 #include <tuple>
99
100 using namespace llvm;
101 using namespace llvm::PatternMatch;
102
103 #define LV_NAME "loop-vectorize"
104 #define DEBUG_TYPE LV_NAME
105
106 STATISTIC(LoopsVectorized, "Number of loops vectorized");
107 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
108
109 static cl::opt<bool>
110 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
111                    cl::desc("Enable if-conversion during vectorization."));
112
113 /// We don't vectorize loops with a known constant trip count below this number.
114 static cl::opt<unsigned>
115 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
116                              cl::Hidden,
117                              cl::desc("Don't vectorize loops with a constant "
118                                       "trip count that is smaller than this "
119                                       "value."));
120
121 /// This enables versioning on the strides of symbolically striding memory
122 /// accesses in code like the following.
123 ///   for (i = 0; i < N; ++i)
124 ///     A[i * Stride1] += B[i * Stride2] ...
125 ///
126 /// Will be roughly translated to
127 ///    if (Stride1 == 1 && Stride2 == 1) {
128 ///      for (i = 0; i < N; i+=4)
129 ///       A[i:i+3] += ...
130 ///    } else
131 ///      ...
132 static cl::opt<bool> EnableMemAccessVersioning(
133     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
134     cl::desc("Enable symblic stride memory access versioning"));
135
136 /// We don't unroll loops with a known constant trip count below this number.
137 static const unsigned TinyTripCountUnrollThreshold = 128;
138
139 static cl::opt<unsigned> ForceTargetNumScalarRegs(
140     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
141     cl::desc("A flag that overrides the target's number of scalar registers."));
142
143 static cl::opt<unsigned> ForceTargetNumVectorRegs(
144     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
145     cl::desc("A flag that overrides the target's number of vector registers."));
146
147 /// Maximum vectorization interleave count.
148 static const unsigned MaxInterleaveFactor = 16;
149
150 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
151     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
152     cl::desc("A flag that overrides the target's max interleave factor for "
153              "scalar loops."));
154
155 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
156     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
157     cl::desc("A flag that overrides the target's max interleave factor for "
158              "vectorized loops."));
159
160 static cl::opt<unsigned> ForceTargetInstructionCost(
161     "force-target-instruction-cost", cl::init(0), cl::Hidden,
162     cl::desc("A flag that overrides the target's expected cost for "
163              "an instruction to a single constant value. Mostly "
164              "useful for getting consistent testing."));
165
166 static cl::opt<unsigned> SmallLoopCost(
167     "small-loop-cost", cl::init(20), cl::Hidden,
168     cl::desc("The cost of a loop that is considered 'small' by the unroller."));
169
170 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
171     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
172     cl::desc("Enable the use of the block frequency analysis to access PGO "
173              "heuristics minimizing code growth in cold regions and being more "
174              "aggressive in hot regions."));
175
176 // Runtime unroll loops for load/store throughput.
177 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
178     "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
179     cl::desc("Enable runtime unrolling until load/store ports are saturated"));
180
181 /// The number of stores in a loop that are allowed to need predication.
182 static cl::opt<unsigned> NumberOfStoresToPredicate(
183     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
184     cl::desc("Max number of stores to be predicated behind an if."));
185
186 static cl::opt<bool> EnableIndVarRegisterHeur(
187     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
188     cl::desc("Count the induction variable only once when unrolling"));
189
190 static cl::opt<bool> EnableCondStoresVectorization(
191     "enable-cond-stores-vec", cl::init(false), cl::Hidden,
192     cl::desc("Enable if predication of stores during vectorization."));
193
194 static cl::opt<unsigned> MaxNestedScalarReductionUF(
195     "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
196     cl::desc("The maximum unroll factor to use when unrolling a scalar "
197              "reduction in a nested loop."));
198
199 namespace {
200
201 // Forward declarations.
202 class LoopVectorizationLegality;
203 class LoopVectorizationCostModel;
204 class LoopVectorizeHints;
205
206 /// \brief This modifies LoopAccessReport to initialize message with
207 /// loop-vectorizer-specific part.
208 class VectorizationReport : public LoopAccessReport {
209 public:
210   VectorizationReport(Instruction *I = nullptr)
211       : LoopAccessReport("loop not vectorized: ", I) {}
212
213   /// \brief This allows promotion of the loop-access analysis report into the
214   /// loop-vectorizer report.  It modifies the message to add the
215   /// loop-vectorizer-specific part of the message.
216   explicit VectorizationReport(const LoopAccessReport &R)
217       : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
218                          R.getInstr()) {}
219 };
220
221 /// A helper function for converting Scalar types to vector types.
222 /// If the incoming type is void, we return void. If the VF is 1, we return
223 /// the scalar type.
224 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
225   if (Scalar->isVoidTy() || VF == 1)
226     return Scalar;
227   return VectorType::get(Scalar, VF);
228 }
229
230 /// InnerLoopVectorizer vectorizes loops which contain only one basic
231 /// block to a specified vectorization factor (VF).
232 /// This class performs the widening of scalars into vectors, or multiple
233 /// scalars. This class also implements the following features:
234 /// * It inserts an epilogue loop for handling loops that don't have iteration
235 ///   counts that are known to be a multiple of the vectorization factor.
236 /// * It handles the code generation for reduction variables.
237 /// * Scalarization (implementation using scalars) of un-vectorizable
238 ///   instructions.
239 /// InnerLoopVectorizer does not perform any vectorization-legality
240 /// checks, and relies on the caller to check for the different legality
241 /// aspects. The InnerLoopVectorizer relies on the
242 /// LoopVectorizationLegality class to provide information about the induction
243 /// and reduction variables that were found to a given vectorization factor.
244 class InnerLoopVectorizer {
245 public:
246   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
247                       DominatorTree *DT, const DataLayout *DL,
248                       const TargetLibraryInfo *TLI, unsigned VecWidth,
249                       unsigned UnrollFactor)
250       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
251         VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
252         Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
253         Legal(nullptr) {}
254
255   // Perform the actual loop widening (vectorization).
256   void vectorize(LoopVectorizationLegality *L) {
257     Legal = L;
258     // Create a new empty loop. Unlink the old loop and connect the new one.
259     createEmptyLoop();
260     // Widen each instruction in the old loop to a new one in the new loop.
261     // Use the Legality module to find the induction and reduction variables.
262     vectorizeLoop();
263     // Register the new loop and update the analysis passes.
264     updateAnalysis();
265   }
266
267   virtual ~InnerLoopVectorizer() {}
268
269 protected:
270   /// A small list of PHINodes.
271   typedef SmallVector<PHINode*, 4> PhiVector;
272   /// When we unroll loops we have multiple vector values for each scalar.
273   /// This data structure holds the unrolled and vectorized values that
274   /// originated from one scalar instruction.
275   typedef SmallVector<Value*, 2> VectorParts;
276
277   // When we if-convert we need create edge masks. We have to cache values so
278   // that we don't end up with exponential recursion/IR.
279   typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
280                    VectorParts> EdgeMaskCache;
281
282   /// \brief Add checks for strides that where assumed to be 1.
283   ///
284   /// Returns the last check instruction and the first check instruction in the
285   /// pair as (first, last).
286   std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
287
288   /// Create an empty loop, based on the loop ranges of the old loop.
289   void createEmptyLoop();
290   /// Copy and widen the instructions from the old loop.
291   virtual void vectorizeLoop();
292
293   /// \brief The Loop exit block may have single value PHI nodes where the
294   /// incoming value is 'Undef'. While vectorizing we only handled real values
295   /// that were defined inside the loop. Here we fix the 'undef case'.
296   /// See PR14725.
297   void fixLCSSAPHIs();
298
299   /// A helper function that computes the predicate of the block BB, assuming
300   /// that the header block of the loop is set to True. It returns the *entry*
301   /// mask for the block BB.
302   VectorParts createBlockInMask(BasicBlock *BB);
303   /// A helper function that computes the predicate of the edge between SRC
304   /// and DST.
305   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
306
307   /// A helper function to vectorize a single BB within the innermost loop.
308   void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
309
310   /// Vectorize a single PHINode in a block. This method handles the induction
311   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
312   /// arbitrary length vectors.
313   void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
314                            unsigned UF, unsigned VF, PhiVector *PV);
315
316   /// Insert the new loop to the loop hierarchy and pass manager
317   /// and update the analysis passes.
318   void updateAnalysis();
319
320   /// This instruction is un-vectorizable. Implement it as a sequence
321   /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
322   /// scalarized instruction behind an if block predicated on the control
323   /// dependence of the instruction.
324   virtual void scalarizeInstruction(Instruction *Instr,
325                                     bool IfPredicateStore=false);
326
327   /// Vectorize Load and Store instructions,
328   virtual void vectorizeMemoryInstruction(Instruction *Instr);
329
330   /// Create a broadcast instruction. This method generates a broadcast
331   /// instruction (shuffle) for loop invariant values and for the induction
332   /// value. If this is the induction variable then we extend it to N, N+1, ...
333   /// this is needed because each iteration in the loop corresponds to a SIMD
334   /// element.
335   virtual Value *getBroadcastInstrs(Value *V);
336
337   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
338   /// to each vector element of Val. The sequence starts at StartIndex.
339   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
340
341   /// When we go over instructions in the basic block we rely on previous
342   /// values within the current basic block or on loop invariant values.
343   /// When we widen (vectorize) values we place them in the map. If the values
344   /// are not within the map, they have to be loop invariant, so we simply
345   /// broadcast them into a vector.
346   VectorParts &getVectorValue(Value *V);
347
348   /// Generate a shuffle sequence that will reverse the vector Vec.
349   virtual Value *reverseVector(Value *Vec);
350
351   /// This is a helper class that holds the vectorizer state. It maps scalar
352   /// instructions to vector instructions. When the code is 'unrolled' then
353   /// then a single scalar value is mapped to multiple vector parts. The parts
354   /// are stored in the VectorPart type.
355   struct ValueMap {
356     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
357     /// are mapped.
358     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
359
360     /// \return True if 'Key' is saved in the Value Map.
361     bool has(Value *Key) const { return MapStorage.count(Key); }
362
363     /// Initializes a new entry in the map. Sets all of the vector parts to the
364     /// save value in 'Val'.
365     /// \return A reference to a vector with splat values.
366     VectorParts &splat(Value *Key, Value *Val) {
367       VectorParts &Entry = MapStorage[Key];
368       Entry.assign(UF, Val);
369       return Entry;
370     }
371
372     ///\return A reference to the value that is stored at 'Key'.
373     VectorParts &get(Value *Key) {
374       VectorParts &Entry = MapStorage[Key];
375       if (Entry.empty())
376         Entry.resize(UF);
377       assert(Entry.size() == UF);
378       return Entry;
379     }
380
381   private:
382     /// The unroll factor. Each entry in the map stores this number of vector
383     /// elements.
384     unsigned UF;
385
386     /// Map storage. We use std::map and not DenseMap because insertions to a
387     /// dense map invalidates its iterators.
388     std::map<Value *, VectorParts> MapStorage;
389   };
390
391   /// The original loop.
392   Loop *OrigLoop;
393   /// Scev analysis to use.
394   ScalarEvolution *SE;
395   /// Loop Info.
396   LoopInfo *LI;
397   /// Dominator Tree.
398   DominatorTree *DT;
399   /// Alias Analysis.
400   AliasAnalysis *AA;
401   /// Data Layout.
402   const DataLayout *DL;
403   /// Target Library Info.
404   const TargetLibraryInfo *TLI;
405
406   /// The vectorization SIMD factor to use. Each vector will have this many
407   /// vector elements.
408   unsigned VF;
409
410 protected:
411   /// The vectorization unroll factor to use. Each scalar is vectorized to this
412   /// many different vector instructions.
413   unsigned UF;
414
415   /// The builder that we use
416   IRBuilder<> Builder;
417
418   // --- Vectorization state ---
419
420   /// The vector-loop preheader.
421   BasicBlock *LoopVectorPreHeader;
422   /// The scalar-loop preheader.
423   BasicBlock *LoopScalarPreHeader;
424   /// Middle Block between the vector and the scalar.
425   BasicBlock *LoopMiddleBlock;
426   ///The ExitBlock of the scalar loop.
427   BasicBlock *LoopExitBlock;
428   ///The vector loop body.
429   SmallVector<BasicBlock *, 4> LoopVectorBody;
430   ///The scalar loop body.
431   BasicBlock *LoopScalarBody;
432   /// A list of all bypass blocks. The first block is the entry of the loop.
433   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
434
435   /// The new Induction variable which was added to the new block.
436   PHINode *Induction;
437   /// The induction variable of the old basic block.
438   PHINode *OldInduction;
439   /// Holds the extended (to the widest induction type) start index.
440   Value *ExtendedIdx;
441   /// Maps scalars to widened vectors.
442   ValueMap WidenMap;
443   EdgeMaskCache MaskCache;
444
445   LoopVectorizationLegality *Legal;
446 };
447
448 class InnerLoopUnroller : public InnerLoopVectorizer {
449 public:
450   InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
451                     DominatorTree *DT, const DataLayout *DL,
452                     const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
453     InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
454
455 private:
456   void scalarizeInstruction(Instruction *Instr,
457                             bool IfPredicateStore = false) override;
458   void vectorizeMemoryInstruction(Instruction *Instr) override;
459   Value *getBroadcastInstrs(Value *V) override;
460   Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
461   Value *reverseVector(Value *Vec) override;
462 };
463
464 /// \brief Look for a meaningful debug location on the instruction or it's
465 /// operands.
466 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
467   if (!I)
468     return I;
469
470   DebugLoc Empty;
471   if (I->getDebugLoc() != Empty)
472     return I;
473
474   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
475     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
476       if (OpInst->getDebugLoc() != Empty)
477         return OpInst;
478   }
479
480   return I;
481 }
482
483 /// \brief Set the debug location in the builder using the debug location in the
484 /// instruction.
485 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
486   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
487     B.SetCurrentDebugLocation(Inst->getDebugLoc());
488   else
489     B.SetCurrentDebugLocation(DebugLoc());
490 }
491
492 #ifndef NDEBUG
493 /// \return string containing a file name and a line # for the given loop.
494 static std::string getDebugLocString(const Loop *L) {
495   std::string Result;
496   if (L) {
497     raw_string_ostream OS(Result);
498     const DebugLoc LoopDbgLoc = L->getStartLoc();
499     if (!LoopDbgLoc.isUnknown())
500       LoopDbgLoc.print(OS);
501     else
502       // Just print the module name.
503       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
504     OS.flush();
505   }
506   return Result;
507 }
508 #endif
509
510 /// \brief Propagate known metadata from one instruction to another.
511 static void propagateMetadata(Instruction *To, const Instruction *From) {
512   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
513   From->getAllMetadataOtherThanDebugLoc(Metadata);
514
515   for (auto M : Metadata) {
516     unsigned Kind = M.first;
517
518     // These are safe to transfer (this is safe for TBAA, even when we
519     // if-convert, because should that metadata have had a control dependency
520     // on the condition, and thus actually aliased with some other
521     // non-speculated memory access when the condition was false, this would be
522     // caught by the runtime overlap checks).
523     if (Kind != LLVMContext::MD_tbaa &&
524         Kind != LLVMContext::MD_alias_scope &&
525         Kind != LLVMContext::MD_noalias &&
526         Kind != LLVMContext::MD_fpmath)
527       continue;
528
529     To->setMetadata(Kind, M.second);
530   }
531 }
532
533 /// \brief Propagate known metadata from one instruction to a vector of others.
534 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
535   for (Value *V : To)
536     if (Instruction *I = dyn_cast<Instruction>(V))
537       propagateMetadata(I, From);
538 }
539
540 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
541 /// to what vectorization factor.
542 /// This class does not look at the profitability of vectorization, only the
543 /// legality. This class has two main kinds of checks:
544 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
545 ///   will change the order of memory accesses in a way that will change the
546 ///   correctness of the program.
547 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
548 /// checks for a number of different conditions, such as the availability of a
549 /// single induction variable, that all types are supported and vectorize-able,
550 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
551 /// This class is also used by InnerLoopVectorizer for identifying
552 /// induction variable and the different reduction variables.
553 class LoopVectorizationLegality {
554 public:
555   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
556                             DominatorTree *DT, TargetLibraryInfo *TLI,
557                             AliasAnalysis *AA, Function *F,
558                             const TargetTransformInfo *TTI,
559                             LoopAccessAnalysis *LAA)
560       : NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
561         TLI(TLI), TheFunction(F), TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr),
562         Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false) {}
563
564   /// This enum represents the kinds of reductions that we support.
565   enum ReductionKind {
566     RK_NoReduction, ///< Not a reduction.
567     RK_IntegerAdd,  ///< Sum of integers.
568     RK_IntegerMult, ///< Product of integers.
569     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
570     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
571     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
572     RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
573     RK_FloatAdd,    ///< Sum of floats.
574     RK_FloatMult,   ///< Product of floats.
575     RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
576   };
577
578   /// This enum represents the kinds of inductions that we support.
579   enum InductionKind {
580     IK_NoInduction,  ///< Not an induction variable.
581     IK_IntInduction, ///< Integer induction variable. Step = C.
582     IK_PtrInduction  ///< Pointer induction var. Step = C / sizeof(elem).
583   };
584
585   // This enum represents the kind of minmax reduction.
586   enum MinMaxReductionKind {
587     MRK_Invalid,
588     MRK_UIntMin,
589     MRK_UIntMax,
590     MRK_SIntMin,
591     MRK_SIntMax,
592     MRK_FloatMin,
593     MRK_FloatMax
594   };
595
596   /// This struct holds information about reduction variables.
597   struct ReductionDescriptor {
598     ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
599       Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
600
601     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
602                         MinMaxReductionKind MK)
603         : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
604
605     // The starting value of the reduction.
606     // It does not have to be zero!
607     TrackingVH<Value> StartValue;
608     // The instruction who's value is used outside the loop.
609     Instruction *LoopExitInstr;
610     // The kind of the reduction.
611     ReductionKind Kind;
612     // If this a min/max reduction the kind of reduction.
613     MinMaxReductionKind MinMaxKind;
614   };
615
616   /// This POD struct holds information about a potential reduction operation.
617   struct ReductionInstDesc {
618     ReductionInstDesc(bool IsRedux, Instruction *I) :
619       IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
620
621     ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
622       IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
623
624     // Is this instruction a reduction candidate.
625     bool IsReduction;
626     // The last instruction in a min/max pattern (select of the select(icmp())
627     // pattern), or the current reduction instruction otherwise.
628     Instruction *PatternLastInst;
629     // If this is a min/max pattern the comparison predicate.
630     MinMaxReductionKind MinMaxKind;
631   };
632
633   /// A struct for saving information about induction variables.
634   struct InductionInfo {
635     InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
636         : StartValue(Start), IK(K), StepValue(Step) {
637       assert(IK != IK_NoInduction && "Not an induction");
638       assert(StartValue && "StartValue is null");
639       assert(StepValue && !StepValue->isZero() && "StepValue is zero");
640       assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
641              "StartValue is not a pointer for pointer induction");
642       assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
643              "StartValue is not an integer for integer induction");
644       assert(StepValue->getType()->isIntegerTy() &&
645              "StepValue is not an integer");
646     }
647     InductionInfo()
648         : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
649
650     /// Get the consecutive direction. Returns:
651     ///   0 - unknown or non-consecutive.
652     ///   1 - consecutive and increasing.
653     ///  -1 - consecutive and decreasing.
654     int getConsecutiveDirection() const {
655       if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
656         return StepValue->getSExtValue();
657       return 0;
658     }
659
660     /// Compute the transformed value of Index at offset StartValue using step
661     /// StepValue.
662     /// For integer induction, returns StartValue + Index * StepValue.
663     /// For pointer induction, returns StartValue[Index * StepValue].
664     /// FIXME: The newly created binary instructions should contain nsw/nuw
665     /// flags, which can be found from the original scalar operations.
666     Value *transform(IRBuilder<> &B, Value *Index) const {
667       switch (IK) {
668       case IK_IntInduction:
669         assert(Index->getType() == StartValue->getType() &&
670                "Index type does not match StartValue type");
671         if (StepValue->isMinusOne())
672           return B.CreateSub(StartValue, Index);
673         if (!StepValue->isOne())
674           Index = B.CreateMul(Index, StepValue);
675         return B.CreateAdd(StartValue, Index);
676
677       case IK_PtrInduction:
678         if (StepValue->isMinusOne())
679           Index = B.CreateNeg(Index);
680         else if (!StepValue->isOne())
681           Index = B.CreateMul(Index, StepValue);
682         return B.CreateGEP(StartValue, Index);
683
684       case IK_NoInduction:
685         return nullptr;
686       }
687       llvm_unreachable("invalid enum");
688     }
689
690     /// Start value.
691     TrackingVH<Value> StartValue;
692     /// Induction kind.
693     InductionKind IK;
694     /// Step value.
695     ConstantInt *StepValue;
696   };
697
698   /// ReductionList contains the reduction descriptors for all
699   /// of the reductions that were found in the loop.
700   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
701
702   /// InductionList saves induction variables and maps them to the
703   /// induction descriptor.
704   typedef MapVector<PHINode*, InductionInfo> InductionList;
705
706   /// Returns true if it is legal to vectorize this loop.
707   /// This does not mean that it is profitable to vectorize this
708   /// loop, only that it is legal to do so.
709   bool canVectorize();
710
711   /// Returns the Induction variable.
712   PHINode *getInduction() { return Induction; }
713
714   /// Returns the reduction variables found in the loop.
715   ReductionList *getReductionVars() { return &Reductions; }
716
717   /// Returns the induction variables found in the loop.
718   InductionList *getInductionVars() { return &Inductions; }
719
720   /// Returns the widest induction type.
721   Type *getWidestInductionType() { return WidestIndTy; }
722
723   /// Returns True if V is an induction variable in this loop.
724   bool isInductionVariable(const Value *V);
725
726   /// Return true if the block BB needs to be predicated in order for the loop
727   /// to be vectorized.
728   bool blockNeedsPredication(BasicBlock *BB);
729
730   /// Check if this  pointer is consecutive when vectorizing. This happens
731   /// when the last index of the GEP is the induction variable, or that the
732   /// pointer itself is an induction variable.
733   /// This check allows us to vectorize A[idx] into a wide load/store.
734   /// Returns:
735   /// 0 - Stride is unknown or non-consecutive.
736   /// 1 - Address is consecutive.
737   /// -1 - Address is consecutive, and decreasing.
738   int isConsecutivePtr(Value *Ptr);
739
740   /// Returns true if the value V is uniform within the loop.
741   bool isUniform(Value *V);
742
743   /// Returns true if this instruction will remain scalar after vectorization.
744   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
745
746   /// Returns the information that we collected about runtime memory check.
747   const LoopAccessInfo::RuntimePointerCheck *getRuntimePointerCheck() const {
748     return LAI->getRuntimePointerCheck();
749   }
750
751   const LoopAccessInfo *getLAI() const {
752     return LAI;
753   }
754
755   /// This function returns the identity element (or neutral element) for
756   /// the operation K.
757   static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
758
759   unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
760
761   bool hasStride(Value *V) { return StrideSet.count(V); }
762   bool mustCheckStrides() { return !StrideSet.empty(); }
763   SmallPtrSet<Value *, 8>::iterator strides_begin() {
764     return StrideSet.begin();
765   }
766   SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
767
768   /// Returns true if the target machine supports masked store operation
769   /// for the given \p DataType and kind of access to \p Ptr.
770   bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
771     return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
772   }
773   /// Returns true if the target machine supports masked load operation
774   /// for the given \p DataType and kind of access to \p Ptr.
775   bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
776     return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
777   }
778   /// Returns true if vector representation of the instruction \p I
779   /// requires mask.
780   bool isMaskRequired(const Instruction* I) {
781     return (MaskedOp.count(I) != 0);
782   }
783   unsigned getNumStores() const {
784     return LAI->getNumStores();
785   }
786   unsigned getNumLoads() const {
787     return LAI->getNumLoads();
788   }
789   unsigned getNumPredStores() const {
790     return NumPredStores;
791   }
792 private:
793   /// Check if a single basic block loop is vectorizable.
794   /// At this point we know that this is a loop with a constant trip count
795   /// and we only need to check individual instructions.
796   bool canVectorizeInstrs();
797
798   /// When we vectorize loops we may change the order in which
799   /// we read and write from memory. This method checks if it is
800   /// legal to vectorize the code, considering only memory constrains.
801   /// Returns true if the loop is vectorizable
802   bool canVectorizeMemory();
803
804   /// Return true if we can vectorize this loop using the IF-conversion
805   /// transformation.
806   bool canVectorizeWithIfConvert();
807
808   /// Collect the variables that need to stay uniform after vectorization.
809   void collectLoopUniforms();
810
811   /// Return true if all of the instructions in the block can be speculatively
812   /// executed. \p SafePtrs is a list of addresses that are known to be legal
813   /// and we know that we can read from them without segfault.
814   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
815
816   /// Returns True, if 'Phi' is the kind of reduction variable for type
817   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
818   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
819   /// Returns a struct describing if the instruction 'I' can be a reduction
820   /// variable of type 'Kind'. If the reduction is a min/max pattern of
821   /// select(icmp()) this function advances the instruction pointer 'I' from the
822   /// compare instruction to the select instruction and stores this pointer in
823   /// 'PatternLastInst' member of the returned struct.
824   ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
825                                      ReductionInstDesc &Desc);
826   /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
827   /// pattern corresponding to a min(X, Y) or max(X, Y).
828   static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
829                                                     ReductionInstDesc &Prev);
830   /// Returns the induction kind of Phi and record the step. This function may
831   /// return NoInduction if the PHI is not an induction variable.
832   InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
833
834   /// \brief Collect memory access with loop invariant strides.
835   ///
836   /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
837   /// invariant.
838   void collectStridedAccess(Value *LoadOrStoreInst);
839
840   /// Report an analysis message to assist the user in diagnosing loops that are
841   /// not vectorized.  These are handled as LoopAccessReport rather than
842   /// VectorizationReport because the << operator of VectorizationReport returns
843   /// LoopAccessReport.
844   void emitAnalysis(const LoopAccessReport &Message) {
845     LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
846   }
847
848   unsigned NumPredStores;
849
850   /// The loop that we evaluate.
851   Loop *TheLoop;
852   /// Scev analysis.
853   ScalarEvolution *SE;
854   /// DataLayout analysis.
855   const DataLayout *DL;
856   /// Target Library Info.
857   TargetLibraryInfo *TLI;
858   /// Parent function
859   Function *TheFunction;
860   /// Target Transform Info
861   const TargetTransformInfo *TTI;
862   /// Dominator Tree.
863   DominatorTree *DT;
864   // LoopAccess analysis.
865   LoopAccessAnalysis *LAA;
866   // And the loop-accesses info corresponding to this loop.  This pointer is
867   // null until canVectorizeMemory sets it up.
868   const LoopAccessInfo *LAI;
869
870   //  ---  vectorization state --- //
871
872   /// Holds the integer induction variable. This is the counter of the
873   /// loop.
874   PHINode *Induction;
875   /// Holds the reduction variables.
876   ReductionList Reductions;
877   /// Holds all of the induction variables that we found in the loop.
878   /// Notice that inductions don't need to start at zero and that induction
879   /// variables can be pointers.
880   InductionList Inductions;
881   /// Holds the widest induction type encountered.
882   Type *WidestIndTy;
883
884   /// Allowed outside users. This holds the reduction
885   /// vars which can be accessed from outside the loop.
886   SmallPtrSet<Value*, 4> AllowedExit;
887   /// This set holds the variables which are known to be uniform after
888   /// vectorization.
889   SmallPtrSet<Instruction*, 4> Uniforms;
890
891   /// Can we assume the absence of NaNs.
892   bool HasFunNoNaNAttr;
893
894   ValueToValueMap Strides;
895   SmallPtrSet<Value *, 8> StrideSet;
896   
897   /// While vectorizing these instructions we have to generate a
898   /// call to the appropriate masked intrinsic
899   SmallPtrSet<const Instruction*, 8> MaskedOp;
900 };
901
902 /// LoopVectorizationCostModel - estimates the expected speedups due to
903 /// vectorization.
904 /// In many cases vectorization is not profitable. This can happen because of
905 /// a number of reasons. In this class we mainly attempt to predict the
906 /// expected speedup/slowdowns due to the supported instruction set. We use the
907 /// TargetTransformInfo to query the different backends for the cost of
908 /// different operations.
909 class LoopVectorizationCostModel {
910 public:
911   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
912                              LoopVectorizationLegality *Legal,
913                              const TargetTransformInfo &TTI,
914                              const DataLayout *DL, const TargetLibraryInfo *TLI,
915                              AssumptionCache *AC, const Function *F,
916                              const LoopVectorizeHints *Hints)
917       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
918         TheFunction(F), Hints(Hints) {
919     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
920   }
921
922   /// Information about vectorization costs
923   struct VectorizationFactor {
924     unsigned Width; // Vector width with best cost
925     unsigned Cost; // Cost of the loop with that width
926   };
927   /// \return The most profitable vectorization factor and the cost of that VF.
928   /// This method checks every power of two up to VF. If UserVF is not ZERO
929   /// then this vectorization factor will be selected if vectorization is
930   /// possible.
931   VectorizationFactor selectVectorizationFactor(bool OptForSize);
932
933   /// \return The size (in bits) of the widest type in the code that
934   /// needs to be vectorized. We ignore values that remain scalar such as
935   /// 64 bit loop indices.
936   unsigned getWidestType();
937
938   /// \return The most profitable unroll factor.
939   /// If UserUF is non-zero then this method finds the best unroll-factor
940   /// based on register pressure and other parameters.
941   /// VF and LoopCost are the selected vectorization factor and the cost of the
942   /// selected VF.
943   unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
944
945   /// \brief A struct that represents some properties of the register usage
946   /// of a loop.
947   struct RegisterUsage {
948     /// Holds the number of loop invariant values that are used in the loop.
949     unsigned LoopInvariantRegs;
950     /// Holds the maximum number of concurrent live intervals in the loop.
951     unsigned MaxLocalUsers;
952     /// Holds the number of instructions in the loop.
953     unsigned NumInstructions;
954   };
955
956   /// \return  information about the register usage of the loop.
957   RegisterUsage calculateRegisterUsage();
958
959 private:
960   /// Returns the expected execution cost. The unit of the cost does
961   /// not matter because we use the 'cost' units to compare different
962   /// vector widths. The cost that is returned is *not* normalized by
963   /// the factor width.
964   unsigned expectedCost(unsigned VF);
965
966   /// Returns the execution time cost of an instruction for a given vector
967   /// width. Vector width of one means scalar.
968   unsigned getInstructionCost(Instruction *I, unsigned VF);
969
970   /// Returns whether the instruction is a load or store and will be a emitted
971   /// as a vector operation.
972   bool isConsecutiveLoadOrStore(Instruction *I);
973
974   /// Report an analysis message to assist the user in diagnosing loops that are
975   /// not vectorized.  These are handled as LoopAccessReport rather than
976   /// VectorizationReport because the << operator of VectorizationReport returns
977   /// LoopAccessReport.
978   void emitAnalysis(const LoopAccessReport &Message) {
979     LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
980   }
981
982   /// Values used only by @llvm.assume calls.
983   SmallPtrSet<const Value *, 32> EphValues;
984
985   /// The loop that we evaluate.
986   Loop *TheLoop;
987   /// Scev analysis.
988   ScalarEvolution *SE;
989   /// Loop Info analysis.
990   LoopInfo *LI;
991   /// Vectorization legality.
992   LoopVectorizationLegality *Legal;
993   /// Vector target information.
994   const TargetTransformInfo &TTI;
995   /// Target data layout information.
996   const DataLayout *DL;
997   /// Target Library Info.
998   const TargetLibraryInfo *TLI;
999   const Function *TheFunction;
1000   // Loop Vectorize Hint.
1001   const LoopVectorizeHints *Hints;
1002 };
1003
1004 /// Utility class for getting and setting loop vectorizer hints in the form
1005 /// of loop metadata.
1006 /// This class keeps a number of loop annotations locally (as member variables)
1007 /// and can, upon request, write them back as metadata on the loop. It will
1008 /// initially scan the loop for existing metadata, and will update the local
1009 /// values based on information in the loop.
1010 /// We cannot write all values to metadata, as the mere presence of some info,
1011 /// for example 'force', means a decision has been made. So, we need to be
1012 /// careful NOT to add them if the user hasn't specifically asked so.
1013 class LoopVectorizeHints {
1014   enum HintKind {
1015     HK_WIDTH,
1016     HK_UNROLL,
1017     HK_FORCE
1018   };
1019
1020   /// Hint - associates name and validation with the hint value.
1021   struct Hint {
1022     const char * Name;
1023     unsigned Value; // This may have to change for non-numeric values.
1024     HintKind Kind;
1025
1026     Hint(const char * Name, unsigned Value, HintKind Kind)
1027       : Name(Name), Value(Value), Kind(Kind) { }
1028
1029     bool validate(unsigned Val) {
1030       switch (Kind) {
1031       case HK_WIDTH:
1032         return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1033       case HK_UNROLL:
1034         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1035       case HK_FORCE:
1036         return (Val <= 1);
1037       }
1038       return false;
1039     }
1040   };
1041
1042   /// Vectorization width.
1043   Hint Width;
1044   /// Vectorization interleave factor.
1045   Hint Interleave;
1046   /// Vectorization forced
1047   Hint Force;
1048
1049   /// Return the loop metadata prefix.
1050   static StringRef Prefix() { return "llvm.loop."; }
1051
1052 public:
1053   enum ForceKind {
1054     FK_Undefined = -1, ///< Not selected.
1055     FK_Disabled = 0,   ///< Forcing disabled.
1056     FK_Enabled = 1,    ///< Forcing enabled.
1057   };
1058
1059   LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1060       : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1061               HK_WIDTH),
1062         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1063         Force("vectorize.enable", FK_Undefined, HK_FORCE),
1064         TheLoop(L) {
1065     // Populate values with existing loop metadata.
1066     getHintsFromMetadata();
1067
1068     // force-vector-interleave overrides DisableInterleaving.
1069     if (VectorizerParams::isInterleaveForced())
1070       Interleave.Value = VectorizerParams::VectorizationInterleave;
1071
1072     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1073           << "LV: Interleaving disabled by the pass manager\n");
1074   }
1075
1076   /// Mark the loop L as already vectorized by setting the width to 1.
1077   void setAlreadyVectorized() {
1078     Width.Value = Interleave.Value = 1;
1079     Hint Hints[] = {Width, Interleave};
1080     writeHintsToMetadata(Hints);
1081   }
1082
1083   /// Dumps all the hint information.
1084   std::string emitRemark() const {
1085     VectorizationReport R;
1086     if (Force.Value == LoopVectorizeHints::FK_Disabled)
1087       R << "vectorization is explicitly disabled";
1088     else {
1089       R << "use -Rpass-analysis=loop-vectorize for more info";
1090       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1091         R << " (Force=true";
1092         if (Width.Value != 0)
1093           R << ", Vector Width=" << Width.Value;
1094         if (Interleave.Value != 0)
1095           R << ", Interleave Count=" << Interleave.Value;
1096         R << ")";
1097       }
1098     }
1099
1100     return R.str();
1101   }
1102
1103   unsigned getWidth() const { return Width.Value; }
1104   unsigned getInterleave() const { return Interleave.Value; }
1105   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1106
1107 private:
1108   /// Find hints specified in the loop metadata and update local values.
1109   void getHintsFromMetadata() {
1110     MDNode *LoopID = TheLoop->getLoopID();
1111     if (!LoopID)
1112       return;
1113
1114     // First operand should refer to the loop id itself.
1115     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1116     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1117
1118     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1119       const MDString *S = nullptr;
1120       SmallVector<Metadata *, 4> Args;
1121
1122       // The expected hint is either a MDString or a MDNode with the first
1123       // operand a MDString.
1124       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1125         if (!MD || MD->getNumOperands() == 0)
1126           continue;
1127         S = dyn_cast<MDString>(MD->getOperand(0));
1128         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1129           Args.push_back(MD->getOperand(i));
1130       } else {
1131         S = dyn_cast<MDString>(LoopID->getOperand(i));
1132         assert(Args.size() == 0 && "too many arguments for MDString");
1133       }
1134
1135       if (!S)
1136         continue;
1137
1138       // Check if the hint starts with the loop metadata prefix.
1139       StringRef Name = S->getString();
1140       if (Args.size() == 1)
1141         setHint(Name, Args[0]);
1142     }
1143   }
1144
1145   /// Checks string hint with one operand and set value if valid.
1146   void setHint(StringRef Name, Metadata *Arg) {
1147     if (!Name.startswith(Prefix()))
1148       return;
1149     Name = Name.substr(Prefix().size(), StringRef::npos);
1150
1151     const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1152     if (!C) return;
1153     unsigned Val = C->getZExtValue();
1154
1155     Hint *Hints[] = {&Width, &Interleave, &Force};
1156     for (auto H : Hints) {
1157       if (Name == H->Name) {
1158         if (H->validate(Val))
1159           H->Value = Val;
1160         else
1161           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1162         break;
1163       }
1164     }
1165   }
1166
1167   /// Create a new hint from name / value pair.
1168   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1169     LLVMContext &Context = TheLoop->getHeader()->getContext();
1170     Metadata *MDs[] = {MDString::get(Context, Name),
1171                        ConstantAsMetadata::get(
1172                            ConstantInt::get(Type::getInt32Ty(Context), V))};
1173     return MDNode::get(Context, MDs);
1174   }
1175
1176   /// Matches metadata with hint name.
1177   bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1178     MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1179     if (!Name)
1180       return false;
1181
1182     for (auto H : HintTypes)
1183       if (Name->getString().endswith(H.Name))
1184         return true;
1185     return false;
1186   }
1187
1188   /// Sets current hints into loop metadata, keeping other values intact.
1189   void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1190     if (HintTypes.size() == 0)
1191       return;
1192
1193     // Reserve the first element to LoopID (see below).
1194     SmallVector<Metadata *, 4> MDs(1);
1195     // If the loop already has metadata, then ignore the existing operands.
1196     MDNode *LoopID = TheLoop->getLoopID();
1197     if (LoopID) {
1198       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1199         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1200         // If node in update list, ignore old value.
1201         if (!matchesHintMetadataName(Node, HintTypes))
1202           MDs.push_back(Node);
1203       }
1204     }
1205
1206     // Now, add the missing hints.
1207     for (auto H : HintTypes)
1208       MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1209
1210     // Replace current metadata node with new one.
1211     LLVMContext &Context = TheLoop->getHeader()->getContext();
1212     MDNode *NewLoopID = MDNode::get(Context, MDs);
1213     // Set operand 0 to refer to the loop id itself.
1214     NewLoopID->replaceOperandWith(0, NewLoopID);
1215
1216     TheLoop->setLoopID(NewLoopID);
1217   }
1218
1219   /// The loop these hints belong to.
1220   const Loop *TheLoop;
1221 };
1222
1223 static void emitMissedWarning(Function *F, Loop *L,
1224                               const LoopVectorizeHints &LH) {
1225   emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1226                                L->getStartLoc(), LH.emitRemark());
1227
1228   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1229     if (LH.getWidth() != 1)
1230       emitLoopVectorizeWarning(
1231           F->getContext(), *F, L->getStartLoc(),
1232           "failed explicitly specified loop vectorization");
1233     else if (LH.getInterleave() != 1)
1234       emitLoopInterleaveWarning(
1235           F->getContext(), *F, L->getStartLoc(),
1236           "failed explicitly specified loop interleaving");
1237   }
1238 }
1239
1240 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1241   if (L.empty())
1242     return V.push_back(&L);
1243
1244   for (Loop *InnerL : L)
1245     addInnerLoop(*InnerL, V);
1246 }
1247
1248 /// The LoopVectorize Pass.
1249 struct LoopVectorize : public FunctionPass {
1250   /// Pass identification, replacement for typeid
1251   static char ID;
1252
1253   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1254     : FunctionPass(ID),
1255       DisableUnrolling(NoUnrolling),
1256       AlwaysVectorize(AlwaysVectorize) {
1257     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1258   }
1259
1260   ScalarEvolution *SE;
1261   const DataLayout *DL;
1262   LoopInfo *LI;
1263   TargetTransformInfo *TTI;
1264   DominatorTree *DT;
1265   BlockFrequencyInfo *BFI;
1266   TargetLibraryInfo *TLI;
1267   AliasAnalysis *AA;
1268   AssumptionCache *AC;
1269   LoopAccessAnalysis *LAA;
1270   bool DisableUnrolling;
1271   bool AlwaysVectorize;
1272
1273   BlockFrequency ColdEntryFreq;
1274
1275   bool runOnFunction(Function &F) override {
1276     SE = &getAnalysis<ScalarEvolution>();
1277     DL = &F.getParent()->getDataLayout();
1278     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1279     TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1280     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1281     BFI = &getAnalysis<BlockFrequencyInfo>();
1282     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1283     TLI = TLIP ? &TLIP->getTLI() : nullptr;
1284     AA = &getAnalysis<AliasAnalysis>();
1285     AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1286     LAA = &getAnalysis<LoopAccessAnalysis>();
1287
1288     // Compute some weights outside of the loop over the loops. Compute this
1289     // using a BranchProbability to re-use its scaling math.
1290     const BranchProbability ColdProb(1, 5); // 20%
1291     ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1292
1293     // If the target claims to have no vector registers don't attempt
1294     // vectorization.
1295     if (!TTI->getNumberOfRegisters(true))
1296       return false;
1297
1298     if (!DL) {
1299       DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1300                    << ": Missing data layout\n");
1301       return false;
1302     }
1303
1304     // Build up a worklist of inner-loops to vectorize. This is necessary as
1305     // the act of vectorizing or partially unrolling a loop creates new loops
1306     // and can invalidate iterators across the loops.
1307     SmallVector<Loop *, 8> Worklist;
1308
1309     for (Loop *L : *LI)
1310       addInnerLoop(*L, Worklist);
1311
1312     LoopsAnalyzed += Worklist.size();
1313
1314     // Now walk the identified inner loops.
1315     bool Changed = false;
1316     while (!Worklist.empty())
1317       Changed |= processLoop(Worklist.pop_back_val());
1318
1319     // Process each loop nest in the function.
1320     return Changed;
1321   }
1322
1323   bool processLoop(Loop *L) {
1324     assert(L->empty() && "Only process inner loops.");
1325
1326 #ifndef NDEBUG
1327     const std::string DebugLocStr = getDebugLocString(L);
1328 #endif /* NDEBUG */
1329
1330     DEBUG(dbgs() << "\nLV: Checking a loop in \""
1331                  << L->getHeader()->getParent()->getName() << "\" from "
1332                  << DebugLocStr << "\n");
1333
1334     LoopVectorizeHints Hints(L, DisableUnrolling);
1335
1336     DEBUG(dbgs() << "LV: Loop hints:"
1337                  << " force="
1338                  << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1339                          ? "disabled"
1340                          : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1341                                 ? "enabled"
1342                                 : "?")) << " width=" << Hints.getWidth()
1343                  << " unroll=" << Hints.getInterleave() << "\n");
1344
1345     // Function containing loop
1346     Function *F = L->getHeader()->getParent();
1347
1348     // Looking at the diagnostic output is the only way to determine if a loop
1349     // was vectorized (other than looking at the IR or machine code), so it
1350     // is important to generate an optimization remark for each loop. Most of
1351     // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1352     // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1353     // less verbose reporting vectorized loops and unvectorized loops that may
1354     // benefit from vectorization, respectively.
1355
1356     if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1357       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1358       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1359                                      L->getStartLoc(), Hints.emitRemark());
1360       return false;
1361     }
1362
1363     if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1364       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1365       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1366                                      L->getStartLoc(), Hints.emitRemark());
1367       return false;
1368     }
1369
1370     if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1371       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1372       emitOptimizationRemarkAnalysis(
1373           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1374           "loop not vectorized: vector width and interleave count are "
1375           "explicitly set to 1");
1376       return false;
1377     }
1378
1379     // Check the loop for a trip count threshold:
1380     // do not vectorize loops with a tiny trip count.
1381     const unsigned TC = SE->getSmallConstantTripCount(L);
1382     if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1383       DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1384                    << "This loop is not worth vectorizing.");
1385       if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1386         DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1387       else {
1388         DEBUG(dbgs() << "\n");
1389         emitOptimizationRemarkAnalysis(
1390             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1391             "vectorization is not beneficial and is not explicitly forced");
1392         return false;
1393       }
1394     }
1395
1396     // Check if it is legal to vectorize the loop.
1397     LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F, TTI, LAA);
1398     if (!LVL.canVectorize()) {
1399       DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1400       emitMissedWarning(F, L, Hints);
1401       return false;
1402     }
1403
1404     // Use the cost model.
1405     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AC, F,
1406                                   &Hints);
1407
1408     // Check the function attributes to find out if this function should be
1409     // optimized for size.
1410     bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1411                       F->hasFnAttribute(Attribute::OptimizeForSize);
1412
1413     // Compute the weighted frequency of this loop being executed and see if it
1414     // is less than 20% of the function entry baseline frequency. Note that we
1415     // always have a canonical loop here because we think we *can* vectoriez.
1416     // FIXME: This is hidden behind a flag due to pervasive problems with
1417     // exactly what block frequency models.
1418     if (LoopVectorizeWithBlockFrequency) {
1419       BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1420       if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1421           LoopEntryFreq < ColdEntryFreq)
1422         OptForSize = true;
1423     }
1424
1425     // Check the function attributes to see if implicit floats are allowed.a
1426     // FIXME: This check doesn't seem possibly correct -- what if the loop is
1427     // an integer loop and the vector instructions selected are purely integer
1428     // vector instructions?
1429     if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1430       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1431             "attribute is used.\n");
1432       emitOptimizationRemarkAnalysis(
1433           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1434           "loop not vectorized due to NoImplicitFloat attribute");
1435       emitMissedWarning(F, L, Hints);
1436       return false;
1437     }
1438
1439     // Select the optimal vectorization factor.
1440     const LoopVectorizationCostModel::VectorizationFactor VF =
1441         CM.selectVectorizationFactor(OptForSize);
1442
1443     // Select the unroll factor.
1444     const unsigned UF =
1445         CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1446
1447     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1448                  << DebugLocStr << '\n');
1449     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1450
1451     if (VF.Width == 1) {
1452       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1453
1454       if (UF == 1) {
1455         emitOptimizationRemarkAnalysis(
1456             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1457             "not beneficial to vectorize and user disabled interleaving");
1458         return false;
1459       }
1460       DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1461
1462       // Report the unrolling decision.
1463       emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1464                              Twine("unrolled with interleaving factor " +
1465                                    Twine(UF) +
1466                                    " (vectorization not beneficial)"));
1467
1468       // We decided not to vectorize, but we may want to unroll.
1469
1470       InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1471       Unroller.vectorize(&LVL);
1472     } else {
1473       // If we decided that it is *legal* to vectorize the loop then do it.
1474       InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1475       LB.vectorize(&LVL);
1476       ++LoopsVectorized;
1477
1478       // Report the vectorization decision.
1479       emitOptimizationRemark(
1480           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1481           Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1482               ", unrolling interleave factor: " + Twine(UF) + ")");
1483     }
1484
1485     // Mark the loop as already vectorized to avoid vectorizing again.
1486     Hints.setAlreadyVectorized();
1487
1488     DEBUG(verifyFunction(*L->getHeader()->getParent()));
1489     return true;
1490   }
1491
1492   void getAnalysisUsage(AnalysisUsage &AU) const override {
1493     AU.addRequired<AssumptionCacheTracker>();
1494     AU.addRequiredID(LoopSimplifyID);
1495     AU.addRequiredID(LCSSAID);
1496     AU.addRequired<BlockFrequencyInfo>();
1497     AU.addRequired<DominatorTreeWrapperPass>();
1498     AU.addRequired<LoopInfoWrapperPass>();
1499     AU.addRequired<ScalarEvolution>();
1500     AU.addRequired<TargetTransformInfoWrapperPass>();
1501     AU.addRequired<AliasAnalysis>();
1502     AU.addRequired<LoopAccessAnalysis>();
1503     AU.addPreserved<LoopInfoWrapperPass>();
1504     AU.addPreserved<DominatorTreeWrapperPass>();
1505     AU.addPreserved<AliasAnalysis>();
1506   }
1507
1508 };
1509
1510 } // end anonymous namespace
1511
1512 //===----------------------------------------------------------------------===//
1513 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1514 // LoopVectorizationCostModel.
1515 //===----------------------------------------------------------------------===//
1516
1517 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1518   // We need to place the broadcast of invariant variables outside the loop.
1519   Instruction *Instr = dyn_cast<Instruction>(V);
1520   bool NewInstr =
1521       (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1522                           Instr->getParent()) != LoopVectorBody.end());
1523   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1524
1525   // Place the code for broadcasting invariant variables in the new preheader.
1526   IRBuilder<>::InsertPointGuard Guard(Builder);
1527   if (Invariant)
1528     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1529
1530   // Broadcast the scalar into all locations in the vector.
1531   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1532
1533   return Shuf;
1534 }
1535
1536 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1537                                           Value *Step) {
1538   assert(Val->getType()->isVectorTy() && "Must be a vector");
1539   assert(Val->getType()->getScalarType()->isIntegerTy() &&
1540          "Elem must be an integer");
1541   assert(Step->getType() == Val->getType()->getScalarType() &&
1542          "Step has wrong type");
1543   // Create the types.
1544   Type *ITy = Val->getType()->getScalarType();
1545   VectorType *Ty = cast<VectorType>(Val->getType());
1546   int VLen = Ty->getNumElements();
1547   SmallVector<Constant*, 8> Indices;
1548
1549   // Create a vector of consecutive numbers from zero to VF.
1550   for (int i = 0; i < VLen; ++i)
1551     Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1552
1553   // Add the consecutive indices to the vector value.
1554   Constant *Cv = ConstantVector::get(Indices);
1555   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1556   Step = Builder.CreateVectorSplat(VLen, Step);
1557   assert(Step->getType() == Val->getType() && "Invalid step vec");
1558   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1559   // which can be found from the original scalar operations.
1560   Step = Builder.CreateMul(Cv, Step);
1561   return Builder.CreateAdd(Val, Step, "induction");
1562 }
1563
1564 /// \brief Find the operand of the GEP that should be checked for consecutive
1565 /// stores. This ignores trailing indices that have no effect on the final
1566 /// pointer.
1567 static unsigned getGEPInductionOperand(const DataLayout *DL,
1568                                        const GetElementPtrInst *Gep) {
1569   unsigned LastOperand = Gep->getNumOperands() - 1;
1570   unsigned GEPAllocSize = DL->getTypeAllocSize(
1571       cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1572
1573   // Walk backwards and try to peel off zeros.
1574   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1575     // Find the type we're currently indexing into.
1576     gep_type_iterator GEPTI = gep_type_begin(Gep);
1577     std::advance(GEPTI, LastOperand - 1);
1578
1579     // If it's a type with the same allocation size as the result of the GEP we
1580     // can peel off the zero index.
1581     if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1582       break;
1583     --LastOperand;
1584   }
1585
1586   return LastOperand;
1587 }
1588
1589 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1590   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1591   // Make sure that the pointer does not point to structs.
1592   if (Ptr->getType()->getPointerElementType()->isAggregateType())
1593     return 0;
1594
1595   // If this value is a pointer induction variable we know it is consecutive.
1596   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1597   if (Phi && Inductions.count(Phi)) {
1598     InductionInfo II = Inductions[Phi];
1599     return II.getConsecutiveDirection();
1600   }
1601
1602   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1603   if (!Gep)
1604     return 0;
1605
1606   unsigned NumOperands = Gep->getNumOperands();
1607   Value *GpPtr = Gep->getPointerOperand();
1608   // If this GEP value is a consecutive pointer induction variable and all of
1609   // the indices are constant then we know it is consecutive. We can
1610   Phi = dyn_cast<PHINode>(GpPtr);
1611   if (Phi && Inductions.count(Phi)) {
1612
1613     // Make sure that the pointer does not point to structs.
1614     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1615     if (GepPtrType->getElementType()->isAggregateType())
1616       return 0;
1617
1618     // Make sure that all of the index operands are loop invariant.
1619     for (unsigned i = 1; i < NumOperands; ++i)
1620       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1621         return 0;
1622
1623     InductionInfo II = Inductions[Phi];
1624     return II.getConsecutiveDirection();
1625   }
1626
1627   unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1628
1629   // Check that all of the gep indices are uniform except for our induction
1630   // operand.
1631   for (unsigned i = 0; i != NumOperands; ++i)
1632     if (i != InductionOperand &&
1633         !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1634       return 0;
1635
1636   // We can emit wide load/stores only if the last non-zero index is the
1637   // induction variable.
1638   const SCEV *Last = nullptr;
1639   if (!Strides.count(Gep))
1640     Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1641   else {
1642     // Because of the multiplication by a stride we can have a s/zext cast.
1643     // We are going to replace this stride by 1 so the cast is safe to ignore.
1644     //
1645     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1646     //  %0 = trunc i64 %indvars.iv to i32
1647     //  %mul = mul i32 %0, %Stride1
1648     //  %idxprom = zext i32 %mul to i64  << Safe cast.
1649     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1650     //
1651     Last = replaceSymbolicStrideSCEV(SE, Strides,
1652                                      Gep->getOperand(InductionOperand), Gep);
1653     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1654       Last =
1655           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1656               ? C->getOperand()
1657               : Last;
1658   }
1659   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1660     const SCEV *Step = AR->getStepRecurrence(*SE);
1661
1662     // The memory is consecutive because the last index is consecutive
1663     // and all other indices are loop invariant.
1664     if (Step->isOne())
1665       return 1;
1666     if (Step->isAllOnesValue())
1667       return -1;
1668   }
1669
1670   return 0;
1671 }
1672
1673 bool LoopVectorizationLegality::isUniform(Value *V) {
1674   return LAI->isUniform(V);
1675 }
1676
1677 InnerLoopVectorizer::VectorParts&
1678 InnerLoopVectorizer::getVectorValue(Value *V) {
1679   assert(V != Induction && "The new induction variable should not be used.");
1680   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1681
1682   // If we have a stride that is replaced by one, do it here.
1683   if (Legal->hasStride(V))
1684     V = ConstantInt::get(V->getType(), 1);
1685
1686   // If we have this scalar in the map, return it.
1687   if (WidenMap.has(V))
1688     return WidenMap.get(V);
1689
1690   // If this scalar is unknown, assume that it is a constant or that it is
1691   // loop invariant. Broadcast V and save the value for future uses.
1692   Value *B = getBroadcastInstrs(V);
1693   return WidenMap.splat(V, B);
1694 }
1695
1696 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1697   assert(Vec->getType()->isVectorTy() && "Invalid type");
1698   SmallVector<Constant*, 8> ShuffleMask;
1699   for (unsigned i = 0; i < VF; ++i)
1700     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1701
1702   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1703                                      ConstantVector::get(ShuffleMask),
1704                                      "reverse");
1705 }
1706
1707 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1708   // Attempt to issue a wide load.
1709   LoadInst *LI = dyn_cast<LoadInst>(Instr);
1710   StoreInst *SI = dyn_cast<StoreInst>(Instr);
1711
1712   assert((LI || SI) && "Invalid Load/Store instruction");
1713
1714   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1715   Type *DataTy = VectorType::get(ScalarDataTy, VF);
1716   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1717   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1718   // An alignment of 0 means target abi alignment. We need to use the scalar's
1719   // target abi alignment in such a case.
1720   if (!Alignment)
1721     Alignment = DL->getABITypeAlignment(ScalarDataTy);
1722   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1723   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1724   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1725
1726   if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
1727       !Legal->isMaskRequired(SI))
1728     return scalarizeInstruction(Instr, true);
1729
1730   if (ScalarAllocatedSize != VectorElementSize)
1731     return scalarizeInstruction(Instr);
1732
1733   // If the pointer is loop invariant or if it is non-consecutive,
1734   // scalarize the load.
1735   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1736   bool Reverse = ConsecutiveStride < 0;
1737   bool UniformLoad = LI && Legal->isUniform(Ptr);
1738   if (!ConsecutiveStride || UniformLoad)
1739     return scalarizeInstruction(Instr);
1740
1741   Constant *Zero = Builder.getInt32(0);
1742   VectorParts &Entry = WidenMap.get(Instr);
1743
1744   // Handle consecutive loads/stores.
1745   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1746   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1747     setDebugLocFromInst(Builder, Gep);
1748     Value *PtrOperand = Gep->getPointerOperand();
1749     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1750     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1751
1752     // Create the new GEP with the new induction variable.
1753     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1754     Gep2->setOperand(0, FirstBasePtr);
1755     Gep2->setName("gep.indvar.base");
1756     Ptr = Builder.Insert(Gep2);
1757   } else if (Gep) {
1758     setDebugLocFromInst(Builder, Gep);
1759     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1760                                OrigLoop) && "Base ptr must be invariant");
1761
1762     // The last index does not have to be the induction. It can be
1763     // consecutive and be a function of the index. For example A[I+1];
1764     unsigned NumOperands = Gep->getNumOperands();
1765     unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1766     // Create the new GEP with the new induction variable.
1767     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1768
1769     for (unsigned i = 0; i < NumOperands; ++i) {
1770       Value *GepOperand = Gep->getOperand(i);
1771       Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1772
1773       // Update last index or loop invariant instruction anchored in loop.
1774       if (i == InductionOperand ||
1775           (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1776         assert((i == InductionOperand ||
1777                SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1778                "Must be last index or loop invariant");
1779
1780         VectorParts &GEPParts = getVectorValue(GepOperand);
1781         Value *Index = GEPParts[0];
1782         Index = Builder.CreateExtractElement(Index, Zero);
1783         Gep2->setOperand(i, Index);
1784         Gep2->setName("gep.indvar.idx");
1785       }
1786     }
1787     Ptr = Builder.Insert(Gep2);
1788   } else {
1789     // Use the induction element ptr.
1790     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1791     setDebugLocFromInst(Builder, Ptr);
1792     VectorParts &PtrVal = getVectorValue(Ptr);
1793     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1794   }
1795
1796   VectorParts Mask = createBlockInMask(Instr->getParent());
1797   // Handle Stores:
1798   if (SI) {
1799     assert(!Legal->isUniform(SI->getPointerOperand()) &&
1800            "We do not allow storing to uniform addresses");
1801     setDebugLocFromInst(Builder, SI);
1802     // We don't want to update the value in the map as it might be used in
1803     // another expression. So don't use a reference type for "StoredVal".
1804     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1805     
1806     for (unsigned Part = 0; Part < UF; ++Part) {
1807       // Calculate the pointer for the specific unroll-part.
1808       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1809
1810       if (Reverse) {
1811         // If we store to reverse consecutive memory locations then we need
1812         // to reverse the order of elements in the stored value.
1813         StoredVal[Part] = reverseVector(StoredVal[Part]);
1814         // If the address is consecutive but reversed, then the
1815         // wide store needs to start at the last vector element.
1816         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1817         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1818         Mask[Part] = reverseVector(Mask[Part]);
1819       }
1820
1821       Value *VecPtr = Builder.CreateBitCast(PartPtr,
1822                                             DataTy->getPointerTo(AddressSpace));
1823
1824       Instruction *NewSI;
1825       if (Legal->isMaskRequired(SI))
1826         NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
1827                                           Mask[Part]);
1828       else 
1829         NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1830       propagateMetadata(NewSI, SI);
1831     }
1832     return;
1833   }
1834
1835   // Handle loads.
1836   assert(LI && "Must have a load instruction");
1837   setDebugLocFromInst(Builder, LI);
1838   for (unsigned Part = 0; Part < UF; ++Part) {
1839     // Calculate the pointer for the specific unroll-part.
1840     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1841
1842     if (Reverse) {
1843       // If the address is consecutive but reversed, then the
1844       // wide load needs to start at the last vector element.
1845       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1846       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1847       Mask[Part] = reverseVector(Mask[Part]);
1848     }
1849
1850     Instruction* NewLI;
1851     Value *VecPtr = Builder.CreateBitCast(PartPtr,
1852                                           DataTy->getPointerTo(AddressSpace));
1853     if (Legal->isMaskRequired(LI))
1854       NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
1855                                        UndefValue::get(DataTy),
1856                                        "wide.masked.load");
1857     else
1858       NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1859     propagateMetadata(NewLI, LI);
1860     Entry[Part] = Reverse ? reverseVector(NewLI) :  NewLI;
1861   }
1862 }
1863
1864 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1865   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1866   // Holds vector parameters or scalars, in case of uniform vals.
1867   SmallVector<VectorParts, 4> Params;
1868
1869   setDebugLocFromInst(Builder, Instr);
1870
1871   // Find all of the vectorized parameters.
1872   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1873     Value *SrcOp = Instr->getOperand(op);
1874
1875     // If we are accessing the old induction variable, use the new one.
1876     if (SrcOp == OldInduction) {
1877       Params.push_back(getVectorValue(SrcOp));
1878       continue;
1879     }
1880
1881     // Try using previously calculated values.
1882     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1883
1884     // If the src is an instruction that appeared earlier in the basic block
1885     // then it should already be vectorized.
1886     if (SrcInst && OrigLoop->contains(SrcInst)) {
1887       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1888       // The parameter is a vector value from earlier.
1889       Params.push_back(WidenMap.get(SrcInst));
1890     } else {
1891       // The parameter is a scalar from outside the loop. Maybe even a constant.
1892       VectorParts Scalars;
1893       Scalars.append(UF, SrcOp);
1894       Params.push_back(Scalars);
1895     }
1896   }
1897
1898   assert(Params.size() == Instr->getNumOperands() &&
1899          "Invalid number of operands");
1900
1901   // Does this instruction return a value ?
1902   bool IsVoidRetTy = Instr->getType()->isVoidTy();
1903
1904   Value *UndefVec = IsVoidRetTy ? nullptr :
1905     UndefValue::get(VectorType::get(Instr->getType(), VF));
1906   // Create a new entry in the WidenMap and initialize it to Undef or Null.
1907   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1908
1909   Instruction *InsertPt = Builder.GetInsertPoint();
1910   BasicBlock *IfBlock = Builder.GetInsertBlock();
1911   BasicBlock *CondBlock = nullptr;
1912
1913   VectorParts Cond;
1914   Loop *VectorLp = nullptr;
1915   if (IfPredicateStore) {
1916     assert(Instr->getParent()->getSinglePredecessor() &&
1917            "Only support single predecessor blocks");
1918     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1919                           Instr->getParent());
1920     VectorLp = LI->getLoopFor(IfBlock);
1921     assert(VectorLp && "Must have a loop for this block");
1922   }
1923
1924   // For each vector unroll 'part':
1925   for (unsigned Part = 0; Part < UF; ++Part) {
1926     // For each scalar that we create:
1927     for (unsigned Width = 0; Width < VF; ++Width) {
1928
1929       // Start if-block.
1930       Value *Cmp = nullptr;
1931       if (IfPredicateStore) {
1932         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1933         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1934         CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1935         LoopVectorBody.push_back(CondBlock);
1936         VectorLp->addBasicBlockToLoop(CondBlock, *LI);
1937         // Update Builder with newly created basic block.
1938         Builder.SetInsertPoint(InsertPt);
1939       }
1940
1941       Instruction *Cloned = Instr->clone();
1942       if (!IsVoidRetTy)
1943         Cloned->setName(Instr->getName() + ".cloned");
1944       // Replace the operands of the cloned instructions with extracted scalars.
1945       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1946         Value *Op = Params[op][Part];
1947         // Param is a vector. Need to extract the right lane.
1948         if (Op->getType()->isVectorTy())
1949           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1950         Cloned->setOperand(op, Op);
1951       }
1952
1953       // Place the cloned scalar in the new loop.
1954       Builder.Insert(Cloned);
1955
1956       // If the original scalar returns a value we need to place it in a vector
1957       // so that future users will be able to use it.
1958       if (!IsVoidRetTy)
1959         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1960                                                        Builder.getInt32(Width));
1961       // End if-block.
1962       if (IfPredicateStore) {
1963          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1964          LoopVectorBody.push_back(NewIfBlock);
1965          VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
1966          Builder.SetInsertPoint(InsertPt);
1967          Instruction *OldBr = IfBlock->getTerminator();
1968          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1969          OldBr->eraseFromParent();
1970          IfBlock = NewIfBlock;
1971       }
1972     }
1973   }
1974 }
1975
1976 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1977                                  Instruction *Loc) {
1978   if (FirstInst)
1979     return FirstInst;
1980   if (Instruction *I = dyn_cast<Instruction>(V))
1981     return I->getParent() == Loc->getParent() ? I : nullptr;
1982   return nullptr;
1983 }
1984
1985 std::pair<Instruction *, Instruction *>
1986 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1987   Instruction *tnullptr = nullptr;
1988   if (!Legal->mustCheckStrides())
1989     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1990
1991   IRBuilder<> ChkBuilder(Loc);
1992
1993   // Emit checks.
1994   Value *Check = nullptr;
1995   Instruction *FirstInst = nullptr;
1996   for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1997                                          SE = Legal->strides_end();
1998        SI != SE; ++SI) {
1999     Value *Ptr = stripIntegerCast(*SI);
2000     Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2001                                        "stride.chk");
2002     // Store the first instruction we create.
2003     FirstInst = getFirstInst(FirstInst, C, Loc);
2004     if (Check)
2005       Check = ChkBuilder.CreateOr(Check, C);
2006     else
2007       Check = C;
2008   }
2009
2010   // We have to do this trickery because the IRBuilder might fold the check to a
2011   // constant expression in which case there is no Instruction anchored in a
2012   // the block.
2013   LLVMContext &Ctx = Loc->getContext();
2014   Instruction *TheCheck =
2015       BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2016   ChkBuilder.Insert(TheCheck, "stride.not.one");
2017   FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2018
2019   return std::make_pair(FirstInst, TheCheck);
2020 }
2021
2022 void InnerLoopVectorizer::createEmptyLoop() {
2023   /*
2024    In this function we generate a new loop. The new loop will contain
2025    the vectorized instructions while the old loop will continue to run the
2026    scalar remainder.
2027
2028        [ ] <-- Back-edge taken count overflow check.
2029     /   |
2030    /    v
2031   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
2032   |  /  |
2033   | /   v
2034   ||   [ ]     <-- vector pre header.
2035   ||    |
2036   ||    v
2037   ||   [  ] \
2038   ||   [  ]_|   <-- vector loop.
2039   ||    |
2040   | \   v
2041   |   >[ ]   <--- middle-block.
2042   |  /  |
2043   | /   v
2044   -|- >[ ]     <--- new preheader.
2045    |    |
2046    |    v
2047    |   [ ] \
2048    |   [ ]_|   <-- old scalar loop to handle remainder.
2049     \   |
2050      \  v
2051       >[ ]     <-- exit block.
2052    ...
2053    */
2054
2055   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2056   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2057   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2058   assert(BypassBlock && "Invalid loop structure");
2059   assert(ExitBlock && "Must have an exit block");
2060
2061   // Some loops have a single integer induction variable, while other loops
2062   // don't. One example is c++ iterators that often have multiple pointer
2063   // induction variables. In the code below we also support a case where we
2064   // don't have a single induction variable.
2065   OldInduction = Legal->getInduction();
2066   Type *IdxTy = Legal->getWidestInductionType();
2067
2068   // Find the loop boundaries.
2069   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2070   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2071
2072   // The exit count might have the type of i64 while the phi is i32. This can
2073   // happen if we have an induction variable that is sign extended before the
2074   // compare. The only way that we get a backedge taken count is that the
2075   // induction variable was signed and as such will not overflow. In such a case
2076   // truncation is legal.
2077   if (ExitCount->getType()->getPrimitiveSizeInBits() >
2078       IdxTy->getPrimitiveSizeInBits())
2079     ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2080
2081   const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2082   // Get the total trip count from the count by adding 1.
2083   ExitCount = SE->getAddExpr(BackedgeTakeCount,
2084                              SE->getConstant(BackedgeTakeCount->getType(), 1));
2085
2086   // Expand the trip count and place the new instructions in the preheader.
2087   // Notice that the pre-header does not change, only the loop body.
2088   SCEVExpander Exp(*SE, "induction");
2089
2090   // We need to test whether the backedge-taken count is uint##_max. Adding one
2091   // to it will cause overflow and an incorrect loop trip count in the vector
2092   // body. In case of overflow we want to directly jump to the scalar remainder
2093   // loop.
2094   Value *BackedgeCount =
2095       Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2096                         BypassBlock->getTerminator());
2097   if (BackedgeCount->getType()->isPointerTy())
2098     BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2099                                                 "backedge.ptrcnt.to.int",
2100                                                 BypassBlock->getTerminator());
2101   Instruction *CheckBCOverflow =
2102       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2103                       Constant::getAllOnesValue(BackedgeCount->getType()),
2104                       "backedge.overflow", BypassBlock->getTerminator());
2105
2106   // The loop index does not have to start at Zero. Find the original start
2107   // value from the induction PHI node. If we don't have an induction variable
2108   // then we know that it starts at zero.
2109   Builder.SetInsertPoint(BypassBlock->getTerminator());
2110   Value *StartIdx = ExtendedIdx = OldInduction ?
2111     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2112                        IdxTy):
2113     ConstantInt::get(IdxTy, 0);
2114
2115   // We need an instruction to anchor the overflow check on. StartIdx needs to
2116   // be defined before the overflow check branch. Because the scalar preheader
2117   // is going to merge the start index and so the overflow branch block needs to
2118   // contain a definition of the start index.
2119   Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2120       StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2121       BypassBlock->getTerminator());
2122
2123   // Count holds the overall loop count (N).
2124   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2125                                    BypassBlock->getTerminator());
2126
2127   LoopBypassBlocks.push_back(BypassBlock);
2128
2129   // Split the single block loop into the two loop structure described above.
2130   BasicBlock *VectorPH =
2131   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2132   BasicBlock *VecBody =
2133   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2134   BasicBlock *MiddleBlock =
2135   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2136   BasicBlock *ScalarPH =
2137   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2138
2139   // Create and register the new vector loop.
2140   Loop* Lp = new Loop();
2141   Loop *ParentLoop = OrigLoop->getParentLoop();
2142
2143   // Insert the new loop into the loop nest and register the new basic blocks
2144   // before calling any utilities such as SCEV that require valid LoopInfo.
2145   if (ParentLoop) {
2146     ParentLoop->addChildLoop(Lp);
2147     ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2148     ParentLoop->addBasicBlockToLoop(VectorPH, *LI);
2149     ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2150   } else {
2151     LI->addTopLevelLoop(Lp);
2152   }
2153   Lp->addBasicBlockToLoop(VecBody, *LI);
2154
2155   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2156   // inside the loop.
2157   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2158
2159   // Generate the induction variable.
2160   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2161   Induction = Builder.CreatePHI(IdxTy, 2, "index");
2162   // The loop step is equal to the vectorization factor (num of SIMD elements)
2163   // times the unroll factor (num of SIMD instructions).
2164   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2165
2166   // This is the IR builder that we use to add all of the logic for bypassing
2167   // the new vector loop.
2168   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2169   setDebugLocFromInst(BypassBuilder,
2170                       getDebugLocFromInstOrOperands(OldInduction));
2171
2172   // We may need to extend the index in case there is a type mismatch.
2173   // We know that the count starts at zero and does not overflow.
2174   if (Count->getType() != IdxTy) {
2175     // The exit count can be of pointer type. Convert it to the correct
2176     // integer type.
2177     if (ExitCount->getType()->isPointerTy())
2178       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2179     else
2180       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2181   }
2182
2183   // Add the start index to the loop count to get the new end index.
2184   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2185
2186   // Now we need to generate the expression for N - (N % VF), which is
2187   // the part that the vectorized body will execute.
2188   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2189   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2190   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2191                                                      "end.idx.rnd.down");
2192
2193   // Now, compare the new count to zero. If it is zero skip the vector loop and
2194   // jump to the scalar loop.
2195   Value *Cmp =
2196       BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2197
2198   BasicBlock *LastBypassBlock = BypassBlock;
2199
2200   // Generate code to check that the loops trip count that we computed by adding
2201   // one to the backedge-taken count will not overflow.
2202   {
2203     auto PastOverflowCheck =
2204         std::next(BasicBlock::iterator(OverflowCheckAnchor));
2205     BasicBlock *CheckBlock =
2206       LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2207     if (ParentLoop)
2208       ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2209     LoopBypassBlocks.push_back(CheckBlock);
2210     Instruction *OldTerm = LastBypassBlock->getTerminator();
2211     BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2212     OldTerm->eraseFromParent();
2213     LastBypassBlock = CheckBlock;
2214   }
2215
2216   // Generate the code to check that the strides we assumed to be one are really
2217   // one. We want the new basic block to start at the first instruction in a
2218   // sequence of instructions that form a check.
2219   Instruction *StrideCheck;
2220   Instruction *FirstCheckInst;
2221   std::tie(FirstCheckInst, StrideCheck) =
2222       addStrideCheck(LastBypassBlock->getTerminator());
2223   if (StrideCheck) {
2224     // Create a new block containing the stride check.
2225     BasicBlock *CheckBlock =
2226         LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2227     if (ParentLoop)
2228       ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2229     LoopBypassBlocks.push_back(CheckBlock);
2230
2231     // Replace the branch into the memory check block with a conditional branch
2232     // for the "few elements case".
2233     Instruction *OldTerm = LastBypassBlock->getTerminator();
2234     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2235     OldTerm->eraseFromParent();
2236
2237     Cmp = StrideCheck;
2238     LastBypassBlock = CheckBlock;
2239   }
2240
2241   // Generate the code that checks in runtime if arrays overlap. We put the
2242   // checks into a separate block to make the more common case of few elements
2243   // faster.
2244   Instruction *MemRuntimeCheck;
2245   std::tie(FirstCheckInst, MemRuntimeCheck) =
2246     Legal->getLAI()->addRuntimeCheck(LastBypassBlock->getTerminator());
2247   if (MemRuntimeCheck) {
2248     // Create a new block containing the memory check.
2249     BasicBlock *CheckBlock =
2250         LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.memcheck");
2251     if (ParentLoop)
2252       ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2253     LoopBypassBlocks.push_back(CheckBlock);
2254
2255     // Replace the branch into the memory check block with a conditional branch
2256     // for the "few elements case".
2257     Instruction *OldTerm = LastBypassBlock->getTerminator();
2258     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2259     OldTerm->eraseFromParent();
2260
2261     Cmp = MemRuntimeCheck;
2262     LastBypassBlock = CheckBlock;
2263   }
2264
2265   LastBypassBlock->getTerminator()->eraseFromParent();
2266   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2267                      LastBypassBlock);
2268
2269   // We are going to resume the execution of the scalar loop.
2270   // Go over all of the induction variables that we found and fix the
2271   // PHIs that are left in the scalar version of the loop.
2272   // The starting values of PHI nodes depend on the counter of the last
2273   // iteration in the vectorized loop.
2274   // If we come from a bypass edge then we need to start from the original
2275   // start value.
2276
2277   // This variable saves the new starting index for the scalar loop.
2278   PHINode *ResumeIndex = nullptr;
2279   LoopVectorizationLegality::InductionList::iterator I, E;
2280   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2281   // Set builder to point to last bypass block.
2282   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2283   for (I = List->begin(), E = List->end(); I != E; ++I) {
2284     PHINode *OrigPhi = I->first;
2285     LoopVectorizationLegality::InductionInfo II = I->second;
2286
2287     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2288     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2289                                          MiddleBlock->getTerminator());
2290     // We might have extended the type of the induction variable but we need a
2291     // truncated version for the scalar loop.
2292     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2293       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2294                       MiddleBlock->getTerminator()) : nullptr;
2295
2296     // Create phi nodes to merge from the  backedge-taken check block.
2297     PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2298                                            ScalarPH->getTerminator());
2299     BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2300
2301     PHINode *BCTruncResumeVal = nullptr;
2302     if (OrigPhi == OldInduction) {
2303       BCTruncResumeVal =
2304           PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2305                           ScalarPH->getTerminator());
2306       BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2307     }
2308
2309     Value *EndValue = nullptr;
2310     switch (II.IK) {
2311     case LoopVectorizationLegality::IK_NoInduction:
2312       llvm_unreachable("Unknown induction");
2313     case LoopVectorizationLegality::IK_IntInduction: {
2314       // Handle the integer induction counter.
2315       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2316
2317       // We have the canonical induction variable.
2318       if (OrigPhi == OldInduction) {
2319         // Create a truncated version of the resume value for the scalar loop,
2320         // we might have promoted the type to a larger width.
2321         EndValue =
2322           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2323         // The new PHI merges the original incoming value, in case of a bypass,
2324         // or the value at the end of the vectorized loop.
2325         for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2326           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2327         TruncResumeVal->addIncoming(EndValue, VecBody);
2328
2329         BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2330
2331         // We know what the end value is.
2332         EndValue = IdxEndRoundDown;
2333         // We also know which PHI node holds it.
2334         ResumeIndex = ResumeVal;
2335         break;
2336       }
2337
2338       // Not the canonical induction variable - add the vector loop count to the
2339       // start value.
2340       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2341                                                    II.StartValue->getType(),
2342                                                    "cast.crd");
2343       EndValue = II.transform(BypassBuilder, CRD);
2344       EndValue->setName("ind.end");
2345       break;
2346     }
2347     case LoopVectorizationLegality::IK_PtrInduction: {
2348       EndValue = II.transform(BypassBuilder, CountRoundDown);
2349       EndValue->setName("ptr.ind.end");
2350       break;
2351     }
2352     }// end of case
2353
2354     // The new PHI merges the original incoming value, in case of a bypass,
2355     // or the value at the end of the vectorized loop.
2356     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2357       if (OrigPhi == OldInduction)
2358         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2359       else
2360         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2361     }
2362     ResumeVal->addIncoming(EndValue, VecBody);
2363
2364     // Fix the scalar body counter (PHI node).
2365     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2366
2367     // The old induction's phi node in the scalar body needs the truncated
2368     // value.
2369     if (OrigPhi == OldInduction) {
2370       BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2371       OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2372     } else {
2373       BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2374       OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2375     }
2376   }
2377
2378   // If we are generating a new induction variable then we also need to
2379   // generate the code that calculates the exit value. This value is not
2380   // simply the end of the counter because we may skip the vectorized body
2381   // in case of a runtime check.
2382   if (!OldInduction){
2383     assert(!ResumeIndex && "Unexpected resume value found");
2384     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2385                                   MiddleBlock->getTerminator());
2386     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2387       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2388     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2389   }
2390
2391   // Make sure that we found the index where scalar loop needs to continue.
2392   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2393          "Invalid resume Index");
2394
2395   // Add a check in the middle block to see if we have completed
2396   // all of the iterations in the first vector loop.
2397   // If (N - N%VF) == N, then we *don't* need to run the remainder.
2398   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2399                                 ResumeIndex, "cmp.n",
2400                                 MiddleBlock->getTerminator());
2401
2402   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2403   // Remove the old terminator.
2404   MiddleBlock->getTerminator()->eraseFromParent();
2405
2406   // Create i+1 and fill the PHINode.
2407   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2408   Induction->addIncoming(StartIdx, VectorPH);
2409   Induction->addIncoming(NextIdx, VecBody);
2410   // Create the compare.
2411   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2412   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2413
2414   // Now we have two terminators. Remove the old one from the block.
2415   VecBody->getTerminator()->eraseFromParent();
2416
2417   // Get ready to start creating new instructions into the vectorized body.
2418   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2419
2420   // Save the state.
2421   LoopVectorPreHeader = VectorPH;
2422   LoopScalarPreHeader = ScalarPH;
2423   LoopMiddleBlock = MiddleBlock;
2424   LoopExitBlock = ExitBlock;
2425   LoopVectorBody.push_back(VecBody);
2426   LoopScalarBody = OldBasicBlock;
2427
2428   LoopVectorizeHints Hints(Lp, true);
2429   Hints.setAlreadyVectorized();
2430 }
2431
2432 /// This function returns the identity element (or neutral element) for
2433 /// the operation K.
2434 Constant*
2435 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2436   switch (K) {
2437   case RK_IntegerXor:
2438   case RK_IntegerAdd:
2439   case RK_IntegerOr:
2440     // Adding, Xoring, Oring zero to a number does not change it.
2441     return ConstantInt::get(Tp, 0);
2442   case RK_IntegerMult:
2443     // Multiplying a number by 1 does not change it.
2444     return ConstantInt::get(Tp, 1);
2445   case RK_IntegerAnd:
2446     // AND-ing a number with an all-1 value does not change it.
2447     return ConstantInt::get(Tp, -1, true);
2448   case  RK_FloatMult:
2449     // Multiplying a number by 1 does not change it.
2450     return ConstantFP::get(Tp, 1.0L);
2451   case  RK_FloatAdd:
2452     // Adding zero to a number does not change it.
2453     return ConstantFP::get(Tp, 0.0L);
2454   default:
2455     llvm_unreachable("Unknown reduction kind");
2456   }
2457 }
2458
2459 /// This function translates the reduction kind to an LLVM binary operator.
2460 static unsigned
2461 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2462   switch (Kind) {
2463     case LoopVectorizationLegality::RK_IntegerAdd:
2464       return Instruction::Add;
2465     case LoopVectorizationLegality::RK_IntegerMult:
2466       return Instruction::Mul;
2467     case LoopVectorizationLegality::RK_IntegerOr:
2468       return Instruction::Or;
2469     case LoopVectorizationLegality::RK_IntegerAnd:
2470       return Instruction::And;
2471     case LoopVectorizationLegality::RK_IntegerXor:
2472       return Instruction::Xor;
2473     case LoopVectorizationLegality::RK_FloatMult:
2474       return Instruction::FMul;
2475     case LoopVectorizationLegality::RK_FloatAdd:
2476       return Instruction::FAdd;
2477     case LoopVectorizationLegality::RK_IntegerMinMax:
2478       return Instruction::ICmp;
2479     case LoopVectorizationLegality::RK_FloatMinMax:
2480       return Instruction::FCmp;
2481     default:
2482       llvm_unreachable("Unknown reduction operation");
2483   }
2484 }
2485
2486 Value *createMinMaxOp(IRBuilder<> &Builder,
2487                       LoopVectorizationLegality::MinMaxReductionKind RK,
2488                       Value *Left,
2489                       Value *Right) {
2490   CmpInst::Predicate P = CmpInst::ICMP_NE;
2491   switch (RK) {
2492   default:
2493     llvm_unreachable("Unknown min/max reduction kind");
2494   case LoopVectorizationLegality::MRK_UIntMin:
2495     P = CmpInst::ICMP_ULT;
2496     break;
2497   case LoopVectorizationLegality::MRK_UIntMax:
2498     P = CmpInst::ICMP_UGT;
2499     break;
2500   case LoopVectorizationLegality::MRK_SIntMin:
2501     P = CmpInst::ICMP_SLT;
2502     break;
2503   case LoopVectorizationLegality::MRK_SIntMax:
2504     P = CmpInst::ICMP_SGT;
2505     break;
2506   case LoopVectorizationLegality::MRK_FloatMin:
2507     P = CmpInst::FCMP_OLT;
2508     break;
2509   case LoopVectorizationLegality::MRK_FloatMax:
2510     P = CmpInst::FCMP_OGT;
2511     break;
2512   }
2513
2514   Value *Cmp;
2515   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2516       RK == LoopVectorizationLegality::MRK_FloatMax)
2517     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2518   else
2519     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2520
2521   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2522   return Select;
2523 }
2524
2525 namespace {
2526 struct CSEDenseMapInfo {
2527   static bool canHandle(Instruction *I) {
2528     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2529            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2530   }
2531   static inline Instruction *getEmptyKey() {
2532     return DenseMapInfo<Instruction *>::getEmptyKey();
2533   }
2534   static inline Instruction *getTombstoneKey() {
2535     return DenseMapInfo<Instruction *>::getTombstoneKey();
2536   }
2537   static unsigned getHashValue(Instruction *I) {
2538     assert(canHandle(I) && "Unknown instruction!");
2539     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2540                                                            I->value_op_end()));
2541   }
2542   static bool isEqual(Instruction *LHS, Instruction *RHS) {
2543     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2544         LHS == getTombstoneKey() || RHS == getTombstoneKey())
2545       return LHS == RHS;
2546     return LHS->isIdenticalTo(RHS);
2547   }
2548 };
2549 }
2550
2551 /// \brief Check whether this block is a predicated block.
2552 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2553 /// = ...;  " blocks. We start with one vectorized basic block. For every
2554 /// conditional block we split this vectorized block. Therefore, every second
2555 /// block will be a predicated one.
2556 static bool isPredicatedBlock(unsigned BlockNum) {
2557   return BlockNum % 2;
2558 }
2559
2560 ///\brief Perform cse of induction variable instructions.
2561 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2562   // Perform simple cse.
2563   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2564   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2565     BasicBlock *BB = BBs[i];
2566     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2567       Instruction *In = I++;
2568
2569       if (!CSEDenseMapInfo::canHandle(In))
2570         continue;
2571
2572       // Check if we can replace this instruction with any of the
2573       // visited instructions.
2574       if (Instruction *V = CSEMap.lookup(In)) {
2575         In->replaceAllUsesWith(V);
2576         In->eraseFromParent();
2577         continue;
2578       }
2579       // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2580       // ...;" blocks for predicated stores. Every second block is a predicated
2581       // block.
2582       if (isPredicatedBlock(i))
2583         continue;
2584
2585       CSEMap[In] = In;
2586     }
2587   }
2588 }
2589
2590 /// \brief Adds a 'fast' flag to floating point operations.
2591 static Value *addFastMathFlag(Value *V) {
2592   if (isa<FPMathOperator>(V)){
2593     FastMathFlags Flags;
2594     Flags.setUnsafeAlgebra();
2595     cast<Instruction>(V)->setFastMathFlags(Flags);
2596   }
2597   return V;
2598 }
2599
2600 void InnerLoopVectorizer::vectorizeLoop() {
2601   //===------------------------------------------------===//
2602   //
2603   // Notice: any optimization or new instruction that go
2604   // into the code below should be also be implemented in
2605   // the cost-model.
2606   //
2607   //===------------------------------------------------===//
2608   Constant *Zero = Builder.getInt32(0);
2609
2610   // In order to support reduction variables we need to be able to vectorize
2611   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2612   // stages. First, we create a new vector PHI node with no incoming edges.
2613   // We use this value when we vectorize all of the instructions that use the
2614   // PHI. Next, after all of the instructions in the block are complete we
2615   // add the new incoming edges to the PHI. At this point all of the
2616   // instructions in the basic block are vectorized, so we can use them to
2617   // construct the PHI.
2618   PhiVector RdxPHIsToFix;
2619
2620   // Scan the loop in a topological order to ensure that defs are vectorized
2621   // before users.
2622   LoopBlocksDFS DFS(OrigLoop);
2623   DFS.perform(LI);
2624
2625   // Vectorize all of the blocks in the original loop.
2626   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2627        be = DFS.endRPO(); bb != be; ++bb)
2628     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2629
2630   // At this point every instruction in the original loop is widened to
2631   // a vector form. We are almost done. Now, we need to fix the PHI nodes
2632   // that we vectorized. The PHI nodes are currently empty because we did
2633   // not want to introduce cycles. Notice that the remaining PHI nodes
2634   // that we need to fix are reduction variables.
2635
2636   // Create the 'reduced' values for each of the induction vars.
2637   // The reduced values are the vector values that we scalarize and combine
2638   // after the loop is finished.
2639   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2640        it != e; ++it) {
2641     PHINode *RdxPhi = *it;
2642     assert(RdxPhi && "Unable to recover vectorized PHI");
2643
2644     // Find the reduction variable descriptor.
2645     assert(Legal->getReductionVars()->count(RdxPhi) &&
2646            "Unable to find the reduction variable");
2647     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2648     (*Legal->getReductionVars())[RdxPhi];
2649
2650     setDebugLocFromInst(Builder, RdxDesc.StartValue);
2651
2652     // We need to generate a reduction vector from the incoming scalar.
2653     // To do so, we need to generate the 'identity' vector and override
2654     // one of the elements with the incoming scalar reduction. We need
2655     // to do it in the vector-loop preheader.
2656     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2657
2658     // This is the vector-clone of the value that leaves the loop.
2659     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2660     Type *VecTy = VectorExit[0]->getType();
2661
2662     // Find the reduction identity variable. Zero for addition, or, xor,
2663     // one for multiplication, -1 for And.
2664     Value *Identity;
2665     Value *VectorStart;
2666     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2667         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2668       // MinMax reduction have the start value as their identify.
2669       if (VF == 1) {
2670         VectorStart = Identity = RdxDesc.StartValue;
2671       } else {
2672         VectorStart = Identity = Builder.CreateVectorSplat(VF,
2673                                                            RdxDesc.StartValue,
2674                                                            "minmax.ident");
2675       }
2676     } else {
2677       // Handle other reduction kinds:
2678       Constant *Iden =
2679       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2680                                                       VecTy->getScalarType());
2681       if (VF == 1) {
2682         Identity = Iden;
2683         // This vector is the Identity vector where the first element is the
2684         // incoming scalar reduction.
2685         VectorStart = RdxDesc.StartValue;
2686       } else {
2687         Identity = ConstantVector::getSplat(VF, Iden);
2688
2689         // This vector is the Identity vector where the first element is the
2690         // incoming scalar reduction.
2691         VectorStart = Builder.CreateInsertElement(Identity,
2692                                                   RdxDesc.StartValue, Zero);
2693       }
2694     }
2695
2696     // Fix the vector-loop phi.
2697
2698     // Reductions do not have to start at zero. They can start with
2699     // any loop invariant values.
2700     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2701     BasicBlock *Latch = OrigLoop->getLoopLatch();
2702     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2703     VectorParts &Val = getVectorValue(LoopVal);
2704     for (unsigned part = 0; part < UF; ++part) {
2705       // Make sure to add the reduction stat value only to the
2706       // first unroll part.
2707       Value *StartVal = (part == 0) ? VectorStart : Identity;
2708       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
2709                                                   LoopVectorPreHeader);
2710       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2711                                                   LoopVectorBody.back());
2712     }
2713
2714     // Before each round, move the insertion point right between
2715     // the PHIs and the values we are going to write.
2716     // This allows us to write both PHINodes and the extractelement
2717     // instructions.
2718     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2719
2720     VectorParts RdxParts;
2721     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2722     for (unsigned part = 0; part < UF; ++part) {
2723       // This PHINode contains the vectorized reduction variable, or
2724       // the initial value vector, if we bypass the vector loop.
2725       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2726       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2727       Value *StartVal = (part == 0) ? VectorStart : Identity;
2728       for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2729         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2730       NewPhi->addIncoming(RdxExitVal[part],
2731                           LoopVectorBody.back());
2732       RdxParts.push_back(NewPhi);
2733     }
2734
2735     // Reduce all of the unrolled parts into a single vector.
2736     Value *ReducedPartRdx = RdxParts[0];
2737     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2738     setDebugLocFromInst(Builder, ReducedPartRdx);
2739     for (unsigned part = 1; part < UF; ++part) {
2740       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2741         // Floating point operations had to be 'fast' to enable the reduction.
2742         ReducedPartRdx = addFastMathFlag(
2743             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2744                                 ReducedPartRdx, "bin.rdx"));
2745       else
2746         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2747                                         ReducedPartRdx, RdxParts[part]);
2748     }
2749
2750     if (VF > 1) {
2751       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2752       // and vector ops, reducing the set of values being computed by half each
2753       // round.
2754       assert(isPowerOf2_32(VF) &&
2755              "Reduction emission only supported for pow2 vectors!");
2756       Value *TmpVec = ReducedPartRdx;
2757       SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2758       for (unsigned i = VF; i != 1; i >>= 1) {
2759         // Move the upper half of the vector to the lower half.
2760         for (unsigned j = 0; j != i/2; ++j)
2761           ShuffleMask[j] = Builder.getInt32(i/2 + j);
2762
2763         // Fill the rest of the mask with undef.
2764         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2765                   UndefValue::get(Builder.getInt32Ty()));
2766
2767         Value *Shuf =
2768         Builder.CreateShuffleVector(TmpVec,
2769                                     UndefValue::get(TmpVec->getType()),
2770                                     ConstantVector::get(ShuffleMask),
2771                                     "rdx.shuf");
2772
2773         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2774           // Floating point operations had to be 'fast' to enable the reduction.
2775           TmpVec = addFastMathFlag(Builder.CreateBinOp(
2776               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2777         else
2778           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2779       }
2780
2781       // The result is in the first element of the vector.
2782       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2783                                                     Builder.getInt32(0));
2784     }
2785
2786     // Create a phi node that merges control-flow from the backedge-taken check
2787     // block and the middle block.
2788     PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2789                                           LoopScalarPreHeader->getTerminator());
2790     BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2791     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2792
2793     // Now, we need to fix the users of the reduction variable
2794     // inside and outside of the scalar remainder loop.
2795     // We know that the loop is in LCSSA form. We need to update the
2796     // PHI nodes in the exit blocks.
2797     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2798          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2799       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2800       if (!LCSSAPhi) break;
2801
2802       // All PHINodes need to have a single entry edge, or two if
2803       // we already fixed them.
2804       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2805
2806       // We found our reduction value exit-PHI. Update it with the
2807       // incoming bypass edge.
2808       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2809         // Add an edge coming from the bypass.
2810         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2811         break;
2812       }
2813     }// end of the LCSSA phi scan.
2814
2815     // Fix the scalar loop reduction variable with the incoming reduction sum
2816     // from the vector body and from the backedge value.
2817     int IncomingEdgeBlockIdx =
2818     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2819     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2820     // Pick the other block.
2821     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2822     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2823     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2824   }// end of for each redux variable.
2825
2826   fixLCSSAPHIs();
2827
2828   // Remove redundant induction instructions.
2829   cse(LoopVectorBody);
2830 }
2831
2832 void InnerLoopVectorizer::fixLCSSAPHIs() {
2833   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2834        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2835     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2836     if (!LCSSAPhi) break;
2837     if (LCSSAPhi->getNumIncomingValues() == 1)
2838       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2839                             LoopMiddleBlock);
2840   }
2841 }
2842
2843 InnerLoopVectorizer::VectorParts
2844 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2845   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2846          "Invalid edge");
2847
2848   // Look for cached value.
2849   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2850   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2851   if (ECEntryIt != MaskCache.end())
2852     return ECEntryIt->second;
2853
2854   VectorParts SrcMask = createBlockInMask(Src);
2855
2856   // The terminator has to be a branch inst!
2857   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2858   assert(BI && "Unexpected terminator found");
2859
2860   if (BI->isConditional()) {
2861     VectorParts EdgeMask = getVectorValue(BI->getCondition());
2862
2863     if (BI->getSuccessor(0) != Dst)
2864       for (unsigned part = 0; part < UF; ++part)
2865         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2866
2867     for (unsigned part = 0; part < UF; ++part)
2868       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2869
2870     MaskCache[Edge] = EdgeMask;
2871     return EdgeMask;
2872   }
2873
2874   MaskCache[Edge] = SrcMask;
2875   return SrcMask;
2876 }
2877
2878 InnerLoopVectorizer::VectorParts
2879 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2880   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2881
2882   // Loop incoming mask is all-one.
2883   if (OrigLoop->getHeader() == BB) {
2884     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2885     return getVectorValue(C);
2886   }
2887
2888   // This is the block mask. We OR all incoming edges, and with zero.
2889   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2890   VectorParts BlockMask = getVectorValue(Zero);
2891
2892   // For each pred:
2893   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2894     VectorParts EM = createEdgeMask(*it, BB);
2895     for (unsigned part = 0; part < UF; ++part)
2896       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2897   }
2898
2899   return BlockMask;
2900 }
2901
2902 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2903                                               InnerLoopVectorizer::VectorParts &Entry,
2904                                               unsigned UF, unsigned VF, PhiVector *PV) {
2905   PHINode* P = cast<PHINode>(PN);
2906   // Handle reduction variables:
2907   if (Legal->getReductionVars()->count(P)) {
2908     for (unsigned part = 0; part < UF; ++part) {
2909       // This is phase one of vectorizing PHIs.
2910       Type *VecTy = (VF == 1) ? PN->getType() :
2911       VectorType::get(PN->getType(), VF);
2912       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2913                                     LoopVectorBody.back()-> getFirstInsertionPt());
2914     }
2915     PV->push_back(P);
2916     return;
2917   }
2918
2919   setDebugLocFromInst(Builder, P);
2920   // Check for PHI nodes that are lowered to vector selects.
2921   if (P->getParent() != OrigLoop->getHeader()) {
2922     // We know that all PHIs in non-header blocks are converted into
2923     // selects, so we don't have to worry about the insertion order and we
2924     // can just use the builder.
2925     // At this point we generate the predication tree. There may be
2926     // duplications since this is a simple recursive scan, but future
2927     // optimizations will clean it up.
2928
2929     unsigned NumIncoming = P->getNumIncomingValues();
2930
2931     // Generate a sequence of selects of the form:
2932     // SELECT(Mask3, In3,
2933     //      SELECT(Mask2, In2,
2934     //                   ( ...)))
2935     for (unsigned In = 0; In < NumIncoming; In++) {
2936       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2937                                         P->getParent());
2938       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2939
2940       for (unsigned part = 0; part < UF; ++part) {
2941         // We might have single edge PHIs (blocks) - use an identity
2942         // 'select' for the first PHI operand.
2943         if (In == 0)
2944           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2945                                              In0[part]);
2946         else
2947           // Select between the current value and the previous incoming edge
2948           // based on the incoming mask.
2949           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2950                                              Entry[part], "predphi");
2951       }
2952     }
2953     return;
2954   }
2955
2956   // This PHINode must be an induction variable.
2957   // Make sure that we know about it.
2958   assert(Legal->getInductionVars()->count(P) &&
2959          "Not an induction variable");
2960
2961   LoopVectorizationLegality::InductionInfo II =
2962   Legal->getInductionVars()->lookup(P);
2963
2964   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2965   // which can be found from the original scalar operations.
2966   switch (II.IK) {
2967     case LoopVectorizationLegality::IK_NoInduction:
2968       llvm_unreachable("Unknown induction");
2969     case LoopVectorizationLegality::IK_IntInduction: {
2970       assert(P->getType() == II.StartValue->getType() && "Types must match");
2971       Type *PhiTy = P->getType();
2972       Value *Broadcasted;
2973       if (P == OldInduction) {
2974         // Handle the canonical induction variable. We might have had to
2975         // extend the type.
2976         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2977       } else {
2978         // Handle other induction variables that are now based on the
2979         // canonical one.
2980         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2981                                                  "normalized.idx");
2982         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2983         Broadcasted = II.transform(Builder, NormalizedIdx);
2984         Broadcasted->setName("offset.idx");
2985       }
2986       Broadcasted = getBroadcastInstrs(Broadcasted);
2987       // After broadcasting the induction variable we need to make the vector
2988       // consecutive by adding 0, 1, 2, etc.
2989       for (unsigned part = 0; part < UF; ++part)
2990         Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
2991       return;
2992     }
2993     case LoopVectorizationLegality::IK_PtrInduction:
2994       // Handle the pointer induction variable case.
2995       assert(P->getType()->isPointerTy() && "Unexpected type.");
2996       // This is the normalized GEP that starts counting at zero.
2997       Value *NormalizedIdx =
2998           Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
2999       // This is the vector of results. Notice that we don't generate
3000       // vector geps because scalar geps result in better code.
3001       for (unsigned part = 0; part < UF; ++part) {
3002         if (VF == 1) {
3003           int EltIndex = part;
3004           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3005           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3006           Value *SclrGep = II.transform(Builder, GlobalIdx);
3007           SclrGep->setName("next.gep");
3008           Entry[part] = SclrGep;
3009           continue;
3010         }
3011
3012         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3013         for (unsigned int i = 0; i < VF; ++i) {
3014           int EltIndex = i + part * VF;
3015           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3016           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3017           Value *SclrGep = II.transform(Builder, GlobalIdx);
3018           SclrGep->setName("next.gep");
3019           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3020                                                Builder.getInt32(i),
3021                                                "insert.gep");
3022         }
3023         Entry[part] = VecVal;
3024       }
3025       return;
3026   }
3027 }
3028
3029 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3030   // For each instruction in the old loop.
3031   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3032     VectorParts &Entry = WidenMap.get(it);
3033     switch (it->getOpcode()) {
3034     case Instruction::Br:
3035       // Nothing to do for PHIs and BR, since we already took care of the
3036       // loop control flow instructions.
3037       continue;
3038     case Instruction::PHI: {
3039       // Vectorize PHINodes.
3040       widenPHIInstruction(it, Entry, UF, VF, PV);
3041       continue;
3042     }// End of PHI.
3043
3044     case Instruction::Add:
3045     case Instruction::FAdd:
3046     case Instruction::Sub:
3047     case Instruction::FSub:
3048     case Instruction::Mul:
3049     case Instruction::FMul:
3050     case Instruction::UDiv:
3051     case Instruction::SDiv:
3052     case Instruction::FDiv:
3053     case Instruction::URem:
3054     case Instruction::SRem:
3055     case Instruction::FRem:
3056     case Instruction::Shl:
3057     case Instruction::LShr:
3058     case Instruction::AShr:
3059     case Instruction::And:
3060     case Instruction::Or:
3061     case Instruction::Xor: {
3062       // Just widen binops.
3063       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3064       setDebugLocFromInst(Builder, BinOp);
3065       VectorParts &A = getVectorValue(it->getOperand(0));
3066       VectorParts &B = getVectorValue(it->getOperand(1));
3067
3068       // Use this vector value for all users of the original instruction.
3069       for (unsigned Part = 0; Part < UF; ++Part) {
3070         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3071
3072         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3073           VecOp->copyIRFlags(BinOp);
3074
3075         Entry[Part] = V;
3076       }
3077
3078       propagateMetadata(Entry, it);
3079       break;
3080     }
3081     case Instruction::Select: {
3082       // Widen selects.
3083       // If the selector is loop invariant we can create a select
3084       // instruction with a scalar condition. Otherwise, use vector-select.
3085       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3086                                                OrigLoop);
3087       setDebugLocFromInst(Builder, it);
3088
3089       // The condition can be loop invariant  but still defined inside the
3090       // loop. This means that we can't just use the original 'cond' value.
3091       // We have to take the 'vectorized' value and pick the first lane.
3092       // Instcombine will make this a no-op.
3093       VectorParts &Cond = getVectorValue(it->getOperand(0));
3094       VectorParts &Op0  = getVectorValue(it->getOperand(1));
3095       VectorParts &Op1  = getVectorValue(it->getOperand(2));
3096
3097       Value *ScalarCond = (VF == 1) ? Cond[0] :
3098         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3099
3100       for (unsigned Part = 0; Part < UF; ++Part) {
3101         Entry[Part] = Builder.CreateSelect(
3102           InvariantCond ? ScalarCond : Cond[Part],
3103           Op0[Part],
3104           Op1[Part]);
3105       }
3106
3107       propagateMetadata(Entry, it);
3108       break;
3109     }
3110
3111     case Instruction::ICmp:
3112     case Instruction::FCmp: {
3113       // Widen compares. Generate vector compares.
3114       bool FCmp = (it->getOpcode() == Instruction::FCmp);
3115       CmpInst *Cmp = dyn_cast<CmpInst>(it);
3116       setDebugLocFromInst(Builder, it);
3117       VectorParts &A = getVectorValue(it->getOperand(0));
3118       VectorParts &B = getVectorValue(it->getOperand(1));
3119       for (unsigned Part = 0; Part < UF; ++Part) {
3120         Value *C = nullptr;
3121         if (FCmp)
3122           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3123         else
3124           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3125         Entry[Part] = C;
3126       }
3127
3128       propagateMetadata(Entry, it);
3129       break;
3130     }
3131
3132     case Instruction::Store:
3133     case Instruction::Load:
3134       vectorizeMemoryInstruction(it);
3135         break;
3136     case Instruction::ZExt:
3137     case Instruction::SExt:
3138     case Instruction::FPToUI:
3139     case Instruction::FPToSI:
3140     case Instruction::FPExt:
3141     case Instruction::PtrToInt:
3142     case Instruction::IntToPtr:
3143     case Instruction::SIToFP:
3144     case Instruction::UIToFP:
3145     case Instruction::Trunc:
3146     case Instruction::FPTrunc:
3147     case Instruction::BitCast: {
3148       CastInst *CI = dyn_cast<CastInst>(it);
3149       setDebugLocFromInst(Builder, it);
3150       /// Optimize the special case where the source is the induction
3151       /// variable. Notice that we can only optimize the 'trunc' case
3152       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3153       /// c. other casts depend on pointer size.
3154       if (CI->getOperand(0) == OldInduction &&
3155           it->getOpcode() == Instruction::Trunc) {
3156         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3157                                                CI->getType());
3158         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3159         LoopVectorizationLegality::InductionInfo II =
3160             Legal->getInductionVars()->lookup(OldInduction);
3161         Constant *Step =
3162             ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3163         for (unsigned Part = 0; Part < UF; ++Part)
3164           Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3165         propagateMetadata(Entry, it);
3166         break;
3167       }
3168       /// Vectorize casts.
3169       Type *DestTy = (VF == 1) ? CI->getType() :
3170                                  VectorType::get(CI->getType(), VF);
3171
3172       VectorParts &A = getVectorValue(it->getOperand(0));
3173       for (unsigned Part = 0; Part < UF; ++Part)
3174         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3175       propagateMetadata(Entry, it);
3176       break;
3177     }
3178
3179     case Instruction::Call: {
3180       // Ignore dbg intrinsics.
3181       if (isa<DbgInfoIntrinsic>(it))
3182         break;
3183       setDebugLocFromInst(Builder, it);
3184
3185       Module *M = BB->getParent()->getParent();
3186       CallInst *CI = cast<CallInst>(it);
3187       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3188       assert(ID && "Not an intrinsic call!");
3189       switch (ID) {
3190       case Intrinsic::assume:
3191       case Intrinsic::lifetime_end:
3192       case Intrinsic::lifetime_start:
3193         scalarizeInstruction(it);
3194         break;
3195       default:
3196         bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3197         for (unsigned Part = 0; Part < UF; ++Part) {
3198           SmallVector<Value *, 4> Args;
3199           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3200             if (HasScalarOpd && i == 1) {
3201               Args.push_back(CI->getArgOperand(i));
3202               continue;
3203             }
3204             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3205             Args.push_back(Arg[Part]);
3206           }
3207           Type *Tys[] = {CI->getType()};
3208           if (VF > 1)
3209             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3210
3211           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3212           Entry[Part] = Builder.CreateCall(F, Args);
3213         }
3214
3215         propagateMetadata(Entry, it);
3216         break;
3217       }
3218       break;
3219     }
3220
3221     default:
3222       // All other instructions are unsupported. Scalarize them.
3223       scalarizeInstruction(it);
3224       break;
3225     }// end of switch.
3226   }// end of for_each instr.
3227 }
3228
3229 void InnerLoopVectorizer::updateAnalysis() {
3230   // Forget the original basic block.
3231   SE->forgetLoop(OrigLoop);
3232
3233   // Update the dominator tree information.
3234   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3235          "Entry does not dominate exit.");
3236
3237   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3238     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3239   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3240
3241   // Due to if predication of stores we might create a sequence of "if(pred)
3242   // a[i] = ...;  " blocks.
3243   for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3244     if (i == 0)
3245       DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3246     else if (isPredicatedBlock(i)) {
3247       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3248     } else {
3249       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3250     }
3251   }
3252
3253   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3254   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3255   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3256   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3257
3258   DEBUG(DT->verifyDomTree());
3259 }
3260
3261 /// \brief Check whether it is safe to if-convert this phi node.
3262 ///
3263 /// Phi nodes with constant expressions that can trap are not safe to if
3264 /// convert.
3265 static bool canIfConvertPHINodes(BasicBlock *BB) {
3266   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3267     PHINode *Phi = dyn_cast<PHINode>(I);
3268     if (!Phi)
3269       return true;
3270     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3271       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3272         if (C->canTrap())
3273           return false;
3274   }
3275   return true;
3276 }
3277
3278 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3279   if (!EnableIfConversion) {
3280     emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3281     return false;
3282   }
3283
3284   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3285
3286   // A list of pointers that we can safely read and write to.
3287   SmallPtrSet<Value *, 8> SafePointes;
3288
3289   // Collect safe addresses.
3290   for (Loop::block_iterator BI = TheLoop->block_begin(),
3291          BE = TheLoop->block_end(); BI != BE; ++BI) {
3292     BasicBlock *BB = *BI;
3293
3294     if (blockNeedsPredication(BB))
3295       continue;
3296
3297     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3298       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3299         SafePointes.insert(LI->getPointerOperand());
3300       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3301         SafePointes.insert(SI->getPointerOperand());
3302     }
3303   }
3304
3305   // Collect the blocks that need predication.
3306   BasicBlock *Header = TheLoop->getHeader();
3307   for (Loop::block_iterator BI = TheLoop->block_begin(),
3308          BE = TheLoop->block_end(); BI != BE; ++BI) {
3309     BasicBlock *BB = *BI;
3310
3311     // We don't support switch statements inside loops.
3312     if (!isa<BranchInst>(BB->getTerminator())) {
3313       emitAnalysis(VectorizationReport(BB->getTerminator())
3314                    << "loop contains a switch statement");
3315       return false;
3316     }
3317
3318     // We must be able to predicate all blocks that need to be predicated.
3319     if (blockNeedsPredication(BB)) {
3320       if (!blockCanBePredicated(BB, SafePointes)) {
3321         emitAnalysis(VectorizationReport(BB->getTerminator())
3322                      << "control flow cannot be substituted for a select");
3323         return false;
3324       }
3325     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3326       emitAnalysis(VectorizationReport(BB->getTerminator())
3327                    << "control flow cannot be substituted for a select");
3328       return false;
3329     }
3330   }
3331
3332   // We can if-convert this loop.
3333   return true;
3334 }
3335
3336 bool LoopVectorizationLegality::canVectorize() {
3337   // We must have a loop in canonical form. Loops with indirectbr in them cannot
3338   // be canonicalized.
3339   if (!TheLoop->getLoopPreheader()) {
3340     emitAnalysis(
3341         VectorizationReport() <<
3342         "loop control flow is not understood by vectorizer");
3343     return false;
3344   }
3345
3346   // We can only vectorize innermost loops.
3347   if (!TheLoop->getSubLoopsVector().empty()) {
3348     emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3349     return false;
3350   }
3351
3352   // We must have a single backedge.
3353   if (TheLoop->getNumBackEdges() != 1) {
3354     emitAnalysis(
3355         VectorizationReport() <<
3356         "loop control flow is not understood by vectorizer");
3357     return false;
3358   }
3359
3360   // We must have a single exiting block.
3361   if (!TheLoop->getExitingBlock()) {
3362     emitAnalysis(
3363         VectorizationReport() <<
3364         "loop control flow is not understood by vectorizer");
3365     return false;
3366   }
3367
3368   // We only handle bottom-tested loops, i.e. loop in which the condition is
3369   // checked at the end of each iteration. With that we can assume that all
3370   // instructions in the loop are executed the same number of times.
3371   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3372     emitAnalysis(
3373         VectorizationReport() <<
3374         "loop control flow is not understood by vectorizer");
3375     return false;
3376   }
3377
3378   // We need to have a loop header.
3379   DEBUG(dbgs() << "LV: Found a loop: " <<
3380         TheLoop->getHeader()->getName() << '\n');
3381
3382   // Check if we can if-convert non-single-bb loops.
3383   unsigned NumBlocks = TheLoop->getNumBlocks();
3384   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3385     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3386     return false;
3387   }
3388
3389   // ScalarEvolution needs to be able to find the exit count.
3390   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3391   if (ExitCount == SE->getCouldNotCompute()) {
3392     emitAnalysis(VectorizationReport() <<
3393                  "could not determine number of loop iterations");
3394     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3395     return false;
3396   }
3397
3398   // Check if we can vectorize the instructions and CFG in this loop.
3399   if (!canVectorizeInstrs()) {
3400     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3401     return false;
3402   }
3403
3404   // Go over each instruction and look at memory deps.
3405   if (!canVectorizeMemory()) {
3406     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3407     return false;
3408   }
3409
3410   // Collect all of the variables that remain uniform after vectorization.
3411   collectLoopUniforms();
3412
3413   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3414         (LAI->getRuntimePointerCheck()->Need ? " (with a runtime bound check)" :
3415          "")
3416         <<"!\n");
3417
3418   // Okay! We can vectorize. At this point we don't have any other mem analysis
3419   // which may limit our maximum vectorization factor, so just return true with
3420   // no restrictions.
3421   return true;
3422 }
3423
3424 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3425   if (Ty->isPointerTy())
3426     return DL.getIntPtrType(Ty);
3427
3428   // It is possible that char's or short's overflow when we ask for the loop's
3429   // trip count, work around this by changing the type size.
3430   if (Ty->getScalarSizeInBits() < 32)
3431     return Type::getInt32Ty(Ty->getContext());
3432
3433   return Ty;
3434 }
3435
3436 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3437   Ty0 = convertPointerToIntegerType(DL, Ty0);
3438   Ty1 = convertPointerToIntegerType(DL, Ty1);
3439   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3440     return Ty0;
3441   return Ty1;
3442 }
3443
3444 /// \brief Check that the instruction has outside loop users and is not an
3445 /// identified reduction variable.
3446 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3447                                SmallPtrSetImpl<Value *> &Reductions) {
3448   // Reduction instructions are allowed to have exit users. All other
3449   // instructions must not have external users.
3450   if (!Reductions.count(Inst))
3451     //Check that all of the users of the loop are inside the BB.
3452     for (User *U : Inst->users()) {
3453       Instruction *UI = cast<Instruction>(U);
3454       // This user may be a reduction exit value.
3455       if (!TheLoop->contains(UI)) {
3456         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3457         return true;
3458       }
3459     }
3460   return false;
3461 }
3462
3463 bool LoopVectorizationLegality::canVectorizeInstrs() {
3464   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3465   BasicBlock *Header = TheLoop->getHeader();
3466
3467   // Look for the attribute signaling the absence of NaNs.
3468   Function &F = *Header->getParent();
3469   if (F.hasFnAttribute("no-nans-fp-math"))
3470     HasFunNoNaNAttr =
3471         F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
3472
3473   // For each block in the loop.
3474   for (Loop::block_iterator bb = TheLoop->block_begin(),
3475        be = TheLoop->block_end(); bb != be; ++bb) {
3476
3477     // Scan the instructions in the block and look for hazards.
3478     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3479          ++it) {
3480
3481       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3482         Type *PhiTy = Phi->getType();
3483         // Check that this PHI type is allowed.
3484         if (!PhiTy->isIntegerTy() &&
3485             !PhiTy->isFloatingPointTy() &&
3486             !PhiTy->isPointerTy()) {
3487           emitAnalysis(VectorizationReport(it)
3488                        << "loop control flow is not understood by vectorizer");
3489           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3490           return false;
3491         }
3492
3493         // If this PHINode is not in the header block, then we know that we
3494         // can convert it to select during if-conversion. No need to check if
3495         // the PHIs in this block are induction or reduction variables.
3496         if (*bb != Header) {
3497           // Check that this instruction has no outside users or is an
3498           // identified reduction value with an outside user.
3499           if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3500             continue;
3501           emitAnalysis(VectorizationReport(it) <<
3502                        "value could not be identified as "
3503                        "an induction or reduction variable");
3504           return false;
3505         }
3506
3507         // We only allow if-converted PHIs with exactly two incoming values.
3508         if (Phi->getNumIncomingValues() != 2) {
3509           emitAnalysis(VectorizationReport(it)
3510                        << "control flow not understood by vectorizer");
3511           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3512           return false;
3513         }
3514
3515         // This is the value coming from the preheader.
3516         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3517         ConstantInt *StepValue = nullptr;
3518         // Check if this is an induction variable.
3519         InductionKind IK = isInductionVariable(Phi, StepValue);
3520
3521         if (IK_NoInduction != IK) {
3522           // Get the widest type.
3523           if (!WidestIndTy)
3524             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3525           else
3526             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3527
3528           // Int inductions are special because we only allow one IV.
3529           if (IK == IK_IntInduction && StepValue->isOne()) {
3530             // Use the phi node with the widest type as induction. Use the last
3531             // one if there are multiple (no good reason for doing this other
3532             // than it is expedient).
3533             if (!Induction || PhiTy == WidestIndTy)
3534               Induction = Phi;
3535           }
3536
3537           DEBUG(dbgs() << "LV: Found an induction variable.\n");
3538           Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
3539
3540           // Until we explicitly handle the case of an induction variable with
3541           // an outside loop user we have to give up vectorizing this loop.
3542           if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3543             emitAnalysis(VectorizationReport(it) <<
3544                          "use of induction value outside of the "
3545                          "loop is not handled by vectorizer");
3546             return false;
3547           }
3548
3549           continue;
3550         }
3551
3552         if (AddReductionVar(Phi, RK_IntegerAdd)) {
3553           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3554           continue;
3555         }
3556         if (AddReductionVar(Phi, RK_IntegerMult)) {
3557           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3558           continue;
3559         }
3560         if (AddReductionVar(Phi, RK_IntegerOr)) {
3561           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3562           continue;
3563         }
3564         if (AddReductionVar(Phi, RK_IntegerAnd)) {
3565           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3566           continue;
3567         }
3568         if (AddReductionVar(Phi, RK_IntegerXor)) {
3569           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3570           continue;
3571         }
3572         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3573           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3574           continue;
3575         }
3576         if (AddReductionVar(Phi, RK_FloatMult)) {
3577           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3578           continue;
3579         }
3580         if (AddReductionVar(Phi, RK_FloatAdd)) {
3581           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3582           continue;
3583         }
3584         if (AddReductionVar(Phi, RK_FloatMinMax)) {
3585           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3586                 "\n");
3587           continue;
3588         }
3589
3590         emitAnalysis(VectorizationReport(it) <<
3591                      "value that could not be identified as "
3592                      "reduction is used outside the loop");
3593         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3594         return false;
3595       }// end of PHI handling
3596
3597       // We still don't handle functions. However, we can ignore dbg intrinsic
3598       // calls and we do handle certain intrinsic and libm functions.
3599       CallInst *CI = dyn_cast<CallInst>(it);
3600       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3601         emitAnalysis(VectorizationReport(it) <<
3602                      "call instruction cannot be vectorized");
3603         DEBUG(dbgs() << "LV: Found a call site.\n");
3604         return false;
3605       }
3606
3607       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3608       // second argument is the same (i.e. loop invariant)
3609       if (CI &&
3610           hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3611         if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3612           emitAnalysis(VectorizationReport(it)
3613                        << "intrinsic instruction cannot be vectorized");
3614           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3615           return false;
3616         }
3617       }
3618
3619       // Check that the instruction return type is vectorizable.
3620       // Also, we can't vectorize extractelement instructions.
3621       if ((!VectorType::isValidElementType(it->getType()) &&
3622            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3623         emitAnalysis(VectorizationReport(it)
3624                      << "instruction return type cannot be vectorized");
3625         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3626         return false;
3627       }
3628
3629       // Check that the stored type is vectorizable.
3630       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3631         Type *T = ST->getValueOperand()->getType();
3632         if (!VectorType::isValidElementType(T)) {
3633           emitAnalysis(VectorizationReport(ST) <<
3634                        "store instruction cannot be vectorized");
3635           return false;
3636         }
3637         if (EnableMemAccessVersioning)
3638           collectStridedAccess(ST);
3639       }
3640
3641       if (EnableMemAccessVersioning)
3642         if (LoadInst *LI = dyn_cast<LoadInst>(it))
3643           collectStridedAccess(LI);
3644
3645       // Reduction instructions are allowed to have exit users.
3646       // All other instructions must not have external users.
3647       if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3648         emitAnalysis(VectorizationReport(it) <<
3649                      "value cannot be used outside the loop");
3650         return false;
3651       }
3652
3653     } // next instr.
3654
3655   }
3656
3657   if (!Induction) {
3658     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3659     if (Inductions.empty()) {
3660       emitAnalysis(VectorizationReport()
3661                    << "loop induction variable could not be identified");
3662       return false;
3663     }
3664   }
3665
3666   return true;
3667 }
3668
3669 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3670 /// return the induction operand of the gep pointer.
3671 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3672                                  const DataLayout *DL, Loop *Lp) {
3673   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3674   if (!GEP)
3675     return Ptr;
3676
3677   unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3678
3679   // Check that all of the gep indices are uniform except for our induction
3680   // operand.
3681   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3682     if (i != InductionOperand &&
3683         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3684       return Ptr;
3685   return GEP->getOperand(InductionOperand);
3686 }
3687
3688 ///\brief Look for a cast use of the passed value.
3689 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3690   Value *UniqueCast = nullptr;
3691   for (User *U : Ptr->users()) {
3692     CastInst *CI = dyn_cast<CastInst>(U);
3693     if (CI && CI->getType() == Ty) {
3694       if (!UniqueCast)
3695         UniqueCast = CI;
3696       else
3697         return nullptr;
3698     }
3699   }
3700   return UniqueCast;
3701 }
3702
3703 ///\brief Get the stride of a pointer access in a loop.
3704 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3705 /// pointer to the Value, or null otherwise.
3706 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3707                                    const DataLayout *DL, Loop *Lp) {
3708   const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3709   if (!PtrTy || PtrTy->isAggregateType())
3710     return nullptr;
3711
3712   // Try to remove a gep instruction to make the pointer (actually index at this
3713   // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3714   // pointer, otherwise, we are analyzing the index.
3715   Value *OrigPtr = Ptr;
3716
3717   // The size of the pointer access.
3718   int64_t PtrAccessSize = 1;
3719
3720   Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3721   const SCEV *V = SE->getSCEV(Ptr);
3722
3723   if (Ptr != OrigPtr)
3724     // Strip off casts.
3725     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3726       V = C->getOperand();
3727
3728   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3729   if (!S)
3730     return nullptr;
3731
3732   V = S->getStepRecurrence(*SE);
3733   if (!V)
3734     return nullptr;
3735
3736   // Strip off the size of access multiplication if we are still analyzing the
3737   // pointer.
3738   if (OrigPtr == Ptr) {
3739     DL->getTypeAllocSize(PtrTy->getElementType());
3740     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3741       if (M->getOperand(0)->getSCEVType() != scConstant)
3742         return nullptr;
3743
3744       const APInt &APStepVal =
3745           cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3746
3747       // Huge step value - give up.
3748       if (APStepVal.getBitWidth() > 64)
3749         return nullptr;
3750
3751       int64_t StepVal = APStepVal.getSExtValue();
3752       if (PtrAccessSize != StepVal)
3753         return nullptr;
3754       V = M->getOperand(1);
3755     }
3756   }
3757
3758   // Strip off casts.
3759   Type *StripedOffRecurrenceCast = nullptr;
3760   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3761     StripedOffRecurrenceCast = C->getType();
3762     V = C->getOperand();
3763   }
3764
3765   // Look for the loop invariant symbolic value.
3766   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3767   if (!U)
3768     return nullptr;
3769
3770   Value *Stride = U->getValue();
3771   if (!Lp->isLoopInvariant(Stride))
3772     return nullptr;
3773
3774   // If we have stripped off the recurrence cast we have to make sure that we
3775   // return the value that is used in this loop so that we can replace it later.
3776   if (StripedOffRecurrenceCast)
3777     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3778
3779   return Stride;
3780 }
3781
3782 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
3783   Value *Ptr = nullptr;
3784   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3785     Ptr = LI->getPointerOperand();
3786   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3787     Ptr = SI->getPointerOperand();
3788   else
3789     return;
3790
3791   Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3792   if (!Stride)
3793     return;
3794
3795   DEBUG(dbgs() << "LV: Found a strided access that we can version");
3796   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3797   Strides[Ptr] = Stride;
3798   StrideSet.insert(Stride);
3799 }
3800
3801 void LoopVectorizationLegality::collectLoopUniforms() {
3802   // We now know that the loop is vectorizable!
3803   // Collect variables that will remain uniform after vectorization.
3804   std::vector<Value*> Worklist;
3805   BasicBlock *Latch = TheLoop->getLoopLatch();
3806
3807   // Start with the conditional branch and walk up the block.
3808   Worklist.push_back(Latch->getTerminator()->getOperand(0));
3809
3810   // Also add all consecutive pointer values; these values will be uniform
3811   // after vectorization (and subsequent cleanup) and, until revectorization is
3812   // supported, all dependencies must also be uniform.
3813   for (Loop::block_iterator B = TheLoop->block_begin(),
3814        BE = TheLoop->block_end(); B != BE; ++B)
3815     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3816          I != IE; ++I)
3817       if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3818         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3819
3820   while (!Worklist.empty()) {
3821     Instruction *I = dyn_cast<Instruction>(Worklist.back());
3822     Worklist.pop_back();
3823
3824     // Look at instructions inside this loop.
3825     // Stop when reaching PHI nodes.
3826     // TODO: we need to follow values all over the loop, not only in this block.
3827     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3828       continue;
3829
3830     // This is a known uniform.
3831     Uniforms.insert(I);
3832
3833     // Insert all operands.
3834     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3835   }
3836 }
3837
3838 bool LoopVectorizationLegality::canVectorizeMemory() {
3839   LAI = &LAA->getInfo(TheLoop, Strides);
3840   auto &OptionalReport = LAI->getReport();
3841   if (OptionalReport)
3842     emitAnalysis(VectorizationReport(*OptionalReport));
3843   return LAI->canVectorizeMemory();
3844 }
3845
3846 static bool hasMultipleUsesOf(Instruction *I,
3847                               SmallPtrSetImpl<Instruction *> &Insts) {
3848   unsigned NumUses = 0;
3849   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3850     if (Insts.count(dyn_cast<Instruction>(*Use)))
3851       ++NumUses;
3852     if (NumUses > 1)
3853       return true;
3854   }
3855
3856   return false;
3857 }
3858
3859 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
3860   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3861     if (!Set.count(dyn_cast<Instruction>(*Use)))
3862       return false;
3863   return true;
3864 }
3865
3866 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3867                                                 ReductionKind Kind) {
3868   if (Phi->getNumIncomingValues() != 2)
3869     return false;
3870
3871   // Reduction variables are only found in the loop header block.
3872   if (Phi->getParent() != TheLoop->getHeader())
3873     return false;
3874
3875   // Obtain the reduction start value from the value that comes from the loop
3876   // preheader.
3877   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3878
3879   // ExitInstruction is the single value which is used outside the loop.
3880   // We only allow for a single reduction value to be used outside the loop.
3881   // This includes users of the reduction, variables (which form a cycle
3882   // which ends in the phi node).
3883   Instruction *ExitInstruction = nullptr;
3884   // Indicates that we found a reduction operation in our scan.
3885   bool FoundReduxOp = false;
3886
3887   // We start with the PHI node and scan for all of the users of this
3888   // instruction. All users must be instructions that can be used as reduction
3889   // variables (such as ADD). We must have a single out-of-block user. The cycle
3890   // must include the original PHI.
3891   bool FoundStartPHI = false;
3892
3893   // To recognize min/max patterns formed by a icmp select sequence, we store
3894   // the number of instruction we saw from the recognized min/max pattern,
3895   //  to make sure we only see exactly the two instructions.
3896   unsigned NumCmpSelectPatternInst = 0;
3897   ReductionInstDesc ReduxDesc(false, nullptr);
3898
3899   SmallPtrSet<Instruction *, 8> VisitedInsts;
3900   SmallVector<Instruction *, 8> Worklist;
3901   Worklist.push_back(Phi);
3902   VisitedInsts.insert(Phi);
3903
3904   // A value in the reduction can be used:
3905   //  - By the reduction:
3906   //      - Reduction operation:
3907   //        - One use of reduction value (safe).
3908   //        - Multiple use of reduction value (not safe).
3909   //      - PHI:
3910   //        - All uses of the PHI must be the reduction (safe).
3911   //        - Otherwise, not safe.
3912   //  - By one instruction outside of the loop (safe).
3913   //  - By further instructions outside of the loop (not safe).
3914   //  - By an instruction that is not part of the reduction (not safe).
3915   //    This is either:
3916   //      * An instruction type other than PHI or the reduction operation.
3917   //      * A PHI in the header other than the initial PHI.
3918   while (!Worklist.empty()) {
3919     Instruction *Cur = Worklist.back();
3920     Worklist.pop_back();
3921
3922     // No Users.
3923     // If the instruction has no users then this is a broken chain and can't be
3924     // a reduction variable.
3925     if (Cur->use_empty())
3926       return false;
3927
3928     bool IsAPhi = isa<PHINode>(Cur);
3929
3930     // A header PHI use other than the original PHI.
3931     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3932       return false;
3933
3934     // Reductions of instructions such as Div, and Sub is only possible if the
3935     // LHS is the reduction variable.
3936     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3937         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3938         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3939       return false;
3940
3941     // Any reduction instruction must be of one of the allowed kinds.
3942     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3943     if (!ReduxDesc.IsReduction)
3944       return false;
3945
3946     // A reduction operation must only have one use of the reduction value.
3947     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3948         hasMultipleUsesOf(Cur, VisitedInsts))
3949       return false;
3950
3951     // All inputs to a PHI node must be a reduction value.
3952     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3953       return false;
3954
3955     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3956                                      isa<SelectInst>(Cur)))
3957       ++NumCmpSelectPatternInst;
3958     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3959                                    isa<SelectInst>(Cur)))
3960       ++NumCmpSelectPatternInst;
3961
3962     // Check  whether we found a reduction operator.
3963     FoundReduxOp |= !IsAPhi;
3964
3965     // Process users of current instruction. Push non-PHI nodes after PHI nodes
3966     // onto the stack. This way we are going to have seen all inputs to PHI
3967     // nodes once we get to them.
3968     SmallVector<Instruction *, 8> NonPHIs;
3969     SmallVector<Instruction *, 8> PHIs;
3970     for (User *U : Cur->users()) {
3971       Instruction *UI = cast<Instruction>(U);
3972
3973       // Check if we found the exit user.
3974       BasicBlock *Parent = UI->getParent();
3975       if (!TheLoop->contains(Parent)) {
3976         // Exit if you find multiple outside users or if the header phi node is
3977         // being used. In this case the user uses the value of the previous
3978         // iteration, in which case we would loose "VF-1" iterations of the
3979         // reduction operation if we vectorize.
3980         if (ExitInstruction != nullptr || Cur == Phi)
3981           return false;
3982
3983         // The instruction used by an outside user must be the last instruction
3984         // before we feed back to the reduction phi. Otherwise, we loose VF-1
3985         // operations on the value.
3986         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
3987          return false;
3988
3989         ExitInstruction = Cur;
3990         continue;
3991       }
3992
3993       // Process instructions only once (termination). Each reduction cycle
3994       // value must only be used once, except by phi nodes and min/max
3995       // reductions which are represented as a cmp followed by a select.
3996       ReductionInstDesc IgnoredVal(false, nullptr);
3997       if (VisitedInsts.insert(UI).second) {
3998         if (isa<PHINode>(UI))
3999           PHIs.push_back(UI);
4000         else
4001           NonPHIs.push_back(UI);
4002       } else if (!isa<PHINode>(UI) &&
4003                  ((!isa<FCmpInst>(UI) &&
4004                    !isa<ICmpInst>(UI) &&
4005                    !isa<SelectInst>(UI)) ||
4006                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4007         return false;
4008
4009       // Remember that we completed the cycle.
4010       if (UI == Phi)
4011         FoundStartPHI = true;
4012     }
4013     Worklist.append(PHIs.begin(), PHIs.end());
4014     Worklist.append(NonPHIs.begin(), NonPHIs.end());
4015   }
4016
4017   // This means we have seen one but not the other instruction of the
4018   // pattern or more than just a select and cmp.
4019   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4020       NumCmpSelectPatternInst != 2)
4021     return false;
4022
4023   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4024     return false;
4025
4026   // We found a reduction var if we have reached the original phi node and we
4027   // only have a single instruction with out-of-loop users.
4028
4029   // This instruction is allowed to have out-of-loop users.
4030   AllowedExit.insert(ExitInstruction);
4031
4032   // Save the description of this reduction variable.
4033   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4034                          ReduxDesc.MinMaxKind);
4035   Reductions[Phi] = RD;
4036   // We've ended the cycle. This is a reduction variable if we have an
4037   // outside user and it has a binary op.
4038
4039   return true;
4040 }
4041
4042 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4043 /// pattern corresponding to a min(X, Y) or max(X, Y).
4044 LoopVectorizationLegality::ReductionInstDesc
4045 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4046                                                     ReductionInstDesc &Prev) {
4047
4048   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4049          "Expect a select instruction");
4050   Instruction *Cmp = nullptr;
4051   SelectInst *Select = nullptr;
4052
4053   // We must handle the select(cmp()) as a single instruction. Advance to the
4054   // select.
4055   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4056     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4057       return ReductionInstDesc(false, I);
4058     return ReductionInstDesc(Select, Prev.MinMaxKind);
4059   }
4060
4061   // Only handle single use cases for now.
4062   if (!(Select = dyn_cast<SelectInst>(I)))
4063     return ReductionInstDesc(false, I);
4064   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4065       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4066     return ReductionInstDesc(false, I);
4067   if (!Cmp->hasOneUse())
4068     return ReductionInstDesc(false, I);
4069
4070   Value *CmpLeft;
4071   Value *CmpRight;
4072
4073   // Look for a min/max pattern.
4074   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4075     return ReductionInstDesc(Select, MRK_UIntMin);
4076   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4077     return ReductionInstDesc(Select, MRK_UIntMax);
4078   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4079     return ReductionInstDesc(Select, MRK_SIntMax);
4080   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4081     return ReductionInstDesc(Select, MRK_SIntMin);
4082   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4083     return ReductionInstDesc(Select, MRK_FloatMin);
4084   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4085     return ReductionInstDesc(Select, MRK_FloatMax);
4086   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4087     return ReductionInstDesc(Select, MRK_FloatMin);
4088   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4089     return ReductionInstDesc(Select, MRK_FloatMax);
4090
4091   return ReductionInstDesc(false, I);
4092 }
4093
4094 LoopVectorizationLegality::ReductionInstDesc
4095 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4096                                             ReductionKind Kind,
4097                                             ReductionInstDesc &Prev) {
4098   bool FP = I->getType()->isFloatingPointTy();
4099   bool FastMath = FP && I->hasUnsafeAlgebra();
4100   switch (I->getOpcode()) {
4101   default:
4102     return ReductionInstDesc(false, I);
4103   case Instruction::PHI:
4104       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4105                  Kind != RK_FloatMinMax))
4106         return ReductionInstDesc(false, I);
4107     return ReductionInstDesc(I, Prev.MinMaxKind);
4108   case Instruction::Sub:
4109   case Instruction::Add:
4110     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4111   case Instruction::Mul:
4112     return ReductionInstDesc(Kind == RK_IntegerMult, I);
4113   case Instruction::And:
4114     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4115   case Instruction::Or:
4116     return ReductionInstDesc(Kind == RK_IntegerOr, I);
4117   case Instruction::Xor:
4118     return ReductionInstDesc(Kind == RK_IntegerXor, I);
4119   case Instruction::FMul:
4120     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4121   case Instruction::FSub:
4122   case Instruction::FAdd:
4123     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4124   case Instruction::FCmp:
4125   case Instruction::ICmp:
4126   case Instruction::Select:
4127     if (Kind != RK_IntegerMinMax &&
4128         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4129       return ReductionInstDesc(false, I);
4130     return isMinMaxSelectCmpPattern(I, Prev);
4131   }
4132 }
4133
4134 LoopVectorizationLegality::InductionKind
4135 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4136                                                ConstantInt *&StepValue) {
4137   Type *PhiTy = Phi->getType();
4138   // We only handle integer and pointer inductions variables.
4139   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4140     return IK_NoInduction;
4141
4142   // Check that the PHI is consecutive.
4143   const SCEV *PhiScev = SE->getSCEV(Phi);
4144   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4145   if (!AR) {
4146     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4147     return IK_NoInduction;
4148   }
4149
4150   const SCEV *Step = AR->getStepRecurrence(*SE);
4151   // Calculate the pointer stride and check if it is consecutive.
4152   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4153   if (!C)
4154     return IK_NoInduction;
4155
4156   ConstantInt *CV = C->getValue();
4157   if (PhiTy->isIntegerTy()) {
4158     StepValue = CV;
4159     return IK_IntInduction;
4160   }
4161
4162   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4163   Type *PointerElementType = PhiTy->getPointerElementType();
4164   // The pointer stride cannot be determined if the pointer element type is not
4165   // sized.
4166   if (!PointerElementType->isSized())
4167     return IK_NoInduction;
4168
4169   int64_t Size = static_cast<int64_t>(DL->getTypeAllocSize(PointerElementType));
4170   int64_t CVSize = CV->getSExtValue();
4171   if (CVSize % Size)
4172     return IK_NoInduction;
4173   StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
4174   return IK_PtrInduction;
4175 }
4176
4177 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4178   Value *In0 = const_cast<Value*>(V);
4179   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4180   if (!PN)
4181     return false;
4182
4183   return Inductions.count(PN);
4184 }
4185
4186 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
4187   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4188 }
4189
4190 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4191                                            SmallPtrSetImpl<Value *> &SafePtrs) {
4192   
4193   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4194     // Check that we don't have a constant expression that can trap as operand.
4195     for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4196          OI != OE; ++OI) {
4197       if (Constant *C = dyn_cast<Constant>(*OI))
4198         if (C->canTrap())
4199           return false;
4200     }
4201     // We might be able to hoist the load.
4202     if (it->mayReadFromMemory()) {
4203       LoadInst *LI = dyn_cast<LoadInst>(it);
4204       if (!LI)
4205         return false;
4206       if (!SafePtrs.count(LI->getPointerOperand())) {
4207         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4208           MaskedOp.insert(LI);
4209           continue;
4210         }
4211         return false;
4212       }
4213     }
4214
4215     // We don't predicate stores at the moment.
4216     if (it->mayWriteToMemory()) {
4217       StoreInst *SI = dyn_cast<StoreInst>(it);
4218       // We only support predication of stores in basic blocks with one
4219       // predecessor.
4220       if (!SI)
4221         return false;
4222
4223       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4224       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4225       
4226       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4227           !isSinglePredecessor) {
4228         // Build a masked store if it is legal for the target, otherwise scalarize
4229         // the block.
4230         bool isLegalMaskedOp =
4231           isLegalMaskedStore(SI->getValueOperand()->getType(),
4232                              SI->getPointerOperand());
4233         if (isLegalMaskedOp) {
4234           --NumPredStores;
4235           MaskedOp.insert(SI);
4236           continue;
4237         }
4238         return false;
4239       }
4240     }
4241     if (it->mayThrow())
4242       return false;
4243
4244     // The instructions below can trap.
4245     switch (it->getOpcode()) {
4246     default: continue;
4247     case Instruction::UDiv:
4248     case Instruction::SDiv:
4249     case Instruction::URem:
4250     case Instruction::SRem:
4251       return false;
4252     }
4253   }
4254
4255   return true;
4256 }
4257
4258 LoopVectorizationCostModel::VectorizationFactor
4259 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4260   // Width 1 means no vectorize
4261   VectorizationFactor Factor = { 1U, 0U };
4262   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4263     emitAnalysis(VectorizationReport() <<
4264                  "runtime pointer checks needed. Enable vectorization of this "
4265                  "loop with '#pragma clang loop vectorize(enable)' when "
4266                  "compiling with -Os");
4267     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4268     return Factor;
4269   }
4270
4271   if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4272     emitAnalysis(VectorizationReport() <<
4273                  "store that is conditionally executed prevents vectorization");
4274     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4275     return Factor;
4276   }
4277
4278   // Find the trip count.
4279   unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4280   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4281
4282   unsigned WidestType = getWidestType();
4283   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4284   unsigned MaxSafeDepDist = -1U;
4285   if (Legal->getMaxSafeDepDistBytes() != -1U)
4286     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4287   WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4288                     WidestRegister : MaxSafeDepDist);
4289   unsigned MaxVectorSize = WidestRegister / WidestType;
4290   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4291   DEBUG(dbgs() << "LV: The Widest register is: "
4292           << WidestRegister << " bits.\n");
4293
4294   if (MaxVectorSize == 0) {
4295     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4296     MaxVectorSize = 1;
4297   }
4298
4299   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4300          " into one vector!");
4301
4302   unsigned VF = MaxVectorSize;
4303
4304   // If we optimize the program for size, avoid creating the tail loop.
4305   if (OptForSize) {
4306     // If we are unable to calculate the trip count then don't try to vectorize.
4307     if (TC < 2) {
4308       emitAnalysis
4309         (VectorizationReport() <<
4310          "unable to calculate the loop count due to complex control flow");
4311       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4312       return Factor;
4313     }
4314
4315     // Find the maximum SIMD width that can fit within the trip count.
4316     VF = TC % MaxVectorSize;
4317
4318     if (VF == 0)
4319       VF = MaxVectorSize;
4320
4321     // If the trip count that we found modulo the vectorization factor is not
4322     // zero then we require a tail.
4323     if (VF < 2) {
4324       emitAnalysis(VectorizationReport() <<
4325                    "cannot optimize for size and vectorize at the "
4326                    "same time. Enable vectorization of this loop "
4327                    "with '#pragma clang loop vectorize(enable)' "
4328                    "when compiling with -Os");
4329       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4330       return Factor;
4331     }
4332   }
4333
4334   int UserVF = Hints->getWidth();
4335   if (UserVF != 0) {
4336     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4337     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4338
4339     Factor.Width = UserVF;
4340     return Factor;
4341   }
4342
4343   float Cost = expectedCost(1);
4344 #ifndef NDEBUG
4345   const float ScalarCost = Cost;
4346 #endif /* NDEBUG */
4347   unsigned Width = 1;
4348   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4349
4350   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4351   // Ignore scalar width, because the user explicitly wants vectorization.
4352   if (ForceVectorization && VF > 1) {
4353     Width = 2;
4354     Cost = expectedCost(Width) / (float)Width;
4355   }
4356
4357   for (unsigned i=2; i <= VF; i*=2) {
4358     // Notice that the vector loop needs to be executed less times, so
4359     // we need to divide the cost of the vector loops by the width of
4360     // the vector elements.
4361     float VectorCost = expectedCost(i) / (float)i;
4362     DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4363           (int)VectorCost << ".\n");
4364     if (VectorCost < Cost) {
4365       Cost = VectorCost;
4366       Width = i;
4367     }
4368   }
4369
4370   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4371         << "LV: Vectorization seems to be not beneficial, "
4372         << "but was forced by a user.\n");
4373   DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4374   Factor.Width = Width;
4375   Factor.Cost = Width * Cost;
4376   return Factor;
4377 }
4378
4379 unsigned LoopVectorizationCostModel::getWidestType() {
4380   unsigned MaxWidth = 8;
4381
4382   // For each block.
4383   for (Loop::block_iterator bb = TheLoop->block_begin(),
4384        be = TheLoop->block_end(); bb != be; ++bb) {
4385     BasicBlock *BB = *bb;
4386
4387     // For each instruction in the loop.
4388     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4389       Type *T = it->getType();
4390
4391       // Ignore ephemeral values.
4392       if (EphValues.count(it))
4393         continue;
4394
4395       // Only examine Loads, Stores and PHINodes.
4396       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4397         continue;
4398
4399       // Examine PHI nodes that are reduction variables.
4400       if (PHINode *PN = dyn_cast<PHINode>(it))
4401         if (!Legal->getReductionVars()->count(PN))
4402           continue;
4403
4404       // Examine the stored values.
4405       if (StoreInst *ST = dyn_cast<StoreInst>(it))
4406         T = ST->getValueOperand()->getType();
4407
4408       // Ignore loaded pointer types and stored pointer types that are not
4409       // consecutive. However, we do want to take consecutive stores/loads of
4410       // pointer vectors into account.
4411       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4412         continue;
4413
4414       MaxWidth = std::max(MaxWidth,
4415                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4416     }
4417   }
4418
4419   return MaxWidth;
4420 }
4421
4422 unsigned
4423 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4424                                                unsigned VF,
4425                                                unsigned LoopCost) {
4426
4427   // -- The unroll heuristics --
4428   // We unroll the loop in order to expose ILP and reduce the loop overhead.
4429   // There are many micro-architectural considerations that we can't predict
4430   // at this level. For example, frontend pressure (on decode or fetch) due to
4431   // code size, or the number and capabilities of the execution ports.
4432   //
4433   // We use the following heuristics to select the unroll factor:
4434   // 1. If the code has reductions, then we unroll in order to break the cross
4435   // iteration dependency.
4436   // 2. If the loop is really small, then we unroll in order to reduce the loop
4437   // overhead.
4438   // 3. We don't unroll if we think that we will spill registers to memory due
4439   // to the increased register pressure.
4440
4441   // Use the user preference, unless 'auto' is selected.
4442   int UserUF = Hints->getInterleave();
4443   if (UserUF != 0)
4444     return UserUF;
4445
4446   // When we optimize for size, we don't unroll.
4447   if (OptForSize)
4448     return 1;
4449
4450   // We used the distance for the unroll factor.
4451   if (Legal->getMaxSafeDepDistBytes() != -1U)
4452     return 1;
4453
4454   // Do not unroll loops with a relatively small trip count.
4455   unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4456   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4457     return 1;
4458
4459   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4460   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4461         " registers\n");
4462
4463   if (VF == 1) {
4464     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4465       TargetNumRegisters = ForceTargetNumScalarRegs;
4466   } else {
4467     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4468       TargetNumRegisters = ForceTargetNumVectorRegs;
4469   }
4470
4471   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4472   // We divide by these constants so assume that we have at least one
4473   // instruction that uses at least one register.
4474   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4475   R.NumInstructions = std::max(R.NumInstructions, 1U);
4476
4477   // We calculate the unroll factor using the following formula.
4478   // Subtract the number of loop invariants from the number of available
4479   // registers. These registers are used by all of the unrolled instances.
4480   // Next, divide the remaining registers by the number of registers that is
4481   // required by the loop, in order to estimate how many parallel instances
4482   // fit without causing spills. All of this is rounded down if necessary to be
4483   // a power of two. We want power of two unroll factors to simplify any
4484   // addressing operations or alignment considerations.
4485   unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4486                               R.MaxLocalUsers);
4487
4488   // Don't count the induction variable as unrolled.
4489   if (EnableIndVarRegisterHeur)
4490     UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4491                        std::max(1U, (R.MaxLocalUsers - 1)));
4492
4493   // Clamp the unroll factor ranges to reasonable factors.
4494   unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
4495
4496   // Check if the user has overridden the unroll max.
4497   if (VF == 1) {
4498     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4499       MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
4500   } else {
4501     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4502       MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
4503   }
4504
4505   // If we did not calculate the cost for VF (because the user selected the VF)
4506   // then we calculate the cost of VF here.
4507   if (LoopCost == 0)
4508     LoopCost = expectedCost(VF);
4509
4510   // Clamp the calculated UF to be between the 1 and the max unroll factor
4511   // that the target allows.
4512   if (UF > MaxInterleaveSize)
4513     UF = MaxInterleaveSize;
4514   else if (UF < 1)
4515     UF = 1;
4516
4517   // Unroll if we vectorized this loop and there is a reduction that could
4518   // benefit from unrolling.
4519   if (VF > 1 && Legal->getReductionVars()->size()) {
4520     DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4521     return UF;
4522   }
4523
4524   // Note that if we've already vectorized the loop we will have done the
4525   // runtime check and so unrolling won't require further checks.
4526   bool UnrollingRequiresRuntimePointerCheck =
4527       (VF == 1 && Legal->getRuntimePointerCheck()->Need);
4528
4529   // We want to unroll small loops in order to reduce the loop overhead and
4530   // potentially expose ILP opportunities.
4531   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4532   if (!UnrollingRequiresRuntimePointerCheck &&
4533       LoopCost < SmallLoopCost) {
4534     // We assume that the cost overhead is 1 and we use the cost model
4535     // to estimate the cost of the loop and unroll until the cost of the
4536     // loop overhead is about 5% of the cost of the loop.
4537     unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4538
4539     // Unroll until store/load ports (estimated by max unroll factor) are
4540     // saturated.
4541     unsigned NumStores = Legal->getNumStores();
4542     unsigned NumLoads = Legal->getNumLoads();
4543     unsigned StoresUF = UF / (NumStores ? NumStores : 1);
4544     unsigned LoadsUF = UF /  (NumLoads ? NumLoads : 1);
4545
4546     // If we have a scalar reduction (vector reductions are already dealt with
4547     // by this point), we can increase the critical path length if the loop
4548     // we're unrolling is inside another loop. Limit, by default to 2, so the
4549     // critical path only gets increased by one reduction operation.
4550     if (Legal->getReductionVars()->size() &&
4551         TheLoop->getLoopDepth() > 1) {
4552       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
4553       SmallUF = std::min(SmallUF, F);
4554       StoresUF = std::min(StoresUF, F);
4555       LoadsUF = std::min(LoadsUF, F);
4556     }
4557
4558     if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
4559       DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
4560       return std::max(StoresUF, LoadsUF);
4561     }
4562
4563     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4564     return SmallUF;
4565   }
4566
4567   DEBUG(dbgs() << "LV: Not Unrolling.\n");
4568   return 1;
4569 }
4570
4571 LoopVectorizationCostModel::RegisterUsage
4572 LoopVectorizationCostModel::calculateRegisterUsage() {
4573   // This function calculates the register usage by measuring the highest number
4574   // of values that are alive at a single location. Obviously, this is a very
4575   // rough estimation. We scan the loop in a topological order in order and
4576   // assign a number to each instruction. We use RPO to ensure that defs are
4577   // met before their users. We assume that each instruction that has in-loop
4578   // users starts an interval. We record every time that an in-loop value is
4579   // used, so we have a list of the first and last occurrences of each
4580   // instruction. Next, we transpose this data structure into a multi map that
4581   // holds the list of intervals that *end* at a specific location. This multi
4582   // map allows us to perform a linear search. We scan the instructions linearly
4583   // and record each time that a new interval starts, by placing it in a set.
4584   // If we find this value in the multi-map then we remove it from the set.
4585   // The max register usage is the maximum size of the set.
4586   // We also search for instructions that are defined outside the loop, but are
4587   // used inside the loop. We need this number separately from the max-interval
4588   // usage number because when we unroll, loop-invariant values do not take
4589   // more register.
4590   LoopBlocksDFS DFS(TheLoop);
4591   DFS.perform(LI);
4592
4593   RegisterUsage R;
4594   R.NumInstructions = 0;
4595
4596   // Each 'key' in the map opens a new interval. The values
4597   // of the map are the index of the 'last seen' usage of the
4598   // instruction that is the key.
4599   typedef DenseMap<Instruction*, unsigned> IntervalMap;
4600   // Maps instruction to its index.
4601   DenseMap<unsigned, Instruction*> IdxToInstr;
4602   // Marks the end of each interval.
4603   IntervalMap EndPoint;
4604   // Saves the list of instruction indices that are used in the loop.
4605   SmallSet<Instruction*, 8> Ends;
4606   // Saves the list of values that are used in the loop but are
4607   // defined outside the loop, such as arguments and constants.
4608   SmallPtrSet<Value*, 8> LoopInvariants;
4609
4610   unsigned Index = 0;
4611   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4612        be = DFS.endRPO(); bb != be; ++bb) {
4613     R.NumInstructions += (*bb)->size();
4614     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4615          ++it) {
4616       Instruction *I = it;
4617       IdxToInstr[Index++] = I;
4618
4619       // Save the end location of each USE.
4620       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4621         Value *U = I->getOperand(i);
4622         Instruction *Instr = dyn_cast<Instruction>(U);
4623
4624         // Ignore non-instruction values such as arguments, constants, etc.
4625         if (!Instr) continue;
4626
4627         // If this instruction is outside the loop then record it and continue.
4628         if (!TheLoop->contains(Instr)) {
4629           LoopInvariants.insert(Instr);
4630           continue;
4631         }
4632
4633         // Overwrite previous end points.
4634         EndPoint[Instr] = Index;
4635         Ends.insert(Instr);
4636       }
4637     }
4638   }
4639
4640   // Saves the list of intervals that end with the index in 'key'.
4641   typedef SmallVector<Instruction*, 2> InstrList;
4642   DenseMap<unsigned, InstrList> TransposeEnds;
4643
4644   // Transpose the EndPoints to a list of values that end at each index.
4645   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4646        it != e; ++it)
4647     TransposeEnds[it->second].push_back(it->first);
4648
4649   SmallSet<Instruction*, 8> OpenIntervals;
4650   unsigned MaxUsage = 0;
4651
4652
4653   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4654   for (unsigned int i = 0; i < Index; ++i) {
4655     Instruction *I = IdxToInstr[i];
4656     // Ignore instructions that are never used within the loop.
4657     if (!Ends.count(I)) continue;
4658
4659     // Ignore ephemeral values.
4660     if (EphValues.count(I))
4661       continue;
4662
4663     // Remove all of the instructions that end at this location.
4664     InstrList &List = TransposeEnds[i];
4665     for (unsigned int j=0, e = List.size(); j < e; ++j)
4666       OpenIntervals.erase(List[j]);
4667
4668     // Count the number of live interals.
4669     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4670
4671     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4672           OpenIntervals.size() << '\n');
4673
4674     // Add the current instruction to the list of open intervals.
4675     OpenIntervals.insert(I);
4676   }
4677
4678   unsigned Invariant = LoopInvariants.size();
4679   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4680   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4681   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4682
4683   R.LoopInvariantRegs = Invariant;
4684   R.MaxLocalUsers = MaxUsage;
4685   return R;
4686 }
4687
4688 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4689   unsigned Cost = 0;
4690
4691   // For each block.
4692   for (Loop::block_iterator bb = TheLoop->block_begin(),
4693        be = TheLoop->block_end(); bb != be; ++bb) {
4694     unsigned BlockCost = 0;
4695     BasicBlock *BB = *bb;
4696
4697     // For each instruction in the old loop.
4698     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4699       // Skip dbg intrinsics.
4700       if (isa<DbgInfoIntrinsic>(it))
4701         continue;
4702
4703       // Ignore ephemeral values.
4704       if (EphValues.count(it))
4705         continue;
4706
4707       unsigned C = getInstructionCost(it, VF);
4708
4709       // Check if we should override the cost.
4710       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4711         C = ForceTargetInstructionCost;
4712
4713       BlockCost += C;
4714       DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
4715             VF << " For instruction: " << *it << '\n');
4716     }
4717
4718     // We assume that if-converted blocks have a 50% chance of being executed.
4719     // When the code is scalar then some of the blocks are avoided due to CF.
4720     // When the code is vectorized we execute all code paths.
4721     if (VF == 1 && Legal->blockNeedsPredication(*bb))
4722       BlockCost /= 2;
4723
4724     Cost += BlockCost;
4725   }
4726
4727   return Cost;
4728 }
4729
4730 /// \brief Check whether the address computation for a non-consecutive memory
4731 /// access looks like an unlikely candidate for being merged into the indexing
4732 /// mode.
4733 ///
4734 /// We look for a GEP which has one index that is an induction variable and all
4735 /// other indices are loop invariant. If the stride of this access is also
4736 /// within a small bound we decide that this address computation can likely be
4737 /// merged into the addressing mode.
4738 /// In all other cases, we identify the address computation as complex.
4739 static bool isLikelyComplexAddressComputation(Value *Ptr,
4740                                               LoopVectorizationLegality *Legal,
4741                                               ScalarEvolution *SE,
4742                                               const Loop *TheLoop) {
4743   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4744   if (!Gep)
4745     return true;
4746
4747   // We are looking for a gep with all loop invariant indices except for one
4748   // which should be an induction variable.
4749   unsigned NumOperands = Gep->getNumOperands();
4750   for (unsigned i = 1; i < NumOperands; ++i) {
4751     Value *Opd = Gep->getOperand(i);
4752     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4753         !Legal->isInductionVariable(Opd))
4754       return true;
4755   }
4756
4757   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4758   // can likely be merged into the address computation.
4759   unsigned MaxMergeDistance = 64;
4760
4761   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4762   if (!AddRec)
4763     return true;
4764
4765   // Check the step is constant.
4766   const SCEV *Step = AddRec->getStepRecurrence(*SE);
4767   // Calculate the pointer stride and check if it is consecutive.
4768   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4769   if (!C)
4770     return true;
4771
4772   const APInt &APStepVal = C->getValue()->getValue();
4773
4774   // Huge step value - give up.
4775   if (APStepVal.getBitWidth() > 64)
4776     return true;
4777
4778   int64_t StepVal = APStepVal.getSExtValue();
4779
4780   return StepVal > MaxMergeDistance;
4781 }
4782
4783 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
4784   if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
4785     return true;
4786   return false;
4787 }
4788
4789 unsigned
4790 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4791   // If we know that this instruction will remain uniform, check the cost of
4792   // the scalar version.
4793   if (Legal->isUniformAfterVectorization(I))
4794     VF = 1;
4795
4796   Type *RetTy = I->getType();
4797   Type *VectorTy = ToVectorTy(RetTy, VF);
4798
4799   // TODO: We need to estimate the cost of intrinsic calls.
4800   switch (I->getOpcode()) {
4801   case Instruction::GetElementPtr:
4802     // We mark this instruction as zero-cost because the cost of GEPs in
4803     // vectorized code depends on whether the corresponding memory instruction
4804     // is scalarized or not. Therefore, we handle GEPs with the memory
4805     // instruction cost.
4806     return 0;
4807   case Instruction::Br: {
4808     return TTI.getCFInstrCost(I->getOpcode());
4809   }
4810   case Instruction::PHI:
4811     //TODO: IF-converted IFs become selects.
4812     return 0;
4813   case Instruction::Add:
4814   case Instruction::FAdd:
4815   case Instruction::Sub:
4816   case Instruction::FSub:
4817   case Instruction::Mul:
4818   case Instruction::FMul:
4819   case Instruction::UDiv:
4820   case Instruction::SDiv:
4821   case Instruction::FDiv:
4822   case Instruction::URem:
4823   case Instruction::SRem:
4824   case Instruction::FRem:
4825   case Instruction::Shl:
4826   case Instruction::LShr:
4827   case Instruction::AShr:
4828   case Instruction::And:
4829   case Instruction::Or:
4830   case Instruction::Xor: {
4831     // Since we will replace the stride by 1 the multiplication should go away.
4832     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
4833       return 0;
4834     // Certain instructions can be cheaper to vectorize if they have a constant
4835     // second vector operand. One example of this are shifts on x86.
4836     TargetTransformInfo::OperandValueKind Op1VK =
4837       TargetTransformInfo::OK_AnyValue;
4838     TargetTransformInfo::OperandValueKind Op2VK =
4839       TargetTransformInfo::OK_AnyValue;
4840     TargetTransformInfo::OperandValueProperties Op1VP =
4841         TargetTransformInfo::OP_None;
4842     TargetTransformInfo::OperandValueProperties Op2VP =
4843         TargetTransformInfo::OP_None;
4844     Value *Op2 = I->getOperand(1);
4845
4846     // Check for a splat of a constant or for a non uniform vector of constants.
4847     if (isa<ConstantInt>(Op2)) {
4848       ConstantInt *CInt = cast<ConstantInt>(Op2);
4849       if (CInt && CInt->getValue().isPowerOf2())
4850         Op2VP = TargetTransformInfo::OP_PowerOf2;
4851       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4852     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
4853       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4854       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
4855       if (SplatValue) {
4856         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
4857         if (CInt && CInt->getValue().isPowerOf2())
4858           Op2VP = TargetTransformInfo::OP_PowerOf2;
4859         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4860       }
4861     }
4862
4863     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
4864                                       Op1VP, Op2VP);
4865   }
4866   case Instruction::Select: {
4867     SelectInst *SI = cast<SelectInst>(I);
4868     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4869     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4870     Type *CondTy = SI->getCondition()->getType();
4871     if (!ScalarCond)
4872       CondTy = VectorType::get(CondTy, VF);
4873
4874     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4875   }
4876   case Instruction::ICmp:
4877   case Instruction::FCmp: {
4878     Type *ValTy = I->getOperand(0)->getType();
4879     VectorTy = ToVectorTy(ValTy, VF);
4880     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4881   }
4882   case Instruction::Store:
4883   case Instruction::Load: {
4884     StoreInst *SI = dyn_cast<StoreInst>(I);
4885     LoadInst *LI = dyn_cast<LoadInst>(I);
4886     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4887                    LI->getType());
4888     VectorTy = ToVectorTy(ValTy, VF);
4889
4890     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4891     unsigned AS = SI ? SI->getPointerAddressSpace() :
4892       LI->getPointerAddressSpace();
4893     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4894     // We add the cost of address computation here instead of with the gep
4895     // instruction because only here we know whether the operation is
4896     // scalarized.
4897     if (VF == 1)
4898       return TTI.getAddressComputationCost(VectorTy) +
4899         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4900
4901     // Scalarized loads/stores.
4902     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4903     bool Reverse = ConsecutiveStride < 0;
4904     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
4905     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
4906     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4907       bool IsComplexComputation =
4908         isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4909       unsigned Cost = 0;
4910       // The cost of extracting from the value vector and pointer vector.
4911       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4912       for (unsigned i = 0; i < VF; ++i) {
4913         //  The cost of extracting the pointer operand.
4914         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4915         // In case of STORE, the cost of ExtractElement from the vector.
4916         // In case of LOAD, the cost of InsertElement into the returned
4917         // vector.
4918         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4919                                             Instruction::InsertElement,
4920                                             VectorTy, i);
4921       }
4922
4923       // The cost of the scalar loads/stores.
4924       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
4925       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4926                                        Alignment, AS);
4927       return Cost;
4928     }
4929
4930     // Wide load/stores.
4931     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4932     if (Legal->isMaskRequired(I))
4933       Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
4934                                         AS);
4935     else
4936       Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4937
4938     if (Reverse)
4939       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4940                                   VectorTy, 0);
4941     return Cost;
4942   }
4943   case Instruction::ZExt:
4944   case Instruction::SExt:
4945   case Instruction::FPToUI:
4946   case Instruction::FPToSI:
4947   case Instruction::FPExt:
4948   case Instruction::PtrToInt:
4949   case Instruction::IntToPtr:
4950   case Instruction::SIToFP:
4951   case Instruction::UIToFP:
4952   case Instruction::Trunc:
4953   case Instruction::FPTrunc:
4954   case Instruction::BitCast: {
4955     // We optimize the truncation of induction variable.
4956     // The cost of these is the same as the scalar operation.
4957     if (I->getOpcode() == Instruction::Trunc &&
4958         Legal->isInductionVariable(I->getOperand(0)))
4959       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
4960                                   I->getOperand(0)->getType());
4961
4962     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
4963     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
4964   }
4965   case Instruction::Call: {
4966     CallInst *CI = cast<CallInst>(I);
4967     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
4968     assert(ID && "Not an intrinsic call!");
4969     Type *RetTy = ToVectorTy(CI->getType(), VF);
4970     SmallVector<Type*, 4> Tys;
4971     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4972       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4973     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
4974   }
4975   default: {
4976     // We are scalarizing the instruction. Return the cost of the scalar
4977     // instruction, plus the cost of insert and extract into vector
4978     // elements, times the vector width.
4979     unsigned Cost = 0;
4980
4981     if (!RetTy->isVoidTy() && VF != 1) {
4982       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4983                                                 VectorTy);
4984       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4985                                                 VectorTy);
4986
4987       // The cost of inserting the results plus extracting each one of the
4988       // operands.
4989       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4990     }
4991
4992     // The cost of executing VF copies of the scalar instruction. This opcode
4993     // is unknown. Assume that it is the same as 'mul'.
4994     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4995     return Cost;
4996   }
4997   }// end of switch.
4998 }
4999
5000 char LoopVectorize::ID = 0;
5001 static const char lv_name[] = "Loop Vectorization";
5002 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5003 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5004 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5005 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5006 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5007 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5008 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5009 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5010 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5011 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5012 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5013 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5014
5015 namespace llvm {
5016   Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5017     return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5018   }
5019 }
5020
5021 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5022   // Check for a store.
5023   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5024     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5025
5026   // Check for a load.
5027   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5028     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5029
5030   return false;
5031 }
5032
5033
5034 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5035                                              bool IfPredicateStore) {
5036   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5037   // Holds vector parameters or scalars, in case of uniform vals.
5038   SmallVector<VectorParts, 4> Params;
5039
5040   setDebugLocFromInst(Builder, Instr);
5041
5042   // Find all of the vectorized parameters.
5043   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5044     Value *SrcOp = Instr->getOperand(op);
5045
5046     // If we are accessing the old induction variable, use the new one.
5047     if (SrcOp == OldInduction) {
5048       Params.push_back(getVectorValue(SrcOp));
5049       continue;
5050     }
5051
5052     // Try using previously calculated values.
5053     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5054
5055     // If the src is an instruction that appeared earlier in the basic block
5056     // then it should already be vectorized.
5057     if (SrcInst && OrigLoop->contains(SrcInst)) {
5058       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5059       // The parameter is a vector value from earlier.
5060       Params.push_back(WidenMap.get(SrcInst));
5061     } else {
5062       // The parameter is a scalar from outside the loop. Maybe even a constant.
5063       VectorParts Scalars;
5064       Scalars.append(UF, SrcOp);
5065       Params.push_back(Scalars);
5066     }
5067   }
5068
5069   assert(Params.size() == Instr->getNumOperands() &&
5070          "Invalid number of operands");
5071
5072   // Does this instruction return a value ?
5073   bool IsVoidRetTy = Instr->getType()->isVoidTy();
5074
5075   Value *UndefVec = IsVoidRetTy ? nullptr :
5076   UndefValue::get(Instr->getType());
5077   // Create a new entry in the WidenMap and initialize it to Undef or Null.
5078   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5079
5080   Instruction *InsertPt = Builder.GetInsertPoint();
5081   BasicBlock *IfBlock = Builder.GetInsertBlock();
5082   BasicBlock *CondBlock = nullptr;
5083
5084   VectorParts Cond;
5085   Loop *VectorLp = nullptr;
5086   if (IfPredicateStore) {
5087     assert(Instr->getParent()->getSinglePredecessor() &&
5088            "Only support single predecessor blocks");
5089     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5090                           Instr->getParent());
5091     VectorLp = LI->getLoopFor(IfBlock);
5092     assert(VectorLp && "Must have a loop for this block");
5093   }
5094
5095   // For each vector unroll 'part':
5096   for (unsigned Part = 0; Part < UF; ++Part) {
5097     // For each scalar that we create:
5098
5099     // Start an "if (pred) a[i] = ..." block.
5100     Value *Cmp = nullptr;
5101     if (IfPredicateStore) {
5102       if (Cond[Part]->getType()->isVectorTy())
5103         Cond[Part] =
5104             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5105       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5106                                ConstantInt::get(Cond[Part]->getType(), 1));
5107       CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5108       LoopVectorBody.push_back(CondBlock);
5109       VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5110       // Update Builder with newly created basic block.
5111       Builder.SetInsertPoint(InsertPt);
5112     }
5113
5114     Instruction *Cloned = Instr->clone();
5115       if (!IsVoidRetTy)
5116         Cloned->setName(Instr->getName() + ".cloned");
5117       // Replace the operands of the cloned instructions with extracted scalars.
5118       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5119         Value *Op = Params[op][Part];
5120         Cloned->setOperand(op, Op);
5121       }
5122
5123       // Place the cloned scalar in the new loop.
5124       Builder.Insert(Cloned);
5125
5126       // If the original scalar returns a value we need to place it in a vector
5127       // so that future users will be able to use it.
5128       if (!IsVoidRetTy)
5129         VecResults[Part] = Cloned;
5130
5131     // End if-block.
5132       if (IfPredicateStore) {
5133         BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5134         LoopVectorBody.push_back(NewIfBlock);
5135         VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5136         Builder.SetInsertPoint(InsertPt);
5137         Instruction *OldBr = IfBlock->getTerminator();
5138         BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5139         OldBr->eraseFromParent();
5140         IfBlock = NewIfBlock;
5141       }
5142   }
5143 }
5144
5145 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5146   StoreInst *SI = dyn_cast<StoreInst>(Instr);
5147   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5148
5149   return scalarizeInstruction(Instr, IfPredicateStore);
5150 }
5151
5152 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5153   return Vec;
5154 }
5155
5156 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5157   return V;
5158 }
5159
5160 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5161   // When unrolling and the VF is 1, we only need to add a simple scalar.
5162   Type *ITy = Val->getType();
5163   assert(!ITy->isVectorTy() && "Val must be a scalar");
5164   Constant *C = ConstantInt::get(ITy, StartIdx);
5165   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
5166 }