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