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