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