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