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