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