]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
MFV r313569:313569:313569:
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/LoopVectorize.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/Hashing.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/SCCIterator.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/CodeMetrics.h"
61 #include "llvm/Analysis/GlobalsModRef.h"
62 #include "llvm/Analysis/LoopInfo.h"
63 #include "llvm/Analysis/LoopIterator.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolutionExpander.h"
66 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
67 #include "llvm/Analysis/ValueTracking.h"
68 #include "llvm/Analysis/VectorUtils.h"
69 #include "llvm/IR/Constants.h"
70 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DebugInfo.h"
72 #include "llvm/IR/DerivedTypes.h"
73 #include "llvm/IR/DiagnosticInfo.h"
74 #include "llvm/IR/Dominators.h"
75 #include "llvm/IR/Function.h"
76 #include "llvm/IR/IRBuilder.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/PatternMatch.h"
82 #include "llvm/IR/Type.h"
83 #include "llvm/IR/Value.h"
84 #include "llvm/IR/ValueHandle.h"
85 #include "llvm/IR/Verifier.h"
86 #include "llvm/Pass.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Debug.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Transforms/Scalar.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include "llvm/Transforms/Utils/Local.h"
94 #include "llvm/Transforms/Utils/LoopUtils.h"
95 #include "llvm/Transforms/Utils/LoopVersioning.h"
96 #include "llvm/Transforms/Vectorize.h"
97 #include <algorithm>
98 #include <map>
99 #include <tuple>
100
101 using namespace llvm;
102 using namespace llvm::PatternMatch;
103
104 #define LV_NAME "loop-vectorize"
105 #define DEBUG_TYPE LV_NAME
106
107 STATISTIC(LoopsVectorized, "Number of loops vectorized");
108 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
109
110 static cl::opt<bool>
111     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
112                        cl::desc("Enable if-conversion during vectorization."));
113
114 /// We don't vectorize loops with a known constant trip count below this number.
115 static cl::opt<unsigned> TinyTripCountVectorThreshold(
116     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
117     cl::desc("Don't vectorize loops with a constant "
118              "trip count that is smaller than this "
119              "value."));
120
121 static cl::opt<bool> MaximizeBandwidth(
122     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
123     cl::desc("Maximize bandwidth when selecting vectorization factor which "
124              "will be determined by the smallest type in loop."));
125
126 static cl::opt<bool> EnableInterleavedMemAccesses(
127     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
128     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
129
130 /// Maximum factor for an interleaved memory access.
131 static cl::opt<unsigned> MaxInterleaveGroupFactor(
132     "max-interleave-group-factor", cl::Hidden,
133     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
134     cl::init(8));
135
136 /// We don't interleave loops with a known constant trip count below this
137 /// number.
138 static const unsigned TinyTripCountInterleaveThreshold = 128;
139
140 static cl::opt<unsigned> ForceTargetNumScalarRegs(
141     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
142     cl::desc("A flag that overrides the target's number of scalar registers."));
143
144 static cl::opt<unsigned> ForceTargetNumVectorRegs(
145     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
146     cl::desc("A flag that overrides the target's number of vector registers."));
147
148 /// Maximum vectorization interleave count.
149 static const unsigned MaxInterleaveFactor = 16;
150
151 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
152     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
153     cl::desc("A flag that overrides the target's max interleave factor for "
154              "scalar loops."));
155
156 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
157     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
158     cl::desc("A flag that overrides the target's max interleave factor for "
159              "vectorized loops."));
160
161 static cl::opt<unsigned> ForceTargetInstructionCost(
162     "force-target-instruction-cost", cl::init(0), cl::Hidden,
163     cl::desc("A flag that overrides the target's expected cost for "
164              "an instruction to a single constant value. Mostly "
165              "useful for getting consistent testing."));
166
167 static cl::opt<unsigned> SmallLoopCost(
168     "small-loop-cost", cl::init(20), cl::Hidden,
169     cl::desc(
170         "The cost of a loop that is considered 'small' by the interleaver."));
171
172 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
173     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
174     cl::desc("Enable the use of the block frequency analysis to access PGO "
175              "heuristics minimizing code growth in cold regions and being more "
176              "aggressive in hot regions."));
177
178 // Runtime interleave loops for load/store throughput.
179 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
180     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
181     cl::desc(
182         "Enable runtime interleaving until load/store ports are saturated"));
183
184 /// The number of stores in a loop that are allowed to need predication.
185 static cl::opt<unsigned> NumberOfStoresToPredicate(
186     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
187     cl::desc("Max number of stores to be predicated behind an if."));
188
189 static cl::opt<bool> EnableIndVarRegisterHeur(
190     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
191     cl::desc("Count the induction variable only once when interleaving"));
192
193 static cl::opt<bool> EnableCondStoresVectorization(
194     "enable-cond-stores-vec", cl::init(false), cl::Hidden,
195     cl::desc("Enable if predication of stores during vectorization."));
196
197 static cl::opt<unsigned> MaxNestedScalarReductionIC(
198     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
199     cl::desc("The maximum interleave count to use when interleaving a scalar "
200              "reduction in a nested loop."));
201
202 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
203     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
204     cl::desc("The maximum allowed number of runtime memory checks with a "
205              "vectorize(enable) pragma."));
206
207 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
208     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
209     cl::desc("The maximum number of SCEV checks allowed."));
210
211 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
212     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
213     cl::desc("The maximum number of SCEV checks allowed with a "
214              "vectorize(enable) pragma"));
215
216 namespace {
217
218 // Forward declarations.
219 class LoopVectorizeHints;
220 class LoopVectorizationLegality;
221 class LoopVectorizationCostModel;
222 class LoopVectorizationRequirements;
223
224 // A traits type that is intended to be used in graph algorithms. The graph it
225 // models starts at the loop header, and traverses the BasicBlocks that are in
226 // the loop body, but not the loop header. Since the loop header is skipped,
227 // the back edges are excluded.
228 struct LoopBodyTraits {
229   using NodeRef = std::pair<const Loop *, BasicBlock *>;
230
231   // This wraps a const Loop * into the iterator, so we know which edges to
232   // filter out.
233   class WrappedSuccIterator
234       : public iterator_adaptor_base<
235             WrappedSuccIterator, succ_iterator,
236             typename std::iterator_traits<succ_iterator>::iterator_category,
237             NodeRef, std::ptrdiff_t, NodeRef *, NodeRef> {
238     using BaseT = iterator_adaptor_base<
239         WrappedSuccIterator, succ_iterator,
240         typename std::iterator_traits<succ_iterator>::iterator_category,
241         NodeRef, std::ptrdiff_t, NodeRef *, NodeRef>;
242
243     const Loop *L;
244
245   public:
246     WrappedSuccIterator(succ_iterator Begin, const Loop *L)
247         : BaseT(Begin), L(L) {}
248
249     NodeRef operator*() const { return {L, *I}; }
250   };
251
252   struct LoopBodyFilter {
253     bool operator()(NodeRef N) const {
254       const Loop *L = N.first;
255       return N.second != L->getHeader() && L->contains(N.second);
256     }
257   };
258
259   using ChildIteratorType =
260       filter_iterator<WrappedSuccIterator, LoopBodyFilter>;
261
262   static NodeRef getEntryNode(const Loop &G) { return {&G, G.getHeader()}; }
263
264   static ChildIteratorType child_begin(NodeRef Node) {
265     return make_filter_range(make_range<WrappedSuccIterator>(
266                                  {succ_begin(Node.second), Node.first},
267                                  {succ_end(Node.second), Node.first}),
268                              LoopBodyFilter{})
269         .begin();
270   }
271
272   static ChildIteratorType child_end(NodeRef Node) {
273     return make_filter_range(make_range<WrappedSuccIterator>(
274                                  {succ_begin(Node.second), Node.first},
275                                  {succ_end(Node.second), Node.first}),
276                              LoopBodyFilter{})
277         .end();
278   }
279 };
280
281 /// Returns true if the given loop body has a cycle, excluding the loop
282 /// itself.
283 static bool hasCyclesInLoopBody(const Loop &L) {
284   if (!L.empty())
285     return true;
286
287   for (const auto SCC :
288        make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L),
289                   scc_iterator<Loop, LoopBodyTraits>::end(L))) {
290     if (SCC.size() > 1) {
291       DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n");
292       DEBUG(L.dump());
293       return true;
294     }
295   }
296   return false;
297 }
298
299 /// \brief This modifies LoopAccessReport to initialize message with
300 /// loop-vectorizer-specific part.
301 class VectorizationReport : public LoopAccessReport {
302 public:
303   VectorizationReport(Instruction *I = nullptr)
304       : LoopAccessReport("loop not vectorized: ", I) {}
305
306   /// \brief This allows promotion of the loop-access analysis report into the
307   /// loop-vectorizer report.  It modifies the message to add the
308   /// loop-vectorizer-specific part of the message.
309   explicit VectorizationReport(const LoopAccessReport &R)
310       : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
311                          R.getInstr()) {}
312 };
313
314 /// A helper function for converting Scalar types to vector types.
315 /// If the incoming type is void, we return void. If the VF is 1, we return
316 /// the scalar type.
317 static Type *ToVectorTy(Type *Scalar, unsigned VF) {
318   if (Scalar->isVoidTy() || VF == 1)
319     return Scalar;
320   return VectorType::get(Scalar, VF);
321 }
322
323 /// A helper function that returns GEP instruction and knows to skip a
324 /// 'bitcast'. The 'bitcast' may be skipped if the source and the destination
325 /// pointee types of the 'bitcast' have the same size.
326 /// For example:
327 ///   bitcast double** %var to i64* - can be skipped
328 ///   bitcast double** %var to i8*  - can not
329 static GetElementPtrInst *getGEPInstruction(Value *Ptr) {
330
331   if (isa<GetElementPtrInst>(Ptr))
332     return cast<GetElementPtrInst>(Ptr);
333
334   if (isa<BitCastInst>(Ptr) &&
335       isa<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0))) {
336     Type *BitcastTy = Ptr->getType();
337     Type *GEPTy = cast<BitCastInst>(Ptr)->getSrcTy();
338     if (!isa<PointerType>(BitcastTy) || !isa<PointerType>(GEPTy))
339       return nullptr;
340     Type *Pointee1Ty = cast<PointerType>(BitcastTy)->getPointerElementType();
341     Type *Pointee2Ty = cast<PointerType>(GEPTy)->getPointerElementType();
342     const DataLayout &DL = cast<BitCastInst>(Ptr)->getModule()->getDataLayout();
343     if (DL.getTypeSizeInBits(Pointee1Ty) == DL.getTypeSizeInBits(Pointee2Ty))
344       return cast<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0));
345   }
346   return nullptr;
347 }
348
349 /// InnerLoopVectorizer vectorizes loops which contain only one basic
350 /// block to a specified vectorization factor (VF).
351 /// This class performs the widening of scalars into vectors, or multiple
352 /// scalars. This class also implements the following features:
353 /// * It inserts an epilogue loop for handling loops that don't have iteration
354 ///   counts that are known to be a multiple of the vectorization factor.
355 /// * It handles the code generation for reduction variables.
356 /// * Scalarization (implementation using scalars) of un-vectorizable
357 ///   instructions.
358 /// InnerLoopVectorizer does not perform any vectorization-legality
359 /// checks, and relies on the caller to check for the different legality
360 /// aspects. The InnerLoopVectorizer relies on the
361 /// LoopVectorizationLegality class to provide information about the induction
362 /// and reduction variables that were found to a given vectorization factor.
363 class InnerLoopVectorizer {
364 public:
365   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
366                       LoopInfo *LI, DominatorTree *DT,
367                       const TargetLibraryInfo *TLI,
368                       const TargetTransformInfo *TTI, AssumptionCache *AC,
369                       unsigned VecWidth, unsigned UnrollFactor)
370       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
371         AC(AC), VF(VecWidth), UF(UnrollFactor),
372         Builder(PSE.getSE()->getContext()), Induction(nullptr),
373         OldInduction(nullptr), WidenMap(UnrollFactor), TripCount(nullptr),
374         VectorTripCount(nullptr), Legal(nullptr), AddedSafetyChecks(false) {}
375
376   // Perform the actual loop widening (vectorization).
377   // MinimumBitWidths maps scalar integer values to the smallest bitwidth they
378   // can be validly truncated to. The cost model has assumed this truncation
379   // will happen when vectorizing. VecValuesToIgnore contains scalar values
380   // that the cost model has chosen to ignore because they will not be
381   // vectorized.
382   void vectorize(LoopVectorizationLegality *L,
383                  const MapVector<Instruction *, uint64_t> &MinimumBitWidths,
384                  SmallPtrSetImpl<const Value *> &VecValuesToIgnore) {
385     MinBWs = &MinimumBitWidths;
386     ValuesNotWidened = &VecValuesToIgnore;
387     Legal = L;
388     // Create a new empty loop. Unlink the old loop and connect the new one.
389     createEmptyLoop();
390     // Widen each instruction in the old loop to a new one in the new loop.
391     // Use the Legality module to find the induction and reduction variables.
392     vectorizeLoop();
393   }
394
395   // Return true if any runtime check is added.
396   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
397
398   virtual ~InnerLoopVectorizer() {}
399
400 protected:
401   /// A small list of PHINodes.
402   typedef SmallVector<PHINode *, 4> PhiVector;
403   /// When we unroll loops we have multiple vector values for each scalar.
404   /// This data structure holds the unrolled and vectorized values that
405   /// originated from one scalar instruction.
406   typedef SmallVector<Value *, 2> VectorParts;
407
408   // When we if-convert we need to create edge masks. We have to cache values
409   // so that we don't end up with exponential recursion/IR.
410   typedef DenseMap<std::pair<BasicBlock *, BasicBlock *>, VectorParts>
411       EdgeMaskCache;
412
413   /// Create an empty loop, based on the loop ranges of the old loop.
414   void createEmptyLoop();
415
416   /// Set up the values of the IVs correctly when exiting the vector loop.
417   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
418                     Value *CountRoundDown, Value *EndValue,
419                     BasicBlock *MiddleBlock);
420
421   /// Create a new induction variable inside L.
422   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
423                                    Value *Step, Instruction *DL);
424   /// Copy and widen the instructions from the old loop.
425   virtual void vectorizeLoop();
426
427   /// Fix a first-order recurrence. This is the second phase of vectorizing
428   /// this phi node.
429   void fixFirstOrderRecurrence(PHINode *Phi);
430
431   /// \brief The Loop exit block may have single value PHI nodes where the
432   /// incoming value is 'Undef'. While vectorizing we only handled real values
433   /// that were defined inside the loop. Here we fix the 'undef case'.
434   /// See PR14725.
435   void fixLCSSAPHIs();
436
437   /// Shrinks vector element sizes based on information in "MinBWs".
438   void truncateToMinimalBitwidths();
439
440   /// A helper function that computes the predicate of the block BB, assuming
441   /// that the header block of the loop is set to True. It returns the *entry*
442   /// mask for the block BB.
443   VectorParts createBlockInMask(BasicBlock *BB);
444   /// A helper function that computes the predicate of the edge between SRC
445   /// and DST.
446   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
447
448   /// A helper function to vectorize a single BB within the innermost loop.
449   void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
450
451   /// Vectorize a single PHINode in a block. This method handles the induction
452   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
453   /// arbitrary length vectors.
454   void widenPHIInstruction(Instruction *PN, VectorParts &Entry, unsigned UF,
455                            unsigned VF, PhiVector *PV);
456
457   /// Insert the new loop to the loop hierarchy and pass manager
458   /// and update the analysis passes.
459   void updateAnalysis();
460
461   /// This instruction is un-vectorizable. Implement it as a sequence
462   /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
463   /// scalarized instruction behind an if block predicated on the control
464   /// dependence of the instruction.
465   virtual void scalarizeInstruction(Instruction *Instr,
466                                     bool IfPredicateStore = false);
467
468   /// Vectorize Load and Store instructions,
469   virtual void vectorizeMemoryInstruction(Instruction *Instr);
470
471   /// Create a broadcast instruction. This method generates a broadcast
472   /// instruction (shuffle) for loop invariant values and for the induction
473   /// value. If this is the induction variable then we extend it to N, N+1, ...
474   /// this is needed because each iteration in the loop corresponds to a SIMD
475   /// element.
476   virtual Value *getBroadcastInstrs(Value *V);
477
478   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
479   /// to each vector element of Val. The sequence starts at StartIndex.
480   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
481
482   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
483   /// variable on which to base the steps, \p Step is the size of the step, and
484   /// \p EntryVal is the value from the original loop that maps to the steps.
485   /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it
486   /// can be a truncate instruction).
487   void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal);
488
489   /// Create a vector induction phi node based on an existing scalar one. This
490   /// currently only works for integer induction variables with a constant
491   /// step. If \p TruncType is non-null, instead of widening the original IV,
492   /// we widen a version of the IV truncated to \p TruncType.
493   void createVectorIntInductionPHI(const InductionDescriptor &II,
494                                    VectorParts &Entry, IntegerType *TruncType);
495
496   /// Widen an integer induction variable \p IV. If \p Trunc is provided, the
497   /// induction variable will first be truncated to the corresponding type. The
498   /// widened values are placed in \p Entry.
499   void widenIntInduction(PHINode *IV, VectorParts &Entry,
500                          TruncInst *Trunc = nullptr);
501
502   /// When we go over instructions in the basic block we rely on previous
503   /// values within the current basic block or on loop invariant values.
504   /// When we widen (vectorize) values we place them in the map. If the values
505   /// are not within the map, they have to be loop invariant, so we simply
506   /// broadcast them into a vector.
507   VectorParts &getVectorValue(Value *V);
508
509   /// Try to vectorize the interleaved access group that \p Instr belongs to.
510   void vectorizeInterleaveGroup(Instruction *Instr);
511
512   /// Generate a shuffle sequence that will reverse the vector Vec.
513   virtual Value *reverseVector(Value *Vec);
514
515   /// Returns (and creates if needed) the original loop trip count.
516   Value *getOrCreateTripCount(Loop *NewLoop);
517
518   /// Returns (and creates if needed) the trip count of the widened loop.
519   Value *getOrCreateVectorTripCount(Loop *NewLoop);
520
521   /// Emit a bypass check to see if the trip count would overflow, or we
522   /// wouldn't have enough iterations to execute one vector loop.
523   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
524   /// Emit a bypass check to see if the vector trip count is nonzero.
525   void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
526   /// Emit a bypass check to see if all of the SCEV assumptions we've
527   /// had to make are correct.
528   void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
529   /// Emit bypass checks to check any memory assumptions we may have made.
530   void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
531
532   /// Add additional metadata to \p To that was not present on \p Orig.
533   ///
534   /// Currently this is used to add the noalias annotations based on the
535   /// inserted memchecks.  Use this for instructions that are *cloned* into the
536   /// vector loop.
537   void addNewMetadata(Instruction *To, const Instruction *Orig);
538
539   /// Add metadata from one instruction to another.
540   ///
541   /// This includes both the original MDs from \p From and additional ones (\see
542   /// addNewMetadata).  Use this for *newly created* instructions in the vector
543   /// loop.
544   void addMetadata(Instruction *To, Instruction *From);
545
546   /// \brief Similar to the previous function but it adds the metadata to a
547   /// vector of instructions.
548   void addMetadata(ArrayRef<Value *> To, Instruction *From);
549
550   /// This is a helper class that holds the vectorizer state. It maps scalar
551   /// instructions to vector instructions. When the code is 'unrolled' then
552   /// then a single scalar value is mapped to multiple vector parts. The parts
553   /// are stored in the VectorPart type.
554   struct ValueMap {
555     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
556     /// are mapped.
557     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
558
559     /// \return True if 'Key' is saved in the Value Map.
560     bool has(Value *Key) const { return MapStorage.count(Key); }
561
562     /// Initializes a new entry in the map. Sets all of the vector parts to the
563     /// save value in 'Val'.
564     /// \return A reference to a vector with splat values.
565     VectorParts &splat(Value *Key, Value *Val) {
566       VectorParts &Entry = MapStorage[Key];
567       Entry.assign(UF, Val);
568       return Entry;
569     }
570
571     ///\return A reference to the value that is stored at 'Key'.
572     VectorParts &get(Value *Key) {
573       VectorParts &Entry = MapStorage[Key];
574       if (Entry.empty())
575         Entry.resize(UF);
576       assert(Entry.size() == UF);
577       return Entry;
578     }
579
580   private:
581     /// The unroll factor. Each entry in the map stores this number of vector
582     /// elements.
583     unsigned UF;
584
585     /// Map storage. We use std::map and not DenseMap because insertions to a
586     /// dense map invalidates its iterators.
587     std::map<Value *, VectorParts> MapStorage;
588   };
589
590   /// The original loop.
591   Loop *OrigLoop;
592   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
593   /// dynamic knowledge to simplify SCEV expressions and converts them to a
594   /// more usable form.
595   PredicatedScalarEvolution &PSE;
596   /// Loop Info.
597   LoopInfo *LI;
598   /// Dominator Tree.
599   DominatorTree *DT;
600   /// Alias Analysis.
601   AliasAnalysis *AA;
602   /// Target Library Info.
603   const TargetLibraryInfo *TLI;
604   /// Target Transform Info.
605   const TargetTransformInfo *TTI;
606   /// Assumption Cache.
607   AssumptionCache *AC;
608
609   /// \brief LoopVersioning.  It's only set up (non-null) if memchecks were
610   /// used.
611   ///
612   /// This is currently only used to add no-alias metadata based on the
613   /// memchecks.  The actually versioning is performed manually.
614   std::unique_ptr<LoopVersioning> LVer;
615
616   /// The vectorization SIMD factor to use. Each vector will have this many
617   /// vector elements.
618   unsigned VF;
619
620 protected:
621   /// The vectorization unroll factor to use. Each scalar is vectorized to this
622   /// many different vector instructions.
623   unsigned UF;
624
625   /// The builder that we use
626   IRBuilder<> Builder;
627
628   // --- Vectorization state ---
629
630   /// The vector-loop preheader.
631   BasicBlock *LoopVectorPreHeader;
632   /// The scalar-loop preheader.
633   BasicBlock *LoopScalarPreHeader;
634   /// Middle Block between the vector and the scalar.
635   BasicBlock *LoopMiddleBlock;
636   /// The ExitBlock of the scalar loop.
637   BasicBlock *LoopExitBlock;
638   /// The vector loop body.
639   BasicBlock *LoopVectorBody;
640   /// The scalar loop body.
641   BasicBlock *LoopScalarBody;
642   /// A list of all bypass blocks. The first block is the entry of the loop.
643   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
644
645   /// The new Induction variable which was added to the new block.
646   PHINode *Induction;
647   /// The induction variable of the old basic block.
648   PHINode *OldInduction;
649   /// Maps scalars to widened vectors.
650   ValueMap WidenMap;
651
652   /// A map of induction variables from the original loop to their
653   /// corresponding VF * UF scalarized values in the vectorized loop. The
654   /// purpose of ScalarIVMap is similar to that of WidenMap. Whereas WidenMap
655   /// maps original loop values to their vector versions in the new loop,
656   /// ScalarIVMap maps induction variables from the original loop that are not
657   /// vectorized to their scalar equivalents in the vector loop. Maintaining a
658   /// separate map for scalarized induction variables allows us to avoid
659   /// unnecessary scalar-to-vector-to-scalar conversions.
660   DenseMap<Value *, SmallVector<Value *, 8>> ScalarIVMap;
661
662   /// Store instructions that should be predicated, as a pair
663   ///   <StoreInst, Predicate>
664   SmallVector<std::pair<StoreInst *, Value *>, 4> PredicatedStores;
665   EdgeMaskCache MaskCache;
666   /// Trip count of the original loop.
667   Value *TripCount;
668   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
669   Value *VectorTripCount;
670
671   /// Map of scalar integer values to the smallest bitwidth they can be legally
672   /// represented as. The vector equivalents of these values should be truncated
673   /// to this type.
674   const MapVector<Instruction *, uint64_t> *MinBWs;
675
676   /// A set of values that should not be widened. This is taken from
677   /// VecValuesToIgnore in the cost model.
678   SmallPtrSetImpl<const Value *> *ValuesNotWidened;
679
680   LoopVectorizationLegality *Legal;
681
682   // Record whether runtime checks are added.
683   bool AddedSafetyChecks;
684 };
685
686 class InnerLoopUnroller : public InnerLoopVectorizer {
687 public:
688   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
689                     LoopInfo *LI, DominatorTree *DT,
690                     const TargetLibraryInfo *TLI,
691                     const TargetTransformInfo *TTI, AssumptionCache *AC,
692                     unsigned UnrollFactor)
693       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, 1,
694                             UnrollFactor) {}
695
696 private:
697   void scalarizeInstruction(Instruction *Instr,
698                             bool IfPredicateStore = false) override;
699   void vectorizeMemoryInstruction(Instruction *Instr) override;
700   Value *getBroadcastInstrs(Value *V) override;
701   Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
702   Value *reverseVector(Value *Vec) override;
703 };
704
705 /// \brief Look for a meaningful debug location on the instruction or it's
706 /// operands.
707 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
708   if (!I)
709     return I;
710
711   DebugLoc Empty;
712   if (I->getDebugLoc() != Empty)
713     return I;
714
715   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
716     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
717       if (OpInst->getDebugLoc() != Empty)
718         return OpInst;
719   }
720
721   return I;
722 }
723
724 /// \brief Set the debug location in the builder using the debug location in the
725 /// instruction.
726 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
727   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
728     B.SetCurrentDebugLocation(Inst->getDebugLoc());
729   else
730     B.SetCurrentDebugLocation(DebugLoc());
731 }
732
733 #ifndef NDEBUG
734 /// \return string containing a file name and a line # for the given loop.
735 static std::string getDebugLocString(const Loop *L) {
736   std::string Result;
737   if (L) {
738     raw_string_ostream OS(Result);
739     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
740       LoopDbgLoc.print(OS);
741     else
742       // Just print the module name.
743       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
744     OS.flush();
745   }
746   return Result;
747 }
748 #endif
749
750 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
751                                          const Instruction *Orig) {
752   // If the loop was versioned with memchecks, add the corresponding no-alias
753   // metadata.
754   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
755     LVer->annotateInstWithNoAlias(To, Orig);
756 }
757
758 void InnerLoopVectorizer::addMetadata(Instruction *To,
759                                       Instruction *From) {
760   propagateMetadata(To, From);
761   addNewMetadata(To, From);
762 }
763
764 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
765                                       Instruction *From) {
766   for (Value *V : To) {
767     if (Instruction *I = dyn_cast<Instruction>(V))
768       addMetadata(I, From);
769   }
770 }
771
772 /// \brief The group of interleaved loads/stores sharing the same stride and
773 /// close to each other.
774 ///
775 /// Each member in this group has an index starting from 0, and the largest
776 /// index should be less than interleaved factor, which is equal to the absolute
777 /// value of the access's stride.
778 ///
779 /// E.g. An interleaved load group of factor 4:
780 ///        for (unsigned i = 0; i < 1024; i+=4) {
781 ///          a = A[i];                           // Member of index 0
782 ///          b = A[i+1];                         // Member of index 1
783 ///          d = A[i+3];                         // Member of index 3
784 ///          ...
785 ///        }
786 ///
787 ///      An interleaved store group of factor 4:
788 ///        for (unsigned i = 0; i < 1024; i+=4) {
789 ///          ...
790 ///          A[i]   = a;                         // Member of index 0
791 ///          A[i+1] = b;                         // Member of index 1
792 ///          A[i+2] = c;                         // Member of index 2
793 ///          A[i+3] = d;                         // Member of index 3
794 ///        }
795 ///
796 /// Note: the interleaved load group could have gaps (missing members), but
797 /// the interleaved store group doesn't allow gaps.
798 class InterleaveGroup {
799 public:
800   InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
801       : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
802     assert(Align && "The alignment should be non-zero");
803
804     Factor = std::abs(Stride);
805     assert(Factor > 1 && "Invalid interleave factor");
806
807     Reverse = Stride < 0;
808     Members[0] = Instr;
809   }
810
811   bool isReverse() const { return Reverse; }
812   unsigned getFactor() const { return Factor; }
813   unsigned getAlignment() const { return Align; }
814   unsigned getNumMembers() const { return Members.size(); }
815
816   /// \brief Try to insert a new member \p Instr with index \p Index and
817   /// alignment \p NewAlign. The index is related to the leader and it could be
818   /// negative if it is the new leader.
819   ///
820   /// \returns false if the instruction doesn't belong to the group.
821   bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
822     assert(NewAlign && "The new member's alignment should be non-zero");
823
824     int Key = Index + SmallestKey;
825
826     // Skip if there is already a member with the same index.
827     if (Members.count(Key))
828       return false;
829
830     if (Key > LargestKey) {
831       // The largest index is always less than the interleave factor.
832       if (Index >= static_cast<int>(Factor))
833         return false;
834
835       LargestKey = Key;
836     } else if (Key < SmallestKey) {
837       // The largest index is always less than the interleave factor.
838       if (LargestKey - Key >= static_cast<int>(Factor))
839         return false;
840
841       SmallestKey = Key;
842     }
843
844     // It's always safe to select the minimum alignment.
845     Align = std::min(Align, NewAlign);
846     Members[Key] = Instr;
847     return true;
848   }
849
850   /// \brief Get the member with the given index \p Index
851   ///
852   /// \returns nullptr if contains no such member.
853   Instruction *getMember(unsigned Index) const {
854     int Key = SmallestKey + Index;
855     if (!Members.count(Key))
856       return nullptr;
857
858     return Members.find(Key)->second;
859   }
860
861   /// \brief Get the index for the given member. Unlike the key in the member
862   /// map, the index starts from 0.
863   unsigned getIndex(Instruction *Instr) const {
864     for (auto I : Members)
865       if (I.second == Instr)
866         return I.first - SmallestKey;
867
868     llvm_unreachable("InterleaveGroup contains no such member");
869   }
870
871   Instruction *getInsertPos() const { return InsertPos; }
872   void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
873
874 private:
875   unsigned Factor; // Interleave Factor.
876   bool Reverse;
877   unsigned Align;
878   DenseMap<int, Instruction *> Members;
879   int SmallestKey;
880   int LargestKey;
881
882   // To avoid breaking dependences, vectorized instructions of an interleave
883   // group should be inserted at either the first load or the last store in
884   // program order.
885   //
886   // E.g. %even = load i32             // Insert Position
887   //      %add = add i32 %even         // Use of %even
888   //      %odd = load i32
889   //
890   //      store i32 %even
891   //      %odd = add i32               // Def of %odd
892   //      store i32 %odd               // Insert Position
893   Instruction *InsertPos;
894 };
895
896 /// \brief Drive the analysis of interleaved memory accesses in the loop.
897 ///
898 /// Use this class to analyze interleaved accesses only when we can vectorize
899 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
900 /// on interleaved accesses is unsafe.
901 ///
902 /// The analysis collects interleave groups and records the relationships
903 /// between the member and the group in a map.
904 class InterleavedAccessInfo {
905 public:
906   InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
907                         DominatorTree *DT, LoopInfo *LI)
908       : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(nullptr),
909         RequiresScalarEpilogue(false) {}
910
911   ~InterleavedAccessInfo() {
912     SmallSet<InterleaveGroup *, 4> DelSet;
913     // Avoid releasing a pointer twice.
914     for (auto &I : InterleaveGroupMap)
915       DelSet.insert(I.second);
916     for (auto *Ptr : DelSet)
917       delete Ptr;
918   }
919
920   /// \brief Analyze the interleaved accesses and collect them in interleave
921   /// groups. Substitute symbolic strides using \p Strides.
922   void analyzeInterleaving(const ValueToValueMap &Strides);
923
924   /// \brief Check if \p Instr belongs to any interleave group.
925   bool isInterleaved(Instruction *Instr) const {
926     return InterleaveGroupMap.count(Instr);
927   }
928
929   /// \brief Return the maximum interleave factor of all interleaved groups.
930   unsigned getMaxInterleaveFactor() const {
931     unsigned MaxFactor = 1;
932     for (auto &Entry : InterleaveGroupMap)
933       MaxFactor = std::max(MaxFactor, Entry.second->getFactor());
934     return MaxFactor;
935   }
936
937   /// \brief Get the interleave group that \p Instr belongs to.
938   ///
939   /// \returns nullptr if doesn't have such group.
940   InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
941     if (InterleaveGroupMap.count(Instr))
942       return InterleaveGroupMap.find(Instr)->second;
943     return nullptr;
944   }
945
946   /// \brief Returns true if an interleaved group that may access memory
947   /// out-of-bounds requires a scalar epilogue iteration for correctness.
948   bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
949
950   /// \brief Initialize the LoopAccessInfo used for dependence checking.
951   void setLAI(const LoopAccessInfo *Info) { LAI = Info; }
952
953 private:
954   /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
955   /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
956   /// The interleaved access analysis can also add new predicates (for example
957   /// by versioning strides of pointers).
958   PredicatedScalarEvolution &PSE;
959   Loop *TheLoop;
960   DominatorTree *DT;
961   LoopInfo *LI;
962   const LoopAccessInfo *LAI;
963
964   /// True if the loop may contain non-reversed interleaved groups with
965   /// out-of-bounds accesses. We ensure we don't speculatively access memory
966   /// out-of-bounds by executing at least one scalar epilogue iteration.
967   bool RequiresScalarEpilogue;
968
969   /// Holds the relationships between the members and the interleave group.
970   DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
971
972   /// Holds dependences among the memory accesses in the loop. It maps a source
973   /// access to a set of dependent sink accesses.
974   DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
975
976   /// \brief The descriptor for a strided memory access.
977   struct StrideDescriptor {
978     StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
979                      unsigned Align)
980         : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
981
982     StrideDescriptor() = default;
983
984     // The access's stride. It is negative for a reverse access.
985     int64_t Stride = 0;
986     const SCEV *Scev = nullptr; // The scalar expression of this access
987     uint64_t Size = 0;          // The size of the memory object.
988     unsigned Align = 0;         // The alignment of this access.
989   };
990
991   /// \brief A type for holding instructions and their stride descriptors.
992   typedef std::pair<Instruction *, StrideDescriptor> StrideEntry;
993
994   /// \brief Create a new interleave group with the given instruction \p Instr,
995   /// stride \p Stride and alignment \p Align.
996   ///
997   /// \returns the newly created interleave group.
998   InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
999                                          unsigned Align) {
1000     assert(!InterleaveGroupMap.count(Instr) &&
1001            "Already in an interleaved access group");
1002     InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
1003     return InterleaveGroupMap[Instr];
1004   }
1005
1006   /// \brief Release the group and remove all the relationships.
1007   void releaseGroup(InterleaveGroup *Group) {
1008     for (unsigned i = 0; i < Group->getFactor(); i++)
1009       if (Instruction *Member = Group->getMember(i))
1010         InterleaveGroupMap.erase(Member);
1011
1012     delete Group;
1013   }
1014
1015   /// \brief Collect all the accesses with a constant stride in program order.
1016   void collectConstStrideAccesses(
1017       MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
1018       const ValueToValueMap &Strides);
1019
1020   /// \brief Returns true if \p Stride is allowed in an interleaved group.
1021   static bool isStrided(int Stride) {
1022     unsigned Factor = std::abs(Stride);
1023     return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1024   }
1025
1026   /// \brief Returns true if \p BB is a predicated block.
1027   bool isPredicated(BasicBlock *BB) const {
1028     return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1029   }
1030
1031   /// \brief Returns true if LoopAccessInfo can be used for dependence queries.
1032   bool areDependencesValid() const {
1033     return LAI && LAI->getDepChecker().getDependences();
1034   }
1035
1036   /// \brief Returns true if memory accesses \p A and \p B can be reordered, if
1037   /// necessary, when constructing interleaved groups.
1038   ///
1039   /// \p A must precede \p B in program order. We return false if reordering is
1040   /// not necessary or is prevented because \p A and \p B may be dependent.
1041   bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1042                                                  StrideEntry *B) const {
1043
1044     // Code motion for interleaved accesses can potentially hoist strided loads
1045     // and sink strided stores. The code below checks the legality of the
1046     // following two conditions:
1047     //
1048     // 1. Potentially moving a strided load (B) before any store (A) that
1049     //    precedes B, or
1050     //
1051     // 2. Potentially moving a strided store (A) after any load or store (B)
1052     //    that A precedes.
1053     //
1054     // It's legal to reorder A and B if we know there isn't a dependence from A
1055     // to B. Note that this determination is conservative since some
1056     // dependences could potentially be reordered safely.
1057
1058     // A is potentially the source of a dependence.
1059     auto *Src = A->first;
1060     auto SrcDes = A->second;
1061
1062     // B is potentially the sink of a dependence.
1063     auto *Sink = B->first;
1064     auto SinkDes = B->second;
1065
1066     // Code motion for interleaved accesses can't violate WAR dependences.
1067     // Thus, reordering is legal if the source isn't a write.
1068     if (!Src->mayWriteToMemory())
1069       return true;
1070
1071     // At least one of the accesses must be strided.
1072     if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1073       return true;
1074
1075     // If dependence information is not available from LoopAccessInfo,
1076     // conservatively assume the instructions can't be reordered.
1077     if (!areDependencesValid())
1078       return false;
1079
1080     // If we know there is a dependence from source to sink, assume the
1081     // instructions can't be reordered. Otherwise, reordering is legal.
1082     return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
1083   }
1084
1085   /// \brief Collect the dependences from LoopAccessInfo.
1086   ///
1087   /// We process the dependences once during the interleaved access analysis to
1088   /// enable constant-time dependence queries.
1089   void collectDependences() {
1090     if (!areDependencesValid())
1091       return;
1092     auto *Deps = LAI->getDepChecker().getDependences();
1093     for (auto Dep : *Deps)
1094       Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1095   }
1096 };
1097
1098 /// Utility class for getting and setting loop vectorizer hints in the form
1099 /// of loop metadata.
1100 /// This class keeps a number of loop annotations locally (as member variables)
1101 /// and can, upon request, write them back as metadata on the loop. It will
1102 /// initially scan the loop for existing metadata, and will update the local
1103 /// values based on information in the loop.
1104 /// We cannot write all values to metadata, as the mere presence of some info,
1105 /// for example 'force', means a decision has been made. So, we need to be
1106 /// careful NOT to add them if the user hasn't specifically asked so.
1107 class LoopVectorizeHints {
1108   enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE };
1109
1110   /// Hint - associates name and validation with the hint value.
1111   struct Hint {
1112     const char *Name;
1113     unsigned Value; // This may have to change for non-numeric values.
1114     HintKind Kind;
1115
1116     Hint(const char *Name, unsigned Value, HintKind Kind)
1117         : Name(Name), Value(Value), Kind(Kind) {}
1118
1119     bool validate(unsigned Val) {
1120       switch (Kind) {
1121       case HK_WIDTH:
1122         return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1123       case HK_UNROLL:
1124         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1125       case HK_FORCE:
1126         return (Val <= 1);
1127       }
1128       return false;
1129     }
1130   };
1131
1132   /// Vectorization width.
1133   Hint Width;
1134   /// Vectorization interleave factor.
1135   Hint Interleave;
1136   /// Vectorization forced
1137   Hint Force;
1138
1139   /// Return the loop metadata prefix.
1140   static StringRef Prefix() { return "llvm.loop."; }
1141
1142   /// True if there is any unsafe math in the loop.
1143   bool PotentiallyUnsafe;
1144
1145 public:
1146   enum ForceKind {
1147     FK_Undefined = -1, ///< Not selected.
1148     FK_Disabled = 0,   ///< Forcing disabled.
1149     FK_Enabled = 1,    ///< Forcing enabled.
1150   };
1151
1152   LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1153       : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1154               HK_WIDTH),
1155         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1156         Force("vectorize.enable", FK_Undefined, HK_FORCE),
1157         PotentiallyUnsafe(false), TheLoop(L) {
1158     // Populate values with existing loop metadata.
1159     getHintsFromMetadata();
1160
1161     // force-vector-interleave overrides DisableInterleaving.
1162     if (VectorizerParams::isInterleaveForced())
1163       Interleave.Value = VectorizerParams::VectorizationInterleave;
1164
1165     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1166           << "LV: Interleaving disabled by the pass manager\n");
1167   }
1168
1169   /// Mark the loop L as already vectorized by setting the width to 1.
1170   void setAlreadyVectorized() {
1171     Width.Value = Interleave.Value = 1;
1172     Hint Hints[] = {Width, Interleave};
1173     writeHintsToMetadata(Hints);
1174   }
1175
1176   bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
1177     if (getForce() == LoopVectorizeHints::FK_Disabled) {
1178       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1179       emitOptimizationRemarkAnalysis(F->getContext(),
1180                                      vectorizeAnalysisPassName(), *F,
1181                                      L->getStartLoc(), emitRemark());
1182       return false;
1183     }
1184
1185     if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1186       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1187       emitOptimizationRemarkAnalysis(F->getContext(),
1188                                      vectorizeAnalysisPassName(), *F,
1189                                      L->getStartLoc(), emitRemark());
1190       return false;
1191     }
1192
1193     if (getWidth() == 1 && getInterleave() == 1) {
1194       // FIXME: Add a separate metadata to indicate when the loop has already
1195       // been vectorized instead of setting width and count to 1.
1196       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1197       // FIXME: Add interleave.disable metadata. This will allow
1198       // vectorize.disable to be used without disabling the pass and errors
1199       // to differentiate between disabled vectorization and a width of 1.
1200       emitOptimizationRemarkAnalysis(
1201           F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
1202           "loop not vectorized: vectorization and interleaving are explicitly "
1203           "disabled, or vectorize width and interleave count are both set to "
1204           "1");
1205       return false;
1206     }
1207
1208     return true;
1209   }
1210
1211   /// Dumps all the hint information.
1212   std::string emitRemark() const {
1213     VectorizationReport R;
1214     if (Force.Value == LoopVectorizeHints::FK_Disabled)
1215       R << "vectorization is explicitly disabled";
1216     else {
1217       R << "use -Rpass-analysis=loop-vectorize for more info";
1218       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1219         R << " (Force=true";
1220         if (Width.Value != 0)
1221           R << ", Vector Width=" << Width.Value;
1222         if (Interleave.Value != 0)
1223           R << ", Interleave Count=" << Interleave.Value;
1224         R << ")";
1225       }
1226     }
1227
1228     return R.str();
1229   }
1230
1231   unsigned getWidth() const { return Width.Value; }
1232   unsigned getInterleave() const { return Interleave.Value; }
1233   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1234
1235   /// \brief If hints are provided that force vectorization, use the AlwaysPrint
1236   /// pass name to force the frontend to print the diagnostic.
1237   const char *vectorizeAnalysisPassName() const {
1238     if (getWidth() == 1)
1239       return LV_NAME;
1240     if (getForce() == LoopVectorizeHints::FK_Disabled)
1241       return LV_NAME;
1242     if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1243       return LV_NAME;
1244     return DiagnosticInfoOptimizationRemarkAnalysis::AlwaysPrint;
1245   }
1246
1247   bool allowReordering() const {
1248     // When enabling loop hints are provided we allow the vectorizer to change
1249     // the order of operations that is given by the scalar loop. This is not
1250     // enabled by default because can be unsafe or inefficient. For example,
1251     // reordering floating-point operations will change the way round-off
1252     // error accumulates in the loop.
1253     return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1254   }
1255
1256   bool isPotentiallyUnsafe() const {
1257     // Avoid FP vectorization if the target is unsure about proper support.
1258     // This may be related to the SIMD unit in the target not handling
1259     // IEEE 754 FP ops properly, or bad single-to-double promotions.
1260     // Otherwise, a sequence of vectorized loops, even without reduction,
1261     // could lead to different end results on the destination vectors.
1262     return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1263   }
1264
1265   void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
1266
1267 private:
1268   /// Find hints specified in the loop metadata and update local values.
1269   void getHintsFromMetadata() {
1270     MDNode *LoopID = TheLoop->getLoopID();
1271     if (!LoopID)
1272       return;
1273
1274     // First operand should refer to the loop id itself.
1275     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1276     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1277
1278     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1279       const MDString *S = nullptr;
1280       SmallVector<Metadata *, 4> Args;
1281
1282       // The expected hint is either a MDString or a MDNode with the first
1283       // operand a MDString.
1284       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1285         if (!MD || MD->getNumOperands() == 0)
1286           continue;
1287         S = dyn_cast<MDString>(MD->getOperand(0));
1288         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1289           Args.push_back(MD->getOperand(i));
1290       } else {
1291         S = dyn_cast<MDString>(LoopID->getOperand(i));
1292         assert(Args.size() == 0 && "too many arguments for MDString");
1293       }
1294
1295       if (!S)
1296         continue;
1297
1298       // Check if the hint starts with the loop metadata prefix.
1299       StringRef Name = S->getString();
1300       if (Args.size() == 1)
1301         setHint(Name, Args[0]);
1302     }
1303   }
1304
1305   /// Checks string hint with one operand and set value if valid.
1306   void setHint(StringRef Name, Metadata *Arg) {
1307     if (!Name.startswith(Prefix()))
1308       return;
1309     Name = Name.substr(Prefix().size(), StringRef::npos);
1310
1311     const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1312     if (!C)
1313       return;
1314     unsigned Val = C->getZExtValue();
1315
1316     Hint *Hints[] = {&Width, &Interleave, &Force};
1317     for (auto H : Hints) {
1318       if (Name == H->Name) {
1319         if (H->validate(Val))
1320           H->Value = Val;
1321         else
1322           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1323         break;
1324       }
1325     }
1326   }
1327
1328   /// Create a new hint from name / value pair.
1329   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1330     LLVMContext &Context = TheLoop->getHeader()->getContext();
1331     Metadata *MDs[] = {MDString::get(Context, Name),
1332                        ConstantAsMetadata::get(
1333                            ConstantInt::get(Type::getInt32Ty(Context), V))};
1334     return MDNode::get(Context, MDs);
1335   }
1336
1337   /// Matches metadata with hint name.
1338   bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1339     MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
1340     if (!Name)
1341       return false;
1342
1343     for (auto H : HintTypes)
1344       if (Name->getString().endswith(H.Name))
1345         return true;
1346     return false;
1347   }
1348
1349   /// Sets current hints into loop metadata, keeping other values intact.
1350   void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1351     if (HintTypes.size() == 0)
1352       return;
1353
1354     // Reserve the first element to LoopID (see below).
1355     SmallVector<Metadata *, 4> MDs(1);
1356     // If the loop already has metadata, then ignore the existing operands.
1357     MDNode *LoopID = TheLoop->getLoopID();
1358     if (LoopID) {
1359       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1360         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1361         // If node in update list, ignore old value.
1362         if (!matchesHintMetadataName(Node, HintTypes))
1363           MDs.push_back(Node);
1364       }
1365     }
1366
1367     // Now, add the missing hints.
1368     for (auto H : HintTypes)
1369       MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1370
1371     // Replace current metadata node with new one.
1372     LLVMContext &Context = TheLoop->getHeader()->getContext();
1373     MDNode *NewLoopID = MDNode::get(Context, MDs);
1374     // Set operand 0 to refer to the loop id itself.
1375     NewLoopID->replaceOperandWith(0, NewLoopID);
1376
1377     TheLoop->setLoopID(NewLoopID);
1378   }
1379
1380   /// The loop these hints belong to.
1381   const Loop *TheLoop;
1382 };
1383
1384 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1385                              const LoopVectorizeHints &Hints,
1386                              const LoopAccessReport &Message) {
1387   const char *Name = Hints.vectorizeAnalysisPassName();
1388   LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1389 }
1390
1391 static void emitMissedWarning(Function *F, Loop *L,
1392                               const LoopVectorizeHints &LH) {
1393   emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1394                                LH.emitRemark());
1395
1396   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1397     if (LH.getWidth() != 1)
1398       emitLoopVectorizeWarning(
1399           F->getContext(), *F, L->getStartLoc(),
1400           "failed explicitly specified loop vectorization");
1401     else if (LH.getInterleave() != 1)
1402       emitLoopInterleaveWarning(
1403           F->getContext(), *F, L->getStartLoc(),
1404           "failed explicitly specified loop interleaving");
1405   }
1406 }
1407
1408 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1409 /// to what vectorization factor.
1410 /// This class does not look at the profitability of vectorization, only the
1411 /// legality. This class has two main kinds of checks:
1412 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1413 ///   will change the order of memory accesses in a way that will change the
1414 ///   correctness of the program.
1415 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1416 /// checks for a number of different conditions, such as the availability of a
1417 /// single induction variable, that all types are supported and vectorize-able,
1418 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1419 /// This class is also used by InnerLoopVectorizer for identifying
1420 /// induction variable and the different reduction variables.
1421 class LoopVectorizationLegality {
1422 public:
1423   LoopVectorizationLegality(
1424       Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT,
1425       TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F,
1426       const TargetTransformInfo *TTI,
1427       std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
1428       LoopVectorizationRequirements *R, LoopVectorizeHints *H)
1429       : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TheFunction(F),
1430         TTI(TTI), DT(DT), GetLAA(GetLAA), LAI(nullptr),
1431         InterleaveInfo(PSE, L, DT, LI), Induction(nullptr),
1432         WidestIndTy(nullptr), HasFunNoNaNAttr(false), Requirements(R),
1433         Hints(H) {}
1434
1435   /// ReductionList contains the reduction descriptors for all
1436   /// of the reductions that were found in the loop.
1437   typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1438
1439   /// InductionList saves induction variables and maps them to the
1440   /// induction descriptor.
1441   typedef MapVector<PHINode *, InductionDescriptor> InductionList;
1442
1443   /// RecurrenceSet contains the phi nodes that are recurrences other than
1444   /// inductions and reductions.
1445   typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet;
1446
1447   /// Returns true if it is legal to vectorize this loop.
1448   /// This does not mean that it is profitable to vectorize this
1449   /// loop, only that it is legal to do so.
1450   bool canVectorize();
1451
1452   /// Returns the Induction variable.
1453   PHINode *getInduction() { return Induction; }
1454
1455   /// Returns the reduction variables found in the loop.
1456   ReductionList *getReductionVars() { return &Reductions; }
1457
1458   /// Returns the induction variables found in the loop.
1459   InductionList *getInductionVars() { return &Inductions; }
1460
1461   /// Return the first-order recurrences found in the loop.
1462   RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
1463
1464   /// Returns the widest induction type.
1465   Type *getWidestInductionType() { return WidestIndTy; }
1466
1467   /// Returns True if V is an induction variable in this loop.
1468   bool isInductionVariable(const Value *V);
1469
1470   /// Returns True if PN is a reduction variable in this loop.
1471   bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
1472
1473   /// Returns True if Phi is a first-order recurrence in this loop.
1474   bool isFirstOrderRecurrence(const PHINode *Phi);
1475
1476   /// Return true if the block BB needs to be predicated in order for the loop
1477   /// to be vectorized.
1478   bool blockNeedsPredication(BasicBlock *BB);
1479
1480   /// Check if this pointer is consecutive when vectorizing. This happens
1481   /// when the last index of the GEP is the induction variable, or that the
1482   /// pointer itself is an induction variable.
1483   /// This check allows us to vectorize A[idx] into a wide load/store.
1484   /// Returns:
1485   /// 0 - Stride is unknown or non-consecutive.
1486   /// 1 - Address is consecutive.
1487   /// -1 - Address is consecutive, and decreasing.
1488   int isConsecutivePtr(Value *Ptr);
1489
1490   /// Returns true if the value V is uniform within the loop.
1491   bool isUniform(Value *V);
1492
1493   /// Returns true if this instruction will remain scalar after vectorization.
1494   bool isUniformAfterVectorization(Instruction *I) { return Uniforms.count(I); }
1495
1496   /// Returns the information that we collected about runtime memory check.
1497   const RuntimePointerChecking *getRuntimePointerChecking() const {
1498     return LAI->getRuntimePointerChecking();
1499   }
1500
1501   const LoopAccessInfo *getLAI() const { return LAI; }
1502
1503   /// \brief Check if \p Instr belongs to any interleaved access group.
1504   bool isAccessInterleaved(Instruction *Instr) {
1505     return InterleaveInfo.isInterleaved(Instr);
1506   }
1507
1508   /// \brief Return the maximum interleave factor of all interleaved groups.
1509   unsigned getMaxInterleaveFactor() const {
1510     return InterleaveInfo.getMaxInterleaveFactor();
1511   }
1512
1513   /// \brief Get the interleaved access group that \p Instr belongs to.
1514   const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1515     return InterleaveInfo.getInterleaveGroup(Instr);
1516   }
1517
1518   /// \brief Returns true if an interleaved group requires a scalar iteration
1519   /// to handle accesses with gaps.
1520   bool requiresScalarEpilogue() const {
1521     return InterleaveInfo.requiresScalarEpilogue();
1522   }
1523
1524   unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1525
1526   bool hasStride(Value *V) { return LAI->hasStride(V); }
1527
1528   /// Returns true if the target machine supports masked store operation
1529   /// for the given \p DataType and kind of access to \p Ptr.
1530   bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1531     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1532   }
1533   /// Returns true if the target machine supports masked load operation
1534   /// for the given \p DataType and kind of access to \p Ptr.
1535   bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1536     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1537   }
1538   /// Returns true if the target machine supports masked scatter operation
1539   /// for the given \p DataType.
1540   bool isLegalMaskedScatter(Type *DataType) {
1541     return TTI->isLegalMaskedScatter(DataType);
1542   }
1543   /// Returns true if the target machine supports masked gather operation
1544   /// for the given \p DataType.
1545   bool isLegalMaskedGather(Type *DataType) {
1546     return TTI->isLegalMaskedGather(DataType);
1547   }
1548
1549   /// Returns true if vector representation of the instruction \p I
1550   /// requires mask.
1551   bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
1552   unsigned getNumStores() const { return LAI->getNumStores(); }
1553   unsigned getNumLoads() const { return LAI->getNumLoads(); }
1554   unsigned getNumPredStores() const { return NumPredStores; }
1555
1556 private:
1557   /// Check if a single basic block loop is vectorizable.
1558   /// At this point we know that this is a loop with a constant trip count
1559   /// and we only need to check individual instructions.
1560   bool canVectorizeInstrs();
1561
1562   /// When we vectorize loops we may change the order in which
1563   /// we read and write from memory. This method checks if it is
1564   /// legal to vectorize the code, considering only memory constrains.
1565   /// Returns true if the loop is vectorizable
1566   bool canVectorizeMemory();
1567
1568   /// Return true if we can vectorize this loop using the IF-conversion
1569   /// transformation.
1570   bool canVectorizeWithIfConvert();
1571
1572   /// Collect the variables that need to stay uniform after vectorization.
1573   void collectLoopUniforms();
1574
1575   /// Return true if all of the instructions in the block can be speculatively
1576   /// executed. \p SafePtrs is a list of addresses that are known to be legal
1577   /// and we know that we can read from them without segfault.
1578   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1579
1580   /// Updates the vectorization state by adding \p Phi to the inductions list.
1581   /// This can set \p Phi as the main induction of the loop if \p Phi is a
1582   /// better choice for the main induction than the existing one.
1583   void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
1584                        SmallPtrSetImpl<Value *> &AllowedExit);
1585
1586   /// Report an analysis message to assist the user in diagnosing loops that are
1587   /// not vectorized.  These are handled as LoopAccessReport rather than
1588   /// VectorizationReport because the << operator of VectorizationReport returns
1589   /// LoopAccessReport.
1590   void emitAnalysis(const LoopAccessReport &Message) const {
1591     emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1592   }
1593
1594   /// \brief If an access has a symbolic strides, this maps the pointer value to
1595   /// the stride symbol.
1596   const ValueToValueMap *getSymbolicStrides() {
1597     // FIXME: Currently, the set of symbolic strides is sometimes queried before
1598     // it's collected.  This happens from canVectorizeWithIfConvert, when the
1599     // pointer is checked to reference consecutive elements suitable for a
1600     // masked access.
1601     return LAI ? &LAI->getSymbolicStrides() : nullptr;
1602   }
1603
1604   unsigned NumPredStores;
1605
1606   /// The loop that we evaluate.
1607   Loop *TheLoop;
1608   /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
1609   /// Applies dynamic knowledge to simplify SCEV expressions in the context
1610   /// of existing SCEV assumptions. The analysis will also add a minimal set
1611   /// of new predicates if this is required to enable vectorization and
1612   /// unrolling.
1613   PredicatedScalarEvolution &PSE;
1614   /// Target Library Info.
1615   TargetLibraryInfo *TLI;
1616   /// Parent function
1617   Function *TheFunction;
1618   /// Target Transform Info
1619   const TargetTransformInfo *TTI;
1620   /// Dominator Tree.
1621   DominatorTree *DT;
1622   // LoopAccess analysis.
1623   std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1624   // And the loop-accesses info corresponding to this loop.  This pointer is
1625   // null until canVectorizeMemory sets it up.
1626   const LoopAccessInfo *LAI;
1627
1628   /// The interleave access information contains groups of interleaved accesses
1629   /// with the same stride and close to each other.
1630   InterleavedAccessInfo InterleaveInfo;
1631
1632   //  ---  vectorization state --- //
1633
1634   /// Holds the integer induction variable. This is the counter of the
1635   /// loop.
1636   PHINode *Induction;
1637   /// Holds the reduction variables.
1638   ReductionList Reductions;
1639   /// Holds all of the induction variables that we found in the loop.
1640   /// Notice that inductions don't need to start at zero and that induction
1641   /// variables can be pointers.
1642   InductionList Inductions;
1643   /// Holds the phi nodes that are first-order recurrences.
1644   RecurrenceSet FirstOrderRecurrences;
1645   /// Holds the widest induction type encountered.
1646   Type *WidestIndTy;
1647
1648   /// Allowed outside users. This holds the induction and reduction
1649   /// vars which can be accessed from outside the loop.
1650   SmallPtrSet<Value *, 4> AllowedExit;
1651   /// This set holds the variables which are known to be uniform after
1652   /// vectorization.
1653   SmallPtrSet<Instruction *, 4> Uniforms;
1654
1655   /// Can we assume the absence of NaNs.
1656   bool HasFunNoNaNAttr;
1657
1658   /// Vectorization requirements that will go through late-evaluation.
1659   LoopVectorizationRequirements *Requirements;
1660
1661   /// Used to emit an analysis of any legality issues.
1662   LoopVectorizeHints *Hints;
1663
1664   /// While vectorizing these instructions we have to generate a
1665   /// call to the appropriate masked intrinsic
1666   SmallPtrSet<const Instruction *, 8> MaskedOp;
1667 };
1668
1669 /// LoopVectorizationCostModel - estimates the expected speedups due to
1670 /// vectorization.
1671 /// In many cases vectorization is not profitable. This can happen because of
1672 /// a number of reasons. In this class we mainly attempt to predict the
1673 /// expected speedup/slowdowns due to the supported instruction set. We use the
1674 /// TargetTransformInfo to query the different backends for the cost of
1675 /// different operations.
1676 class LoopVectorizationCostModel {
1677 public:
1678   LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1679                              LoopInfo *LI, LoopVectorizationLegality *Legal,
1680                              const TargetTransformInfo &TTI,
1681                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1682                              AssumptionCache *AC, const Function *F,
1683                              const LoopVectorizeHints *Hints)
1684       : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1685         AC(AC), TheFunction(F), Hints(Hints) {}
1686
1687   /// Information about vectorization costs
1688   struct VectorizationFactor {
1689     unsigned Width; // Vector width with best cost
1690     unsigned Cost;  // Cost of the loop with that width
1691   };
1692   /// \return The most profitable vectorization factor and the cost of that VF.
1693   /// This method checks every power of two up to VF. If UserVF is not ZERO
1694   /// then this vectorization factor will be selected if vectorization is
1695   /// possible.
1696   VectorizationFactor selectVectorizationFactor(bool OptForSize);
1697
1698   /// \return The size (in bits) of the smallest and widest types in the code
1699   /// that needs to be vectorized. We ignore values that remain scalar such as
1700   /// 64 bit loop indices.
1701   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1702
1703   /// \return The desired interleave count.
1704   /// If interleave count has been specified by metadata it will be returned.
1705   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1706   /// are the selected vectorization factor and the cost of the selected VF.
1707   unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1708                                  unsigned LoopCost);
1709
1710   /// \return The most profitable unroll factor.
1711   /// This method finds the best unroll-factor based on register pressure and
1712   /// other parameters. VF and LoopCost are the selected vectorization factor
1713   /// and the cost of the selected VF.
1714   unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1715                                   unsigned LoopCost);
1716
1717   /// \brief A struct that represents some properties of the register usage
1718   /// of a loop.
1719   struct RegisterUsage {
1720     /// Holds the number of loop invariant values that are used in the loop.
1721     unsigned LoopInvariantRegs;
1722     /// Holds the maximum number of concurrent live intervals in the loop.
1723     unsigned MaxLocalUsers;
1724     /// Holds the number of instructions in the loop.
1725     unsigned NumInstructions;
1726   };
1727
1728   /// \return Returns information about the register usages of the loop for the
1729   /// given vectorization factors.
1730   SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1731
1732   /// Collect values we want to ignore in the cost model.
1733   void collectValuesToIgnore();
1734
1735 private:
1736   /// The vectorization cost is a combination of the cost itself and a boolean
1737   /// indicating whether any of the contributing operations will actually
1738   /// operate on
1739   /// vector values after type legalization in the backend. If this latter value
1740   /// is
1741   /// false, then all operations will be scalarized (i.e. no vectorization has
1742   /// actually taken place).
1743   typedef std::pair<unsigned, bool> VectorizationCostTy;
1744
1745   /// Returns the expected execution cost. The unit of the cost does
1746   /// not matter because we use the 'cost' units to compare different
1747   /// vector widths. The cost that is returned is *not* normalized by
1748   /// the factor width.
1749   VectorizationCostTy expectedCost(unsigned VF);
1750
1751   /// Returns the execution time cost of an instruction for a given vector
1752   /// width. Vector width of one means scalar.
1753   VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
1754
1755   /// The cost-computation logic from getInstructionCost which provides
1756   /// the vector type as an output parameter.
1757   unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
1758
1759   /// Returns whether the instruction is a load or store and will be a emitted
1760   /// as a vector operation.
1761   bool isConsecutiveLoadOrStore(Instruction *I);
1762
1763   /// Report an analysis message to assist the user in diagnosing loops that are
1764   /// not vectorized.  These are handled as LoopAccessReport rather than
1765   /// VectorizationReport because the << operator of VectorizationReport returns
1766   /// LoopAccessReport.
1767   void emitAnalysis(const LoopAccessReport &Message) const {
1768     emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1769   }
1770
1771 public:
1772   /// Map of scalar integer values to the smallest bitwidth they can be legally
1773   /// represented as. The vector equivalents of these values should be truncated
1774   /// to this type.
1775   MapVector<Instruction *, uint64_t> MinBWs;
1776
1777   /// The loop that we evaluate.
1778   Loop *TheLoop;
1779   /// Predicated scalar evolution analysis.
1780   PredicatedScalarEvolution &PSE;
1781   /// Loop Info analysis.
1782   LoopInfo *LI;
1783   /// Vectorization legality.
1784   LoopVectorizationLegality *Legal;
1785   /// Vector target information.
1786   const TargetTransformInfo &TTI;
1787   /// Target Library Info.
1788   const TargetLibraryInfo *TLI;
1789   /// Demanded bits analysis.
1790   DemandedBits *DB;
1791   /// Assumption cache.
1792   AssumptionCache *AC;
1793   const Function *TheFunction;
1794   /// Loop Vectorize Hint.
1795   const LoopVectorizeHints *Hints;
1796   /// Values to ignore in the cost model.
1797   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1798   /// Values to ignore in the cost model when VF > 1.
1799   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1800 };
1801
1802 /// \brief This holds vectorization requirements that must be verified late in
1803 /// the process. The requirements are set by legalize and costmodel. Once
1804 /// vectorization has been determined to be possible and profitable the
1805 /// requirements can be verified by looking for metadata or compiler options.
1806 /// For example, some loops require FP commutativity which is only allowed if
1807 /// vectorization is explicitly specified or if the fast-math compiler option
1808 /// has been provided.
1809 /// Late evaluation of these requirements allows helpful diagnostics to be
1810 /// composed that tells the user what need to be done to vectorize the loop. For
1811 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1812 /// evaluation should be used only when diagnostics can generated that can be
1813 /// followed by a non-expert user.
1814 class LoopVectorizationRequirements {
1815 public:
1816   LoopVectorizationRequirements()
1817       : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1818
1819   void addUnsafeAlgebraInst(Instruction *I) {
1820     // First unsafe algebra instruction.
1821     if (!UnsafeAlgebraInst)
1822       UnsafeAlgebraInst = I;
1823   }
1824
1825   void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1826
1827   bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1828     const char *Name = Hints.vectorizeAnalysisPassName();
1829     bool Failed = false;
1830     if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1831       emitOptimizationRemarkAnalysisFPCommute(
1832           F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1833           VectorizationReport() << "cannot prove it is safe to reorder "
1834                                    "floating-point operations");
1835       Failed = true;
1836     }
1837
1838     // Test if runtime memcheck thresholds are exceeded.
1839     bool PragmaThresholdReached =
1840         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1841     bool ThresholdReached =
1842         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1843     if ((ThresholdReached && !Hints.allowReordering()) ||
1844         PragmaThresholdReached) {
1845       emitOptimizationRemarkAnalysisAliasing(
1846           F->getContext(), Name, *F, L->getStartLoc(),
1847           VectorizationReport()
1848               << "cannot prove it is safe to reorder memory operations");
1849       DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1850       Failed = true;
1851     }
1852
1853     return Failed;
1854   }
1855
1856 private:
1857   unsigned NumRuntimePointerChecks;
1858   Instruction *UnsafeAlgebraInst;
1859 };
1860
1861 static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1862   if (L.empty()) {
1863     if (!hasCyclesInLoopBody(L))
1864       V.push_back(&L);
1865     return;
1866   }
1867   for (Loop *InnerL : L)
1868     addAcyclicInnerLoop(*InnerL, V);
1869 }
1870
1871 /// The LoopVectorize Pass.
1872 struct LoopVectorize : public FunctionPass {
1873   /// Pass identification, replacement for typeid
1874   static char ID;
1875
1876   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1877       : FunctionPass(ID) {
1878     Impl.DisableUnrolling = NoUnrolling;
1879     Impl.AlwaysVectorize = AlwaysVectorize;
1880     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1881   }
1882
1883   LoopVectorizePass Impl;
1884
1885   bool runOnFunction(Function &F) override {
1886     if (skipFunction(F))
1887       return false;
1888
1889     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1890     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1891     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1892     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1893     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1894     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1895     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
1896     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1897     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1898     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
1899     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
1900
1901     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1902         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
1903
1904     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
1905                         GetLAA);
1906   }
1907
1908   void getAnalysisUsage(AnalysisUsage &AU) const override {
1909     AU.addRequired<AssumptionCacheTracker>();
1910     AU.addRequiredID(LoopSimplifyID);
1911     AU.addRequiredID(LCSSAID);
1912     AU.addRequired<BlockFrequencyInfoWrapperPass>();
1913     AU.addRequired<DominatorTreeWrapperPass>();
1914     AU.addRequired<LoopInfoWrapperPass>();
1915     AU.addRequired<ScalarEvolutionWrapperPass>();
1916     AU.addRequired<TargetTransformInfoWrapperPass>();
1917     AU.addRequired<AAResultsWrapperPass>();
1918     AU.addRequired<LoopAccessLegacyAnalysis>();
1919     AU.addRequired<DemandedBitsWrapperPass>();
1920     AU.addPreserved<LoopInfoWrapperPass>();
1921     AU.addPreserved<DominatorTreeWrapperPass>();
1922     AU.addPreserved<BasicAAWrapperPass>();
1923     AU.addPreserved<GlobalsAAWrapperPass>();
1924   }
1925 };
1926
1927 } // end anonymous namespace
1928
1929 //===----------------------------------------------------------------------===//
1930 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1931 // LoopVectorizationCostModel.
1932 //===----------------------------------------------------------------------===//
1933
1934 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1935   // We need to place the broadcast of invariant variables outside the loop.
1936   Instruction *Instr = dyn_cast<Instruction>(V);
1937   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
1938   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1939
1940   // Place the code for broadcasting invariant variables in the new preheader.
1941   IRBuilder<>::InsertPointGuard Guard(Builder);
1942   if (Invariant)
1943     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1944
1945   // Broadcast the scalar into all locations in the vector.
1946   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1947
1948   return Shuf;
1949 }
1950
1951 void InnerLoopVectorizer::createVectorIntInductionPHI(
1952     const InductionDescriptor &II, VectorParts &Entry, IntegerType *TruncType) {
1953   Value *Start = II.getStartValue();
1954   ConstantInt *Step = II.getConstIntStepValue();
1955   assert(Step && "Can not widen an IV with a non-constant step");
1956
1957   // Construct the initial value of the vector IV in the vector loop preheader
1958   auto CurrIP = Builder.saveIP();
1959   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1960   if (TruncType) {
1961     Step = ConstantInt::getSigned(TruncType, Step->getSExtValue());
1962     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
1963   }
1964   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
1965   Value *SteppedStart = getStepVector(SplatStart, 0, Step);
1966   Builder.restoreIP(CurrIP);
1967
1968   Value *SplatVF =
1969       ConstantVector::getSplat(VF, ConstantInt::getSigned(Start->getType(),
1970                                VF * Step->getSExtValue()));
1971   // We may need to add the step a number of times, depending on the unroll
1972   // factor. The last of those goes into the PHI.
1973   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
1974                                     &*LoopVectorBody->getFirstInsertionPt());
1975   Value *LastInduction = VecInd;
1976   for (unsigned Part = 0; Part < UF; ++Part) {
1977     Entry[Part] = LastInduction;
1978     LastInduction = Builder.CreateAdd(LastInduction, SplatVF, "step.add");
1979   }
1980
1981   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
1982   VecInd->addIncoming(LastInduction, LoopVectorBody);
1983 }
1984
1985 void InnerLoopVectorizer::widenIntInduction(PHINode *IV, VectorParts &Entry,
1986                                             TruncInst *Trunc) {
1987
1988   auto II = Legal->getInductionVars()->find(IV);
1989   assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
1990
1991   auto ID = II->second;
1992   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
1993
1994   // If a truncate instruction was provided, get the smaller type.
1995   auto *TruncType = Trunc ? cast<IntegerType>(Trunc->getType()) : nullptr;
1996
1997   // The step of the induction.
1998   Value *Step = nullptr;
1999
2000   // If the induction variable has a constant integer step value, go ahead and
2001   // get it now.
2002   if (ID.getConstIntStepValue())
2003     Step = ID.getConstIntStepValue();
2004
2005   // Try to create a new independent vector induction variable. If we can't
2006   // create the phi node, we will splat the scalar induction variable in each
2007   // loop iteration.
2008   if (VF > 1 && IV->getType() == Induction->getType() && Step &&
2009       !ValuesNotWidened->count(IV))
2010     return createVectorIntInductionPHI(ID, Entry, TruncType);
2011
2012   // The scalar value to broadcast. This will be derived from the canonical
2013   // induction variable.
2014   Value *ScalarIV = nullptr;
2015
2016   // Define the scalar induction variable and step values. If we were given a
2017   // truncation type, truncate the canonical induction variable and constant
2018   // step. Otherwise, derive these values from the induction descriptor.
2019   if (TruncType) {
2020     assert(Step && "Truncation requires constant integer step");
2021     auto StepInt = cast<ConstantInt>(Step)->getSExtValue();
2022     ScalarIV = Builder.CreateCast(Instruction::Trunc, Induction, TruncType);
2023     Step = ConstantInt::getSigned(TruncType, StepInt);
2024   } else {
2025     ScalarIV = Induction;
2026     auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2027     if (IV != OldInduction) {
2028       ScalarIV = Builder.CreateSExtOrTrunc(ScalarIV, IV->getType());
2029       ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
2030       ScalarIV->setName("offset.idx");
2031     }
2032     if (!Step) {
2033       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2034       Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2035                                &*Builder.GetInsertPoint());
2036     }
2037   }
2038
2039   // Splat the scalar induction variable, and build the necessary step vectors.
2040   Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2041   for (unsigned Part = 0; Part < UF; ++Part)
2042     Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
2043
2044   // If an induction variable is only used for counting loop iterations or
2045   // calculating addresses, it doesn't need to be widened. Create scalar steps
2046   // that can be used by instructions we will later scalarize. Note that the
2047   // addition of the scalar steps will not increase the number of instructions
2048   // in the loop in the common case prior to InstCombine. We will be trading
2049   // one vector extract for each scalar step.
2050   if (VF > 1 && ValuesNotWidened->count(IV)) {
2051     auto *EntryVal = Trunc ? cast<Value>(Trunc) : IV;
2052     buildScalarSteps(ScalarIV, Step, EntryVal);
2053   }
2054 }
2055
2056 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
2057                                           Value *Step) {
2058   assert(Val->getType()->isVectorTy() && "Must be a vector");
2059   assert(Val->getType()->getScalarType()->isIntegerTy() &&
2060          "Elem must be an integer");
2061   assert(Step->getType() == Val->getType()->getScalarType() &&
2062          "Step has wrong type");
2063   // Create the types.
2064   Type *ITy = Val->getType()->getScalarType();
2065   VectorType *Ty = cast<VectorType>(Val->getType());
2066   int VLen = Ty->getNumElements();
2067   SmallVector<Constant *, 8> Indices;
2068
2069   // Create a vector of consecutive numbers from zero to VF.
2070   for (int i = 0; i < VLen; ++i)
2071     Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
2072
2073   // Add the consecutive indices to the vector value.
2074   Constant *Cv = ConstantVector::get(Indices);
2075   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2076   Step = Builder.CreateVectorSplat(VLen, Step);
2077   assert(Step->getType() == Val->getType() && "Invalid step vec");
2078   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2079   // which can be found from the original scalar operations.
2080   Step = Builder.CreateMul(Cv, Step);
2081   return Builder.CreateAdd(Val, Step, "induction");
2082 }
2083
2084 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2085                                            Value *EntryVal) {
2086
2087   // We shouldn't have to build scalar steps if we aren't vectorizing.
2088   assert(VF > 1 && "VF should be greater than one");
2089
2090   // Get the value type and ensure it and the step have the same integer type.
2091   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2092   assert(ScalarIVTy->isIntegerTy() && ScalarIVTy == Step->getType() &&
2093          "Val and Step should have the same integer type");
2094
2095   // Compute the scalar steps and save the results in ScalarIVMap.
2096   for (unsigned Part = 0; Part < UF; ++Part)
2097     for (unsigned I = 0; I < VF; ++I) {
2098       auto *StartIdx = ConstantInt::get(ScalarIVTy, VF * Part + I);
2099       auto *Mul = Builder.CreateMul(StartIdx, Step);
2100       auto *Add = Builder.CreateAdd(ScalarIV, Mul);
2101       ScalarIVMap[EntryVal].push_back(Add);
2102     }
2103 }
2104
2105 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2106   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
2107   auto *SE = PSE.getSE();
2108   // Make sure that the pointer does not point to structs.
2109   if (Ptr->getType()->getPointerElementType()->isAggregateType())
2110     return 0;
2111
2112   // If this value is a pointer induction variable, we know it is consecutive.
2113   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
2114   if (Phi && Inductions.count(Phi)) {
2115     InductionDescriptor II = Inductions[Phi];
2116     return II.getConsecutiveDirection();
2117   }
2118
2119   GetElementPtrInst *Gep = getGEPInstruction(Ptr);
2120   if (!Gep)
2121     return 0;
2122
2123   unsigned NumOperands = Gep->getNumOperands();
2124   Value *GpPtr = Gep->getPointerOperand();
2125   // If this GEP value is a consecutive pointer induction variable and all of
2126   // the indices are constant, then we know it is consecutive.
2127   Phi = dyn_cast<PHINode>(GpPtr);
2128   if (Phi && Inductions.count(Phi)) {
2129
2130     // Make sure that the pointer does not point to structs.
2131     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
2132     if (GepPtrType->getElementType()->isAggregateType())
2133       return 0;
2134
2135     // Make sure that all of the index operands are loop invariant.
2136     for (unsigned i = 1; i < NumOperands; ++i)
2137       if (!SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop))
2138         return 0;
2139
2140     InductionDescriptor II = Inductions[Phi];
2141     return II.getConsecutiveDirection();
2142   }
2143
2144   unsigned InductionOperand = getGEPInductionOperand(Gep);
2145
2146   // Check that all of the gep indices are uniform except for our induction
2147   // operand.
2148   for (unsigned i = 0; i != NumOperands; ++i)
2149     if (i != InductionOperand &&
2150         !SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop))
2151       return 0;
2152
2153   // We can emit wide load/stores only if the last non-zero index is the
2154   // induction variable.
2155   const SCEV *Last = nullptr;
2156   if (!getSymbolicStrides() || !getSymbolicStrides()->count(Gep))
2157     Last = PSE.getSCEV(Gep->getOperand(InductionOperand));
2158   else {
2159     // Because of the multiplication by a stride we can have a s/zext cast.
2160     // We are going to replace this stride by 1 so the cast is safe to ignore.
2161     //
2162     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
2163     //  %0 = trunc i64 %indvars.iv to i32
2164     //  %mul = mul i32 %0, %Stride1
2165     //  %idxprom = zext i32 %mul to i64  << Safe cast.
2166     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
2167     //
2168     Last = replaceSymbolicStrideSCEV(PSE, *getSymbolicStrides(),
2169                                      Gep->getOperand(InductionOperand), Gep);
2170     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
2171       Last =
2172           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
2173               ? C->getOperand()
2174               : Last;
2175   }
2176   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
2177     const SCEV *Step = AR->getStepRecurrence(*SE);
2178
2179     // The memory is consecutive because the last index is consecutive
2180     // and all other indices are loop invariant.
2181     if (Step->isOne())
2182       return 1;
2183     if (Step->isAllOnesValue())
2184       return -1;
2185   }
2186
2187   return 0;
2188 }
2189
2190 bool LoopVectorizationLegality::isUniform(Value *V) {
2191   return LAI->isUniform(V);
2192 }
2193
2194 InnerLoopVectorizer::VectorParts &
2195 InnerLoopVectorizer::getVectorValue(Value *V) {
2196   assert(V != Induction && "The new induction variable should not be used.");
2197   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2198
2199   // If we have a stride that is replaced by one, do it here.
2200   if (Legal->hasStride(V))
2201     V = ConstantInt::get(V->getType(), 1);
2202
2203   // If we have this scalar in the map, return it.
2204   if (WidenMap.has(V))
2205     return WidenMap.get(V);
2206
2207   // If this scalar is unknown, assume that it is a constant or that it is
2208   // loop invariant. Broadcast V and save the value for future uses.
2209   Value *B = getBroadcastInstrs(V);
2210   return WidenMap.splat(V, B);
2211 }
2212
2213 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2214   assert(Vec->getType()->isVectorTy() && "Invalid type");
2215   SmallVector<Constant *, 8> ShuffleMask;
2216   for (unsigned i = 0; i < VF; ++i)
2217     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2218
2219   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2220                                      ConstantVector::get(ShuffleMask),
2221                                      "reverse");
2222 }
2223
2224 // Get a mask to interleave \p NumVec vectors into a wide vector.
2225 // I.e.  <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2226 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2227 //      <0, 4, 1, 5, 2, 6, 3, 7>
2228 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2229                                     unsigned NumVec) {
2230   SmallVector<Constant *, 16> Mask;
2231   for (unsigned i = 0; i < VF; i++)
2232     for (unsigned j = 0; j < NumVec; j++)
2233       Mask.push_back(Builder.getInt32(j * VF + i));
2234
2235   return ConstantVector::get(Mask);
2236 }
2237
2238 // Get the strided mask starting from index \p Start.
2239 // I.e.  <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2240 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2241                                 unsigned Stride, unsigned VF) {
2242   SmallVector<Constant *, 16> Mask;
2243   for (unsigned i = 0; i < VF; i++)
2244     Mask.push_back(Builder.getInt32(Start + i * Stride));
2245
2246   return ConstantVector::get(Mask);
2247 }
2248
2249 // Get a mask of two parts: The first part consists of sequential integers
2250 // starting from 0, The second part consists of UNDEFs.
2251 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2252 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2253                                    unsigned NumUndef) {
2254   SmallVector<Constant *, 16> Mask;
2255   for (unsigned i = 0; i < NumInt; i++)
2256     Mask.push_back(Builder.getInt32(i));
2257
2258   Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2259   for (unsigned i = 0; i < NumUndef; i++)
2260     Mask.push_back(Undef);
2261
2262   return ConstantVector::get(Mask);
2263 }
2264
2265 // Concatenate two vectors with the same element type. The 2nd vector should
2266 // not have more elements than the 1st vector. If the 2nd vector has less
2267 // elements, extend it with UNDEFs.
2268 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2269                                     Value *V2) {
2270   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2271   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2272   assert(VecTy1 && VecTy2 &&
2273          VecTy1->getScalarType() == VecTy2->getScalarType() &&
2274          "Expect two vectors with the same element type");
2275
2276   unsigned NumElts1 = VecTy1->getNumElements();
2277   unsigned NumElts2 = VecTy2->getNumElements();
2278   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2279
2280   if (NumElts1 > NumElts2) {
2281     // Extend with UNDEFs.
2282     Constant *ExtMask =
2283         getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2284     V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2285   }
2286
2287   Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2288   return Builder.CreateShuffleVector(V1, V2, Mask);
2289 }
2290
2291 // Concatenate vectors in the given list. All vectors have the same type.
2292 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2293                                  ArrayRef<Value *> InputList) {
2294   unsigned NumVec = InputList.size();
2295   assert(NumVec > 1 && "Should be at least two vectors");
2296
2297   SmallVector<Value *, 8> ResList;
2298   ResList.append(InputList.begin(), InputList.end());
2299   do {
2300     SmallVector<Value *, 8> TmpList;
2301     for (unsigned i = 0; i < NumVec - 1; i += 2) {
2302       Value *V0 = ResList[i], *V1 = ResList[i + 1];
2303       assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2304              "Only the last vector may have a different type");
2305
2306       TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2307     }
2308
2309     // Push the last vector if the total number of vectors is odd.
2310     if (NumVec % 2 != 0)
2311       TmpList.push_back(ResList[NumVec - 1]);
2312
2313     ResList = TmpList;
2314     NumVec = ResList.size();
2315   } while (NumVec > 1);
2316
2317   return ResList[0];
2318 }
2319
2320 // Try to vectorize the interleave group that \p Instr belongs to.
2321 //
2322 // E.g. Translate following interleaved load group (factor = 3):
2323 //   for (i = 0; i < N; i+=3) {
2324 //     R = Pic[i];             // Member of index 0
2325 //     G = Pic[i+1];           // Member of index 1
2326 //     B = Pic[i+2];           // Member of index 2
2327 //     ... // do something to R, G, B
2328 //   }
2329 // To:
2330 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2331 //   %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9>   ; R elements
2332 //   %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10>  ; G elements
2333 //   %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11>  ; B elements
2334 //
2335 // Or translate following interleaved store group (factor = 3):
2336 //   for (i = 0; i < N; i+=3) {
2337 //     ... do something to R, G, B
2338 //     Pic[i]   = R;           // Member of index 0
2339 //     Pic[i+1] = G;           // Member of index 1
2340 //     Pic[i+2] = B;           // Member of index 2
2341 //   }
2342 // To:
2343 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2344 //   %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2345 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2346 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2347 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2348 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2349   const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2350   assert(Group && "Fail to get an interleaved access group.");
2351
2352   // Skip if current instruction is not the insert position.
2353   if (Instr != Group->getInsertPos())
2354     return;
2355
2356   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2357   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2358   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2359
2360   // Prepare for the vector type of the interleaved load/store.
2361   Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2362   unsigned InterleaveFactor = Group->getFactor();
2363   Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2364   Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2365
2366   // Prepare for the new pointers.
2367   setDebugLocFromInst(Builder, Ptr);
2368   VectorParts &PtrParts = getVectorValue(Ptr);
2369   SmallVector<Value *, 2> NewPtrs;
2370   unsigned Index = Group->getIndex(Instr);
2371   for (unsigned Part = 0; Part < UF; Part++) {
2372     // Extract the pointer for current instruction from the pointer vector. A
2373     // reverse access uses the pointer in the last lane.
2374     Value *NewPtr = Builder.CreateExtractElement(
2375         PtrParts[Part],
2376         Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2377
2378     // Notice current instruction could be any index. Need to adjust the address
2379     // to the member of index 0.
2380     //
2381     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2382     //       b = A[i];       // Member of index 0
2383     // Current pointer is pointed to A[i+1], adjust it to A[i].
2384     //
2385     // E.g.  A[i+1] = a;     // Member of index 1
2386     //       A[i]   = b;     // Member of index 0
2387     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2388     // Current pointer is pointed to A[i+2], adjust it to A[i].
2389     NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2390
2391     // Cast to the vector pointer type.
2392     NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2393   }
2394
2395   setDebugLocFromInst(Builder, Instr);
2396   Value *UndefVec = UndefValue::get(VecTy);
2397
2398   // Vectorize the interleaved load group.
2399   if (LI) {
2400     for (unsigned Part = 0; Part < UF; Part++) {
2401       Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2402           NewPtrs[Part], Group->getAlignment(), "wide.vec");
2403
2404       for (unsigned i = 0; i < InterleaveFactor; i++) {
2405         Instruction *Member = Group->getMember(i);
2406
2407         // Skip the gaps in the group.
2408         if (!Member)
2409           continue;
2410
2411         Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2412         Value *StridedVec = Builder.CreateShuffleVector(
2413             NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2414
2415         // If this member has different type, cast the result type.
2416         if (Member->getType() != ScalarTy) {
2417           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2418           StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2419         }
2420
2421         VectorParts &Entry = WidenMap.get(Member);
2422         Entry[Part] =
2423             Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2424       }
2425
2426       addMetadata(NewLoadInstr, Instr);
2427     }
2428     return;
2429   }
2430
2431   // The sub vector type for current instruction.
2432   VectorType *SubVT = VectorType::get(ScalarTy, VF);
2433
2434   // Vectorize the interleaved store group.
2435   for (unsigned Part = 0; Part < UF; Part++) {
2436     // Collect the stored vector from each member.
2437     SmallVector<Value *, 4> StoredVecs;
2438     for (unsigned i = 0; i < InterleaveFactor; i++) {
2439       // Interleaved store group doesn't allow a gap, so each index has a member
2440       Instruction *Member = Group->getMember(i);
2441       assert(Member && "Fail to get a member from an interleaved store group");
2442
2443       Value *StoredVec =
2444           getVectorValue(cast<StoreInst>(Member)->getValueOperand())[Part];
2445       if (Group->isReverse())
2446         StoredVec = reverseVector(StoredVec);
2447
2448       // If this member has different type, cast it to an unified type.
2449       if (StoredVec->getType() != SubVT)
2450         StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2451
2452       StoredVecs.push_back(StoredVec);
2453     }
2454
2455     // Concatenate all vectors into a wide vector.
2456     Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2457
2458     // Interleave the elements in the wide vector.
2459     Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2460     Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2461                                               "interleaved.vec");
2462
2463     Instruction *NewStoreInstr =
2464         Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2465     addMetadata(NewStoreInstr, Instr);
2466   }
2467 }
2468
2469 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2470   // Attempt to issue a wide load.
2471   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2472   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2473
2474   assert((LI || SI) && "Invalid Load/Store instruction");
2475
2476   // Try to vectorize the interleave group if this access is interleaved.
2477   if (Legal->isAccessInterleaved(Instr))
2478     return vectorizeInterleaveGroup(Instr);
2479
2480   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2481   Type *DataTy = VectorType::get(ScalarDataTy, VF);
2482   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2483   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2484   // An alignment of 0 means target abi alignment. We need to use the scalar's
2485   // target abi alignment in such a case.
2486   const DataLayout &DL = Instr->getModule()->getDataLayout();
2487   if (!Alignment)
2488     Alignment = DL.getABITypeAlignment(ScalarDataTy);
2489   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2490   uint64_t ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2491   uint64_t VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2492
2493   if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2494       !Legal->isMaskRequired(SI))
2495     return scalarizeInstruction(Instr, true);
2496
2497   if (ScalarAllocatedSize != VectorElementSize)
2498     return scalarizeInstruction(Instr);
2499
2500   // If the pointer is loop invariant scalarize the load.
2501   if (LI && Legal->isUniform(Ptr))
2502     return scalarizeInstruction(Instr);
2503
2504   // If the pointer is non-consecutive and gather/scatter is not supported
2505   // scalarize the instruction.
2506   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2507   bool Reverse = ConsecutiveStride < 0;
2508   bool CreateGatherScatter =
2509       !ConsecutiveStride && ((LI && Legal->isLegalMaskedGather(ScalarDataTy)) ||
2510                              (SI && Legal->isLegalMaskedScatter(ScalarDataTy)));
2511
2512   if (!ConsecutiveStride && !CreateGatherScatter)
2513     return scalarizeInstruction(Instr);
2514
2515   Constant *Zero = Builder.getInt32(0);
2516   VectorParts &Entry = WidenMap.get(Instr);
2517   VectorParts VectorGep;
2518
2519   // Handle consecutive loads/stores.
2520   GetElementPtrInst *Gep = getGEPInstruction(Ptr);
2521   if (ConsecutiveStride) {
2522     if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2523       setDebugLocFromInst(Builder, Gep);
2524       Value *PtrOperand = Gep->getPointerOperand();
2525       Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2526       FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2527
2528       // Create the new GEP with the new induction variable.
2529       GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2530       Gep2->setOperand(0, FirstBasePtr);
2531       Gep2->setName("gep.indvar.base");
2532       Ptr = Builder.Insert(Gep2);
2533     } else if (Gep) {
2534       setDebugLocFromInst(Builder, Gep);
2535       assert(PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getPointerOperand()),
2536                                           OrigLoop) &&
2537              "Base ptr must be invariant");
2538       // The last index does not have to be the induction. It can be
2539       // consecutive and be a function of the index. For example A[I+1];
2540       unsigned NumOperands = Gep->getNumOperands();
2541       unsigned InductionOperand = getGEPInductionOperand(Gep);
2542       // Create the new GEP with the new induction variable.
2543       GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2544
2545       for (unsigned i = 0; i < NumOperands; ++i) {
2546         Value *GepOperand = Gep->getOperand(i);
2547         Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2548
2549         // Update last index or loop invariant instruction anchored in loop.
2550         if (i == InductionOperand ||
2551             (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2552           assert((i == InductionOperand ||
2553                   PSE.getSE()->isLoopInvariant(PSE.getSCEV(GepOperandInst),
2554                                                OrigLoop)) &&
2555                  "Must be last index or loop invariant");
2556
2557           VectorParts &GEPParts = getVectorValue(GepOperand);
2558
2559           // If GepOperand is an induction variable, and there's a scalarized
2560           // version of it available, use it. Otherwise, we will need to create
2561           // an extractelement instruction.
2562           Value *Index = ScalarIVMap.count(GepOperand)
2563                              ? ScalarIVMap[GepOperand][0]
2564                              : Builder.CreateExtractElement(GEPParts[0], Zero);
2565
2566           Gep2->setOperand(i, Index);
2567           Gep2->setName("gep.indvar.idx");
2568         }
2569       }
2570       Ptr = Builder.Insert(Gep2);
2571     } else { // No GEP
2572       // Use the induction element ptr.
2573       assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2574       setDebugLocFromInst(Builder, Ptr);
2575       VectorParts &PtrVal = getVectorValue(Ptr);
2576       Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2577     }
2578   } else {
2579     // At this point we should vector version of GEP for Gather or Scatter
2580     assert(CreateGatherScatter && "The instruction should be scalarized");
2581     if (Gep) {
2582       // Vectorizing GEP, across UF parts. We want to get a vector value for base
2583       // and each index that's defined inside the loop, even if it is
2584       // loop-invariant but wasn't hoisted out. Otherwise we want to keep them
2585       // scalar.
2586       SmallVector<VectorParts, 4> OpsV;
2587       for (Value *Op : Gep->operands()) {
2588         Instruction *SrcInst = dyn_cast<Instruction>(Op);
2589         if (SrcInst && OrigLoop->contains(SrcInst))
2590           OpsV.push_back(getVectorValue(Op));
2591         else
2592           OpsV.push_back(VectorParts(UF, Op));
2593       }
2594       for (unsigned Part = 0; Part < UF; ++Part) {
2595         SmallVector<Value *, 4> Ops;
2596         Value *GEPBasePtr = OpsV[0][Part];
2597         for (unsigned i = 1; i < Gep->getNumOperands(); i++)
2598           Ops.push_back(OpsV[i][Part]);
2599         Value *NewGep =  Builder.CreateGEP(GEPBasePtr, Ops, "VectorGep");
2600         cast<GetElementPtrInst>(NewGep)->setIsInBounds(Gep->isInBounds());
2601         assert(NewGep->getType()->isVectorTy() && "Expected vector GEP");
2602
2603         NewGep =
2604             Builder.CreateBitCast(NewGep, VectorType::get(Ptr->getType(), VF));
2605         VectorGep.push_back(NewGep);
2606       }
2607     } else
2608       VectorGep = getVectorValue(Ptr);
2609   }
2610
2611   VectorParts Mask = createBlockInMask(Instr->getParent());
2612   // Handle Stores:
2613   if (SI) {
2614     assert(!Legal->isUniform(SI->getPointerOperand()) &&
2615            "We do not allow storing to uniform addresses");
2616     setDebugLocFromInst(Builder, SI);
2617     // We don't want to update the value in the map as it might be used in
2618     // another expression. So don't use a reference type for "StoredVal".
2619     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2620
2621     for (unsigned Part = 0; Part < UF; ++Part) {
2622       Instruction *NewSI = nullptr;
2623       if (CreateGatherScatter) {
2624         Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr;
2625         NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part],
2626                                             Alignment, MaskPart);
2627       } else {
2628         // Calculate the pointer for the specific unroll-part.
2629         Value *PartPtr =
2630             Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2631
2632         if (Reverse) {
2633           // If we store to reverse consecutive memory locations, then we need
2634           // to reverse the order of elements in the stored value.
2635           StoredVal[Part] = reverseVector(StoredVal[Part]);
2636           // If the address is consecutive but reversed, then the
2637           // wide store needs to start at the last vector element.
2638           PartPtr =
2639               Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2640           PartPtr =
2641               Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2642           Mask[Part] = reverseVector(Mask[Part]);
2643         }
2644
2645         Value *VecPtr =
2646             Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2647
2648         if (Legal->isMaskRequired(SI))
2649           NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2650                                             Mask[Part]);
2651         else
2652           NewSI =
2653               Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2654       }
2655       addMetadata(NewSI, SI);
2656     }
2657     return;
2658   }
2659
2660   // Handle loads.
2661   assert(LI && "Must have a load instruction");
2662   setDebugLocFromInst(Builder, LI);
2663   for (unsigned Part = 0; Part < UF; ++Part) {
2664     Instruction *NewLI;
2665     if (CreateGatherScatter) {
2666       Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr;
2667       NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment, MaskPart,
2668                                          0, "wide.masked.gather");
2669       Entry[Part] = NewLI;
2670     } else {
2671       // Calculate the pointer for the specific unroll-part.
2672       Value *PartPtr =
2673           Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2674
2675       if (Reverse) {
2676         // If the address is consecutive but reversed, then the
2677         // wide load needs to start at the last vector element.
2678         PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2679         PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2680         Mask[Part] = reverseVector(Mask[Part]);
2681       }
2682
2683       Value *VecPtr =
2684           Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2685       if (Legal->isMaskRequired(LI))
2686         NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2687                                          UndefValue::get(DataTy),
2688                                          "wide.masked.load");
2689       else
2690         NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2691       Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2692     }
2693     addMetadata(NewLI, LI);
2694   }
2695 }
2696
2697 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2698                                                bool IfPredicateStore) {
2699   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2700   // Holds vector parameters or scalars, in case of uniform vals.
2701   SmallVector<VectorParts, 4> Params;
2702
2703   setDebugLocFromInst(Builder, Instr);
2704
2705   // Find all of the vectorized parameters.
2706   for (Value *SrcOp : Instr->operands()) {
2707     // If we are accessing the old induction variable, use the new one.
2708     if (SrcOp == OldInduction) {
2709       Params.push_back(getVectorValue(SrcOp));
2710       continue;
2711     }
2712
2713     // Try using previously calculated values.
2714     auto *SrcInst = dyn_cast<Instruction>(SrcOp);
2715
2716     // If the src is an instruction that appeared earlier in the basic block,
2717     // then it should already be vectorized.
2718     if (SrcInst && OrigLoop->contains(SrcInst)) {
2719       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2720       // The parameter is a vector value from earlier.
2721       Params.push_back(WidenMap.get(SrcInst));
2722     } else {
2723       // The parameter is a scalar from outside the loop. Maybe even a constant.
2724       VectorParts Scalars;
2725       Scalars.append(UF, SrcOp);
2726       Params.push_back(Scalars);
2727     }
2728   }
2729
2730   assert(Params.size() == Instr->getNumOperands() &&
2731          "Invalid number of operands");
2732
2733   // Does this instruction return a value ?
2734   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2735
2736   Value *UndefVec =
2737       IsVoidRetTy ? nullptr
2738                   : UndefValue::get(VectorType::get(Instr->getType(), VF));
2739   // Create a new entry in the WidenMap and initialize it to Undef or Null.
2740   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2741
2742   VectorParts Cond;
2743   if (IfPredicateStore) {
2744     assert(Instr->getParent()->getSinglePredecessor() &&
2745            "Only support single predecessor blocks");
2746     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2747                           Instr->getParent());
2748   }
2749
2750   // For each vector unroll 'part':
2751   for (unsigned Part = 0; Part < UF; ++Part) {
2752     // For each scalar that we create:
2753     for (unsigned Width = 0; Width < VF; ++Width) {
2754
2755       // Start if-block.
2756       Value *Cmp = nullptr;
2757       if (IfPredicateStore) {
2758         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2759         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
2760                                  ConstantInt::get(Cmp->getType(), 1));
2761       }
2762
2763       Instruction *Cloned = Instr->clone();
2764       if (!IsVoidRetTy)
2765         Cloned->setName(Instr->getName() + ".cloned");
2766       // Replace the operands of the cloned instructions with extracted scalars.
2767       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2768
2769         // If the operand is an induction variable, and there's a scalarized
2770         // version of it available, use it. Otherwise, we will need to create
2771         // an extractelement instruction if vectorizing.
2772         auto *NewOp = Params[op][Part];
2773         auto *ScalarOp = Instr->getOperand(op);
2774         if (ScalarIVMap.count(ScalarOp))
2775           NewOp = ScalarIVMap[ScalarOp][VF * Part + Width];
2776         else if (NewOp->getType()->isVectorTy())
2777           NewOp = Builder.CreateExtractElement(NewOp, Builder.getInt32(Width));
2778         Cloned->setOperand(op, NewOp);
2779       }
2780       addNewMetadata(Cloned, Instr);
2781
2782       // Place the cloned scalar in the new loop.
2783       Builder.Insert(Cloned);
2784
2785       // If we just cloned a new assumption, add it the assumption cache.
2786       if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
2787         if (II->getIntrinsicID() == Intrinsic::assume)
2788           AC->registerAssumption(II);
2789
2790       // If the original scalar returns a value we need to place it in a vector
2791       // so that future users will be able to use it.
2792       if (!IsVoidRetTy)
2793         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2794                                                        Builder.getInt32(Width));
2795       // End if-block.
2796       if (IfPredicateStore)
2797         PredicatedStores.push_back(
2798             std::make_pair(cast<StoreInst>(Cloned), Cmp));
2799     }
2800   }
2801 }
2802
2803 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2804                                                       Value *End, Value *Step,
2805                                                       Instruction *DL) {
2806   BasicBlock *Header = L->getHeader();
2807   BasicBlock *Latch = L->getLoopLatch();
2808   // As we're just creating this loop, it's possible no latch exists
2809   // yet. If so, use the header as this will be a single block loop.
2810   if (!Latch)
2811     Latch = Header;
2812
2813   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2814   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2815   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2816
2817   Builder.SetInsertPoint(Latch->getTerminator());
2818
2819   // Create i+1 and fill the PHINode.
2820   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2821   Induction->addIncoming(Start, L->getLoopPreheader());
2822   Induction->addIncoming(Next, Latch);
2823   // Create the compare.
2824   Value *ICmp = Builder.CreateICmpEQ(Next, End);
2825   Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2826
2827   // Now we have two terminators. Remove the old one from the block.
2828   Latch->getTerminator()->eraseFromParent();
2829
2830   return Induction;
2831 }
2832
2833 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2834   if (TripCount)
2835     return TripCount;
2836
2837   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2838   // Find the loop boundaries.
2839   ScalarEvolution *SE = PSE.getSE();
2840   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2841   assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
2842          "Invalid loop count");
2843
2844   Type *IdxTy = Legal->getWidestInductionType();
2845
2846   // The exit count might have the type of i64 while the phi is i32. This can
2847   // happen if we have an induction variable that is sign extended before the
2848   // compare. The only way that we get a backedge taken count is that the
2849   // induction variable was signed and as such will not overflow. In such a case
2850   // truncation is legal.
2851   if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2852       IdxTy->getPrimitiveSizeInBits())
2853     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2854   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2855
2856   // Get the total trip count from the count by adding 1.
2857   const SCEV *ExitCount = SE->getAddExpr(
2858       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2859
2860   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2861
2862   // Expand the trip count and place the new instructions in the preheader.
2863   // Notice that the pre-header does not change, only the loop body.
2864   SCEVExpander Exp(*SE, DL, "induction");
2865
2866   // Count holds the overall loop count (N).
2867   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2868                                 L->getLoopPreheader()->getTerminator());
2869
2870   if (TripCount->getType()->isPointerTy())
2871     TripCount =
2872         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2873                                     L->getLoopPreheader()->getTerminator());
2874
2875   return TripCount;
2876 }
2877
2878 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2879   if (VectorTripCount)
2880     return VectorTripCount;
2881
2882   Value *TC = getOrCreateTripCount(L);
2883   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2884
2885   // Now we need to generate the expression for the part of the loop that the
2886   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2887   // iterations are not required for correctness, or N - Step, otherwise. Step
2888   // is equal to the vectorization factor (number of SIMD elements) times the
2889   // unroll factor (number of SIMD instructions).
2890   Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2891   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2892
2893   // If there is a non-reversed interleaved group that may speculatively access
2894   // memory out-of-bounds, we need to ensure that there will be at least one
2895   // iteration of the scalar epilogue loop. Thus, if the step evenly divides
2896   // the trip count, we set the remainder to be equal to the step. If the step
2897   // does not evenly divide the trip count, no adjustment is necessary since
2898   // there will already be scalar iterations. Note that the minimum iterations
2899   // check ensures that N >= Step.
2900   if (VF > 1 && Legal->requiresScalarEpilogue()) {
2901     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2902     R = Builder.CreateSelect(IsZero, Step, R);
2903   }
2904
2905   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2906
2907   return VectorTripCount;
2908 }
2909
2910 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2911                                                          BasicBlock *Bypass) {
2912   Value *Count = getOrCreateTripCount(L);
2913   BasicBlock *BB = L->getLoopPreheader();
2914   IRBuilder<> Builder(BB->getTerminator());
2915
2916   // Generate code to check that the loop's trip count that we computed by
2917   // adding one to the backedge-taken count will not overflow.
2918   Value *CheckMinIters = Builder.CreateICmpULT(
2919       Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
2920
2921   BasicBlock *NewBB =
2922       BB->splitBasicBlock(BB->getTerminator(), "min.iters.checked");
2923   // Update dominator tree immediately if the generated block is a
2924   // LoopBypassBlock because SCEV expansions to generate loop bypass
2925   // checks may query it before the current function is finished.
2926   DT->addNewBlock(NewBB, BB);
2927   if (L->getParentLoop())
2928     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2929   ReplaceInstWithInst(BB->getTerminator(),
2930                       BranchInst::Create(Bypass, NewBB, CheckMinIters));
2931   LoopBypassBlocks.push_back(BB);
2932 }
2933
2934 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2935                                                      BasicBlock *Bypass) {
2936   Value *TC = getOrCreateVectorTripCount(L);
2937   BasicBlock *BB = L->getLoopPreheader();
2938   IRBuilder<> Builder(BB->getTerminator());
2939
2940   // Now, compare the new count to zero. If it is zero skip the vector loop and
2941   // jump to the scalar loop.
2942   Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2943                                     "cmp.zero");
2944
2945   // Generate code to check that the loop's trip count that we computed by
2946   // adding one to the backedge-taken count will not overflow.
2947   BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2948   // Update dominator tree immediately if the generated block is a
2949   // LoopBypassBlock because SCEV expansions to generate loop bypass
2950   // checks may query it before the current function is finished.
2951   DT->addNewBlock(NewBB, BB);
2952   if (L->getParentLoop())
2953     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2954   ReplaceInstWithInst(BB->getTerminator(),
2955                       BranchInst::Create(Bypass, NewBB, Cmp));
2956   LoopBypassBlocks.push_back(BB);
2957 }
2958
2959 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
2960   BasicBlock *BB = L->getLoopPreheader();
2961
2962   // Generate the code to check that the SCEV assumptions that we made.
2963   // We want the new basic block to start at the first instruction in a
2964   // sequence of instructions that form a check.
2965   SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
2966                    "scev.check");
2967   Value *SCEVCheck =
2968       Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
2969
2970   if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2971     if (C->isZero())
2972       return;
2973
2974   // Create a new block containing the stride check.
2975   BB->setName("vector.scevcheck");
2976   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2977   // Update dominator tree immediately if the generated block is a
2978   // LoopBypassBlock because SCEV expansions to generate loop bypass
2979   // checks may query it before the current function is finished.
2980   DT->addNewBlock(NewBB, BB);
2981   if (L->getParentLoop())
2982     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2983   ReplaceInstWithInst(BB->getTerminator(),
2984                       BranchInst::Create(Bypass, NewBB, SCEVCheck));
2985   LoopBypassBlocks.push_back(BB);
2986   AddedSafetyChecks = true;
2987 }
2988
2989 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
2990   BasicBlock *BB = L->getLoopPreheader();
2991
2992   // Generate the code that checks in runtime if arrays overlap. We put the
2993   // checks into a separate block to make the more common case of few elements
2994   // faster.
2995   Instruction *FirstCheckInst;
2996   Instruction *MemRuntimeCheck;
2997   std::tie(FirstCheckInst, MemRuntimeCheck) =
2998       Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2999   if (!MemRuntimeCheck)
3000     return;
3001
3002   // Create a new block containing the memory check.
3003   BB->setName("vector.memcheck");
3004   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3005   // Update dominator tree immediately if the generated block is a
3006   // LoopBypassBlock because SCEV expansions to generate loop bypass
3007   // checks may query it before the current function is finished.
3008   DT->addNewBlock(NewBB, BB);
3009   if (L->getParentLoop())
3010     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3011   ReplaceInstWithInst(BB->getTerminator(),
3012                       BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
3013   LoopBypassBlocks.push_back(BB);
3014   AddedSafetyChecks = true;
3015
3016   // We currently don't use LoopVersioning for the actual loop cloning but we
3017   // still use it to add the noalias metadata.
3018   LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3019                                            PSE.getSE());
3020   LVer->prepareNoAliasMetadata();
3021 }
3022
3023 void InnerLoopVectorizer::createEmptyLoop() {
3024   /*
3025    In this function we generate a new loop. The new loop will contain
3026    the vectorized instructions while the old loop will continue to run the
3027    scalar remainder.
3028
3029        [ ] <-- loop iteration number check.
3030     /   |
3031    /    v
3032   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3033   |  /  |
3034   | /   v
3035   ||   [ ]     <-- vector pre header.
3036   |/    |
3037   |     v
3038   |    [  ] \
3039   |    [  ]_|   <-- vector loop.
3040   |     |
3041   |     v
3042   |   -[ ]   <--- middle-block.
3043   |  /  |
3044   | /   v
3045   -|- >[ ]     <--- new preheader.
3046    |    |
3047    |    v
3048    |   [ ] \
3049    |   [ ]_|   <-- old scalar loop to handle remainder.
3050     \   |
3051      \  v
3052       >[ ]     <-- exit block.
3053    ...
3054    */
3055
3056   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3057   BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3058   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3059   assert(VectorPH && "Invalid loop structure");
3060   assert(ExitBlock && "Must have an exit block");
3061
3062   // Some loops have a single integer induction variable, while other loops
3063   // don't. One example is c++ iterators that often have multiple pointer
3064   // induction variables. In the code below we also support a case where we
3065   // don't have a single induction variable.
3066   //
3067   // We try to obtain an induction variable from the original loop as hard
3068   // as possible. However if we don't find one that:
3069   //   - is an integer
3070   //   - counts from zero, stepping by one
3071   //   - is the size of the widest induction variable type
3072   // then we create a new one.
3073   OldInduction = Legal->getInduction();
3074   Type *IdxTy = Legal->getWidestInductionType();
3075
3076   // Split the single block loop into the two loop structure described above.
3077   BasicBlock *VecBody =
3078       VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
3079   BasicBlock *MiddleBlock =
3080       VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
3081   BasicBlock *ScalarPH =
3082       MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
3083
3084   // Create and register the new vector loop.
3085   Loop *Lp = new Loop();
3086   Loop *ParentLoop = OrigLoop->getParentLoop();
3087
3088   // Insert the new loop into the loop nest and register the new basic blocks
3089   // before calling any utilities such as SCEV that require valid LoopInfo.
3090   if (ParentLoop) {
3091     ParentLoop->addChildLoop(Lp);
3092     ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
3093     ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
3094   } else {
3095     LI->addTopLevelLoop(Lp);
3096   }
3097   Lp->addBasicBlockToLoop(VecBody, *LI);
3098
3099   // Find the loop boundaries.
3100   Value *Count = getOrCreateTripCount(Lp);
3101
3102   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3103
3104   // We need to test whether the backedge-taken count is uint##_max. Adding one
3105   // to it will cause overflow and an incorrect loop trip count in the vector
3106   // body. In case of overflow we want to directly jump to the scalar remainder
3107   // loop.
3108   emitMinimumIterationCountCheck(Lp, ScalarPH);
3109   // Now, compare the new count to zero. If it is zero skip the vector loop and
3110   // jump to the scalar loop.
3111   emitVectorLoopEnteredCheck(Lp, ScalarPH);
3112   // Generate the code to check any assumptions that we've made for SCEV
3113   // expressions.
3114   emitSCEVChecks(Lp, ScalarPH);
3115
3116   // Generate the code that checks in runtime if arrays overlap. We put the
3117   // checks into a separate block to make the more common case of few elements
3118   // faster.
3119   emitMemRuntimeChecks(Lp, ScalarPH);
3120
3121   // Generate the induction variable.
3122   // The loop step is equal to the vectorization factor (num of SIMD elements)
3123   // times the unroll factor (num of SIMD instructions).
3124   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3125   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
3126   Induction =
3127       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3128                               getDebugLocFromInstOrOperands(OldInduction));
3129
3130   // We are going to resume the execution of the scalar loop.
3131   // Go over all of the induction variables that we found and fix the
3132   // PHIs that are left in the scalar version of the loop.
3133   // The starting values of PHI nodes depend on the counter of the last
3134   // iteration in the vectorized loop.
3135   // If we come from a bypass edge then we need to start from the original
3136   // start value.
3137
3138   // This variable saves the new starting index for the scalar loop. It is used
3139   // to test if there are any tail iterations left once the vector loop has
3140   // completed.
3141   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
3142   for (auto &InductionEntry : *List) {
3143     PHINode *OrigPhi = InductionEntry.first;
3144     InductionDescriptor II = InductionEntry.second;
3145
3146     // Create phi nodes to merge from the  backedge-taken check block.
3147     PHINode *BCResumeVal = PHINode::Create(
3148         OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
3149     Value *EndValue;
3150     if (OrigPhi == OldInduction) {
3151       // We know what the end value is.
3152       EndValue = CountRoundDown;
3153     } else {
3154       IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
3155       Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
3156                                        II.getStep()->getType(), "cast.crd");
3157       const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3158       EndValue = II.transform(B, CRD, PSE.getSE(), DL);
3159       EndValue->setName("ind.end");
3160     }
3161
3162     // The new PHI merges the original incoming value, in case of a bypass,
3163     // or the value at the end of the vectorized loop.
3164     BCResumeVal->addIncoming(EndValue, MiddleBlock);
3165
3166     // Fix up external users of the induction variable.
3167     fixupIVUsers(OrigPhi, II, CountRoundDown, EndValue, MiddleBlock);
3168
3169     // Fix the scalar body counter (PHI node).
3170     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
3171
3172     // The old induction's phi node in the scalar body needs the truncated
3173     // value.
3174     for (BasicBlock *BB : LoopBypassBlocks)
3175       BCResumeVal->addIncoming(II.getStartValue(), BB);
3176     OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
3177   }
3178
3179   // Add a check in the middle block to see if we have completed
3180   // all of the iterations in the first vector loop.
3181   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3182   Value *CmpN =
3183       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3184                       CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
3185   ReplaceInstWithInst(MiddleBlock->getTerminator(),
3186                       BranchInst::Create(ExitBlock, ScalarPH, CmpN));
3187
3188   // Get ready to start creating new instructions into the vectorized body.
3189   Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
3190
3191   // Save the state.
3192   LoopVectorPreHeader = Lp->getLoopPreheader();
3193   LoopScalarPreHeader = ScalarPH;
3194   LoopMiddleBlock = MiddleBlock;
3195   LoopExitBlock = ExitBlock;
3196   LoopVectorBody = VecBody;
3197   LoopScalarBody = OldBasicBlock;
3198
3199   // Keep all loop hints from the original loop on the vector loop (we'll
3200   // replace the vectorizer-specific hints below).
3201   if (MDNode *LID = OrigLoop->getLoopID())
3202     Lp->setLoopID(LID);
3203
3204   LoopVectorizeHints Hints(Lp, true);
3205   Hints.setAlreadyVectorized();
3206 }
3207
3208 // Fix up external users of the induction variable. At this point, we are
3209 // in LCSSA form, with all external PHIs that use the IV having one input value,
3210 // coming from the remainder loop. We need those PHIs to also have a correct
3211 // value for the IV when arriving directly from the middle block.
3212 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3213                                        const InductionDescriptor &II,
3214                                        Value *CountRoundDown, Value *EndValue,
3215                                        BasicBlock *MiddleBlock) {
3216   // There are two kinds of external IV usages - those that use the value
3217   // computed in the last iteration (the PHI) and those that use the penultimate
3218   // value (the value that feeds into the phi from the loop latch).
3219   // We allow both, but they, obviously, have different values.
3220
3221   assert(OrigLoop->getExitBlock() && "Expected a single exit block");
3222
3223   DenseMap<Value *, Value *> MissingVals;
3224
3225   // An external user of the last iteration's value should see the value that
3226   // the remainder loop uses to initialize its own IV.
3227   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3228   for (User *U : PostInc->users()) {
3229     Instruction *UI = cast<Instruction>(U);
3230     if (!OrigLoop->contains(UI)) {
3231       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3232       MissingVals[UI] = EndValue;
3233     }
3234   }
3235
3236   // An external user of the penultimate value need to see EndValue - Step.
3237   // The simplest way to get this is to recompute it from the constituent SCEVs,
3238   // that is Start + (Step * (CRD - 1)).
3239   for (User *U : OrigPhi->users()) {
3240     auto *UI = cast<Instruction>(U);
3241     if (!OrigLoop->contains(UI)) {
3242       const DataLayout &DL =
3243           OrigLoop->getHeader()->getModule()->getDataLayout();
3244       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3245
3246       IRBuilder<> B(MiddleBlock->getTerminator());
3247       Value *CountMinusOne = B.CreateSub(
3248           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3249       Value *CMO = B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType(),
3250                                        "cast.cmo");
3251       Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3252       Escape->setName("ind.escape");
3253       MissingVals[UI] = Escape;
3254     }
3255   }
3256
3257   for (auto &I : MissingVals) {
3258     PHINode *PHI = cast<PHINode>(I.first);
3259     // One corner case we have to handle is two IVs "chasing" each-other,
3260     // that is %IV2 = phi [...], [ %IV1, %latch ]
3261     // In this case, if IV1 has an external use, we need to avoid adding both
3262     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3263     // don't already have an incoming value for the middle block.
3264     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3265       PHI->addIncoming(I.second, MiddleBlock);
3266   }
3267 }
3268
3269 namespace {
3270 struct CSEDenseMapInfo {
3271   static bool canHandle(Instruction *I) {
3272     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3273            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3274   }
3275   static inline Instruction *getEmptyKey() {
3276     return DenseMapInfo<Instruction *>::getEmptyKey();
3277   }
3278   static inline Instruction *getTombstoneKey() {
3279     return DenseMapInfo<Instruction *>::getTombstoneKey();
3280   }
3281   static unsigned getHashValue(Instruction *I) {
3282     assert(canHandle(I) && "Unknown instruction!");
3283     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3284                                                            I->value_op_end()));
3285   }
3286   static bool isEqual(Instruction *LHS, Instruction *RHS) {
3287     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3288         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3289       return LHS == RHS;
3290     return LHS->isIdenticalTo(RHS);
3291   }
3292 };
3293 }
3294
3295 ///\brief Perform cse of induction variable instructions.
3296 static void cse(BasicBlock *BB) {
3297   // Perform simple cse.
3298   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3299   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3300     Instruction *In = &*I++;
3301
3302     if (!CSEDenseMapInfo::canHandle(In))
3303       continue;
3304
3305     // Check if we can replace this instruction with any of the
3306     // visited instructions.
3307     if (Instruction *V = CSEMap.lookup(In)) {
3308       In->replaceAllUsesWith(V);
3309       In->eraseFromParent();
3310       continue;
3311     }
3312
3313     CSEMap[In] = In;
3314   }
3315 }
3316
3317 /// \brief Adds a 'fast' flag to floating point operations.
3318 static Value *addFastMathFlag(Value *V) {
3319   if (isa<FPMathOperator>(V)) {
3320     FastMathFlags Flags;
3321     Flags.setUnsafeAlgebra();
3322     cast<Instruction>(V)->setFastMathFlags(Flags);
3323   }
3324   return V;
3325 }
3326
3327 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3328 /// the result needs to be inserted and/or extracted from vectors.
3329 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3330                                          const TargetTransformInfo &TTI) {
3331   if (Ty->isVoidTy())
3332     return 0;
3333
3334   assert(Ty->isVectorTy() && "Can only scalarize vectors");
3335   unsigned Cost = 0;
3336
3337   for (unsigned I = 0, E = Ty->getVectorNumElements(); I < E; ++I) {
3338     if (Insert)
3339       Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, I);
3340     if (Extract)
3341       Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, I);
3342   }
3343
3344   return Cost;
3345 }
3346
3347 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3348 // Return the cost of the instruction, including scalarization overhead if it's
3349 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3350 // i.e. either vector version isn't available, or is too expensive.
3351 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3352                                   const TargetTransformInfo &TTI,
3353                                   const TargetLibraryInfo *TLI,
3354                                   bool &NeedToScalarize) {
3355   Function *F = CI->getCalledFunction();
3356   StringRef FnName = CI->getCalledFunction()->getName();
3357   Type *ScalarRetTy = CI->getType();
3358   SmallVector<Type *, 4> Tys, ScalarTys;
3359   for (auto &ArgOp : CI->arg_operands())
3360     ScalarTys.push_back(ArgOp->getType());
3361
3362   // Estimate cost of scalarized vector call. The source operands are assumed
3363   // to be vectors, so we need to extract individual elements from there,
3364   // execute VF scalar calls, and then gather the result into the vector return
3365   // value.
3366   unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3367   if (VF == 1)
3368     return ScalarCallCost;
3369
3370   // Compute corresponding vector type for return value and arguments.
3371   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3372   for (Type *ScalarTy : ScalarTys)
3373     Tys.push_back(ToVectorTy(ScalarTy, VF));
3374
3375   // Compute costs of unpacking argument values for the scalar calls and
3376   // packing the return values to a vector.
3377   unsigned ScalarizationCost =
3378       getScalarizationOverhead(RetTy, true, false, TTI);
3379   for (Type *Ty : Tys)
3380     ScalarizationCost += getScalarizationOverhead(Ty, false, true, TTI);
3381
3382   unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3383
3384   // If we can't emit a vector call for this function, then the currently found
3385   // cost is the cost we need to return.
3386   NeedToScalarize = true;
3387   if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3388     return Cost;
3389
3390   // If the corresponding vector cost is cheaper, return its cost.
3391   unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3392   if (VectorCallCost < Cost) {
3393     NeedToScalarize = false;
3394     return VectorCallCost;
3395   }
3396   return Cost;
3397 }
3398
3399 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3400 // factor VF.  Return the cost of the instruction, including scalarization
3401 // overhead if it's needed.
3402 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3403                                        const TargetTransformInfo &TTI,
3404                                        const TargetLibraryInfo *TLI) {
3405   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3406   assert(ID && "Expected intrinsic call!");
3407
3408   Type *RetTy = ToVectorTy(CI->getType(), VF);
3409   SmallVector<Type *, 4> Tys;
3410   for (Value *ArgOperand : CI->arg_operands())
3411     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
3412
3413   FastMathFlags FMF;
3414   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3415     FMF = FPMO->getFastMathFlags();
3416
3417   return TTI.getIntrinsicInstrCost(ID, RetTy, Tys, FMF);
3418 }
3419
3420 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3421   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3422   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3423   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3424 }
3425 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3426   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3427   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3428   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3429 }
3430
3431 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3432   // For every instruction `I` in MinBWs, truncate the operands, create a
3433   // truncated version of `I` and reextend its result. InstCombine runs
3434   // later and will remove any ext/trunc pairs.
3435   //
3436   SmallPtrSet<Value *, 4> Erased;
3437   for (const auto &KV : *MinBWs) {
3438     VectorParts &Parts = WidenMap.get(KV.first);
3439     for (Value *&I : Parts) {
3440       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3441         continue;
3442       Type *OriginalTy = I->getType();
3443       Type *ScalarTruncatedTy =
3444           IntegerType::get(OriginalTy->getContext(), KV.second);
3445       Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3446                                           OriginalTy->getVectorNumElements());
3447       if (TruncatedTy == OriginalTy)
3448         continue;
3449
3450       IRBuilder<> B(cast<Instruction>(I));
3451       auto ShrinkOperand = [&](Value *V) -> Value * {
3452         if (auto *ZI = dyn_cast<ZExtInst>(V))
3453           if (ZI->getSrcTy() == TruncatedTy)
3454             return ZI->getOperand(0);
3455         return B.CreateZExtOrTrunc(V, TruncatedTy);
3456       };
3457
3458       // The actual instruction modification depends on the instruction type,
3459       // unfortunately.
3460       Value *NewI = nullptr;
3461       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3462         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3463                              ShrinkOperand(BO->getOperand(1)));
3464         cast<BinaryOperator>(NewI)->copyIRFlags(I);
3465       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3466         NewI =
3467             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3468                          ShrinkOperand(CI->getOperand(1)));
3469       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3470         NewI = B.CreateSelect(SI->getCondition(),
3471                               ShrinkOperand(SI->getTrueValue()),
3472                               ShrinkOperand(SI->getFalseValue()));
3473       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3474         switch (CI->getOpcode()) {
3475         default:
3476           llvm_unreachable("Unhandled cast!");
3477         case Instruction::Trunc:
3478           NewI = ShrinkOperand(CI->getOperand(0));
3479           break;
3480         case Instruction::SExt:
3481           NewI = B.CreateSExtOrTrunc(
3482               CI->getOperand(0),
3483               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3484           break;
3485         case Instruction::ZExt:
3486           NewI = B.CreateZExtOrTrunc(
3487               CI->getOperand(0),
3488               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3489           break;
3490         }
3491       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3492         auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3493         auto *O0 = B.CreateZExtOrTrunc(
3494             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3495         auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3496         auto *O1 = B.CreateZExtOrTrunc(
3497             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3498
3499         NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3500       } else if (isa<LoadInst>(I)) {
3501         // Don't do anything with the operands, just extend the result.
3502         continue;
3503       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3504         auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3505         auto *O0 = B.CreateZExtOrTrunc(
3506             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3507         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3508         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3509       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3510         auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3511         auto *O0 = B.CreateZExtOrTrunc(
3512             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3513         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3514       } else {
3515         llvm_unreachable("Unhandled instruction type!");
3516       }
3517
3518       // Lastly, extend the result.
3519       NewI->takeName(cast<Instruction>(I));
3520       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3521       I->replaceAllUsesWith(Res);
3522       cast<Instruction>(I)->eraseFromParent();
3523       Erased.insert(I);
3524       I = Res;
3525     }
3526   }
3527
3528   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3529   for (const auto &KV : *MinBWs) {
3530     VectorParts &Parts = WidenMap.get(KV.first);
3531     for (Value *&I : Parts) {
3532       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3533       if (Inst && Inst->use_empty()) {
3534         Value *NewI = Inst->getOperand(0);
3535         Inst->eraseFromParent();
3536         I = NewI;
3537       }
3538     }
3539   }
3540 }
3541
3542 void InnerLoopVectorizer::vectorizeLoop() {
3543   //===------------------------------------------------===//
3544   //
3545   // Notice: any optimization or new instruction that go
3546   // into the code below should be also be implemented in
3547   // the cost-model.
3548   //
3549   //===------------------------------------------------===//
3550   Constant *Zero = Builder.getInt32(0);
3551
3552   // In order to support recurrences we need to be able to vectorize Phi nodes.
3553   // Phi nodes have cycles, so we need to vectorize them in two stages. First,
3554   // we create a new vector PHI node with no incoming edges. We use this value
3555   // when we vectorize all of the instructions that use the PHI. Next, after
3556   // all of the instructions in the block are complete we add the new incoming
3557   // edges to the PHI. At this point all of the instructions in the basic block
3558   // are vectorized, so we can use them to construct the PHI.
3559   PhiVector PHIsToFix;
3560
3561   // Scan the loop in a topological order to ensure that defs are vectorized
3562   // before users.
3563   LoopBlocksDFS DFS(OrigLoop);
3564   DFS.perform(LI);
3565
3566   // Vectorize all of the blocks in the original loop.
3567   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
3568     vectorizeBlockInLoop(BB, &PHIsToFix);
3569
3570   // Insert truncates and extends for any truncated instructions as hints to
3571   // InstCombine.
3572   if (VF > 1)
3573     truncateToMinimalBitwidths();
3574
3575   // At this point every instruction in the original loop is widened to a
3576   // vector form. Now we need to fix the recurrences in PHIsToFix. These PHI
3577   // nodes are currently empty because we did not want to introduce cycles.
3578   // This is the second stage of vectorizing recurrences.
3579   for (PHINode *Phi : PHIsToFix) {
3580     assert(Phi && "Unable to recover vectorized PHI");
3581
3582     // Handle first-order recurrences that need to be fixed.
3583     if (Legal->isFirstOrderRecurrence(Phi)) {
3584       fixFirstOrderRecurrence(Phi);
3585       continue;
3586     }
3587
3588     // If the phi node is not a first-order recurrence, it must be a reduction.
3589     // Get it's reduction variable descriptor.
3590     assert(Legal->isReductionVariable(Phi) &&
3591            "Unable to find the reduction variable");
3592     RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
3593
3594     RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3595     TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3596     Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3597     RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3598         RdxDesc.getMinMaxRecurrenceKind();
3599     setDebugLocFromInst(Builder, ReductionStartValue);
3600
3601     // We need to generate a reduction vector from the incoming scalar.
3602     // To do so, we need to generate the 'identity' vector and override
3603     // one of the elements with the incoming scalar reduction. We need
3604     // to do it in the vector-loop preheader.
3605     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3606
3607     // This is the vector-clone of the value that leaves the loop.
3608     VectorParts &VectorExit = getVectorValue(LoopExitInst);
3609     Type *VecTy = VectorExit[0]->getType();
3610
3611     // Find the reduction identity variable. Zero for addition, or, xor,
3612     // one for multiplication, -1 for And.
3613     Value *Identity;
3614     Value *VectorStart;
3615     if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3616         RK == RecurrenceDescriptor::RK_FloatMinMax) {
3617       // MinMax reduction have the start value as their identify.
3618       if (VF == 1) {
3619         VectorStart = Identity = ReductionStartValue;
3620       } else {
3621         VectorStart = Identity =
3622             Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3623       }
3624     } else {
3625       // Handle other reduction kinds:
3626       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3627           RK, VecTy->getScalarType());
3628       if (VF == 1) {
3629         Identity = Iden;
3630         // This vector is the Identity vector where the first element is the
3631         // incoming scalar reduction.
3632         VectorStart = ReductionStartValue;
3633       } else {
3634         Identity = ConstantVector::getSplat(VF, Iden);
3635
3636         // This vector is the Identity vector where the first element is the
3637         // incoming scalar reduction.
3638         VectorStart =
3639             Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3640       }
3641     }
3642
3643     // Fix the vector-loop phi.
3644
3645     // Reductions do not have to start at zero. They can start with
3646     // any loop invariant values.
3647     VectorParts &VecRdxPhi = WidenMap.get(Phi);
3648     BasicBlock *Latch = OrigLoop->getLoopLatch();
3649     Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
3650     VectorParts &Val = getVectorValue(LoopVal);
3651     for (unsigned part = 0; part < UF; ++part) {
3652       // Make sure to add the reduction stat value only to the
3653       // first unroll part.
3654       Value *StartVal = (part == 0) ? VectorStart : Identity;
3655       cast<PHINode>(VecRdxPhi[part])
3656           ->addIncoming(StartVal, LoopVectorPreHeader);
3657       cast<PHINode>(VecRdxPhi[part])
3658           ->addIncoming(Val[part], LoopVectorBody);
3659     }
3660
3661     // Before each round, move the insertion point right between
3662     // the PHIs and the values we are going to write.
3663     // This allows us to write both PHINodes and the extractelement
3664     // instructions.
3665     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3666
3667     VectorParts RdxParts = getVectorValue(LoopExitInst);
3668     setDebugLocFromInst(Builder, LoopExitInst);
3669
3670     // If the vector reduction can be performed in a smaller type, we truncate
3671     // then extend the loop exit value to enable InstCombine to evaluate the
3672     // entire expression in the smaller type.
3673     if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
3674       Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3675       Builder.SetInsertPoint(LoopVectorBody->getTerminator());
3676       for (unsigned part = 0; part < UF; ++part) {
3677         Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3678         Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3679                                           : Builder.CreateZExt(Trunc, VecTy);
3680         for (Value::user_iterator UI = RdxParts[part]->user_begin();
3681              UI != RdxParts[part]->user_end();)
3682           if (*UI != Trunc) {
3683             (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3684             RdxParts[part] = Extnd;
3685           } else {
3686             ++UI;
3687           }
3688       }
3689       Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3690       for (unsigned part = 0; part < UF; ++part)
3691         RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3692     }
3693
3694     // Reduce all of the unrolled parts into a single vector.
3695     Value *ReducedPartRdx = RdxParts[0];
3696     unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3697     setDebugLocFromInst(Builder, ReducedPartRdx);
3698     for (unsigned part = 1; part < UF; ++part) {
3699       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3700         // Floating point operations had to be 'fast' to enable the reduction.
3701         ReducedPartRdx = addFastMathFlag(
3702             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3703                                 ReducedPartRdx, "bin.rdx"));
3704       else
3705         ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3706             Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3707     }
3708
3709     if (VF > 1) {
3710       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3711       // and vector ops, reducing the set of values being computed by half each
3712       // round.
3713       assert(isPowerOf2_32(VF) &&
3714              "Reduction emission only supported for pow2 vectors!");
3715       Value *TmpVec = ReducedPartRdx;
3716       SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
3717       for (unsigned i = VF; i != 1; i >>= 1) {
3718         // Move the upper half of the vector to the lower half.
3719         for (unsigned j = 0; j != i / 2; ++j)
3720           ShuffleMask[j] = Builder.getInt32(i / 2 + j);
3721
3722         // Fill the rest of the mask with undef.
3723         std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
3724                   UndefValue::get(Builder.getInt32Ty()));
3725
3726         Value *Shuf = Builder.CreateShuffleVector(
3727             TmpVec, UndefValue::get(TmpVec->getType()),
3728             ConstantVector::get(ShuffleMask), "rdx.shuf");
3729
3730         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3731           // Floating point operations had to be 'fast' to enable the reduction.
3732           TmpVec = addFastMathFlag(Builder.CreateBinOp(
3733               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3734         else
3735           TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3736                                                         TmpVec, Shuf);
3737       }
3738
3739       // The result is in the first element of the vector.
3740       ReducedPartRdx =
3741           Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3742
3743       // If the reduction can be performed in a smaller type, we need to extend
3744       // the reduction to the wider type before we branch to the original loop.
3745       if (Phi->getType() != RdxDesc.getRecurrenceType())
3746         ReducedPartRdx =
3747             RdxDesc.isSigned()
3748                 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
3749                 : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
3750     }
3751
3752     // Create a phi node that merges control-flow from the backedge-taken check
3753     // block and the middle block.
3754     PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
3755                                           LoopScalarPreHeader->getTerminator());
3756     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3757       BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3758     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3759
3760     // Now, we need to fix the users of the reduction variable
3761     // inside and outside of the scalar remainder loop.
3762     // We know that the loop is in LCSSA form. We need to update the
3763     // PHI nodes in the exit blocks.
3764     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3765                               LEE = LoopExitBlock->end();
3766          LEI != LEE; ++LEI) {
3767       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3768       if (!LCSSAPhi)
3769         break;
3770
3771       // All PHINodes need to have a single entry edge, or two if
3772       // we already fixed them.
3773       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3774
3775       // We found our reduction value exit-PHI. Update it with the
3776       // incoming bypass edge.
3777       if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3778         // Add an edge coming from the bypass.
3779         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3780         break;
3781       }
3782     } // end of the LCSSA phi scan.
3783
3784     // Fix the scalar loop reduction variable with the incoming reduction sum
3785     // from the vector body and from the backedge value.
3786     int IncomingEdgeBlockIdx =
3787         Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
3788     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3789     // Pick the other block.
3790     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3791     Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3792     Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3793   } // end of for each Phi in PHIsToFix.
3794
3795   fixLCSSAPHIs();
3796
3797   // Make sure DomTree is updated.
3798   updateAnalysis();
3799
3800   // Predicate any stores.
3801   for (auto KV : PredicatedStores) {
3802     BasicBlock::iterator I(KV.first);
3803     auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI);
3804     auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
3805                                         /*BranchWeights=*/nullptr, DT, LI);
3806     I->moveBefore(T);
3807     I->getParent()->setName("pred.store.if");
3808     BB->setName("pred.store.continue");
3809   }
3810   DEBUG(DT->verifyDomTree());
3811   // Remove redundant induction instructions.
3812   cse(LoopVectorBody);
3813 }
3814
3815 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3816
3817   // This is the second phase of vectorizing first-order recurrences. An
3818   // overview of the transformation is described below. Suppose we have the
3819   // following loop.
3820   //
3821   //   for (int i = 0; i < n; ++i)
3822   //     b[i] = a[i] - a[i - 1];
3823   //
3824   // There is a first-order recurrence on "a". For this loop, the shorthand
3825   // scalar IR looks like:
3826   //
3827   //   scalar.ph:
3828   //     s_init = a[-1]
3829   //     br scalar.body
3830   //
3831   //   scalar.body:
3832   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3833   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3834   //     s2 = a[i]
3835   //     b[i] = s2 - s1
3836   //     br cond, scalar.body, ...
3837   //
3838   // In this example, s1 is a recurrence because it's value depends on the
3839   // previous iteration. In the first phase of vectorization, we created a
3840   // temporary value for s1. We now complete the vectorization and produce the
3841   // shorthand vector IR shown below (for VF = 4, UF = 1).
3842   //
3843   //   vector.ph:
3844   //     v_init = vector(..., ..., ..., a[-1])
3845   //     br vector.body
3846   //
3847   //   vector.body
3848   //     i = phi [0, vector.ph], [i+4, vector.body]
3849   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3850   //     v2 = a[i, i+1, i+2, i+3];
3851   //     v3 = vector(v1(3), v2(0, 1, 2))
3852   //     b[i, i+1, i+2, i+3] = v2 - v3
3853   //     br cond, vector.body, middle.block
3854   //
3855   //   middle.block:
3856   //     x = v2(3)
3857   //     br scalar.ph
3858   //
3859   //   scalar.ph:
3860   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3861   //     br scalar.body
3862   //
3863   // After execution completes the vector loop, we extract the next value of
3864   // the recurrence (x) to use as the initial value in the scalar loop.
3865
3866   // Get the original loop preheader and single loop latch.
3867   auto *Preheader = OrigLoop->getLoopPreheader();
3868   auto *Latch = OrigLoop->getLoopLatch();
3869
3870   // Get the initial and previous values of the scalar recurrence.
3871   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
3872   auto *Previous = Phi->getIncomingValueForBlock(Latch);
3873
3874   // Create a vector from the initial value.
3875   auto *VectorInit = ScalarInit;
3876   if (VF > 1) {
3877     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3878     VectorInit = Builder.CreateInsertElement(
3879         UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
3880         Builder.getInt32(VF - 1), "vector.recur.init");
3881   }
3882
3883   // We constructed a temporary phi node in the first phase of vectorization.
3884   // This phi node will eventually be deleted.
3885   auto &PhiParts = getVectorValue(Phi);
3886   Builder.SetInsertPoint(cast<Instruction>(PhiParts[0]));
3887
3888   // Create a phi node for the new recurrence. The current value will either be
3889   // the initial value inserted into a vector or loop-varying vector value.
3890   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
3891   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
3892
3893   // Get the vectorized previous value. We ensured the previous values was an
3894   // instruction when detecting the recurrence.
3895   auto &PreviousParts = getVectorValue(Previous);
3896
3897   // Set the insertion point to be after this instruction. We ensured the
3898   // previous value dominated all uses of the phi when detecting the
3899   // recurrence.
3900   Builder.SetInsertPoint(
3901       &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1])));
3902
3903   // We will construct a vector for the recurrence by combining the values for
3904   // the current and previous iterations. This is the required shuffle mask.
3905   SmallVector<Constant *, 8> ShuffleMask(VF);
3906   ShuffleMask[0] = Builder.getInt32(VF - 1);
3907   for (unsigned I = 1; I < VF; ++I)
3908     ShuffleMask[I] = Builder.getInt32(I + VF - 1);
3909
3910   // The vector from which to take the initial value for the current iteration
3911   // (actual or unrolled). Initially, this is the vector phi node.
3912   Value *Incoming = VecPhi;
3913
3914   // Shuffle the current and previous vector and update the vector parts.
3915   for (unsigned Part = 0; Part < UF; ++Part) {
3916     auto *Shuffle =
3917         VF > 1
3918             ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part],
3919                                           ConstantVector::get(ShuffleMask))
3920             : Incoming;
3921     PhiParts[Part]->replaceAllUsesWith(Shuffle);
3922     cast<Instruction>(PhiParts[Part])->eraseFromParent();
3923     PhiParts[Part] = Shuffle;
3924     Incoming = PreviousParts[Part];
3925   }
3926
3927   // Fix the latch value of the new recurrence in the vector loop.
3928   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3929
3930   // Extract the last vector element in the middle block. This will be the
3931   // initial value for the recurrence when jumping to the scalar loop.
3932   auto *Extract = Incoming;
3933   if (VF > 1) {
3934     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3935     Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1),
3936                                            "vector.recur.extract");
3937   }
3938
3939   // Fix the initial value of the original recurrence in the scalar loop.
3940   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3941   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3942   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3943     auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit;
3944     Start->addIncoming(Incoming, BB);
3945   }
3946
3947   Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
3948   Phi->setName("scalar.recur");
3949
3950   // Finally, fix users of the recurrence outside the loop. The users will need
3951   // either the last value of the scalar recurrence or the last value of the
3952   // vector recurrence we extracted in the middle block. Since the loop is in
3953   // LCSSA form, we just need to find the phi node for the original scalar
3954   // recurrence in the exit block, and then add an edge for the middle block.
3955   for (auto &I : *LoopExitBlock) {
3956     auto *LCSSAPhi = dyn_cast<PHINode>(&I);
3957     if (!LCSSAPhi)
3958       break;
3959     if (LCSSAPhi->getIncomingValue(0) == Phi) {
3960       LCSSAPhi->addIncoming(Extract, LoopMiddleBlock);
3961       break;
3962     }
3963   }
3964 }
3965
3966 void InnerLoopVectorizer::fixLCSSAPHIs() {
3967   for (Instruction &LEI : *LoopExitBlock) {
3968     auto *LCSSAPhi = dyn_cast<PHINode>(&LEI);
3969     if (!LCSSAPhi)
3970       break;
3971     if (LCSSAPhi->getNumIncomingValues() == 1)
3972       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3973                             LoopMiddleBlock);
3974   }
3975 }
3976
3977 InnerLoopVectorizer::VectorParts
3978 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3979   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3980          "Invalid edge");
3981
3982   // Look for cached value.
3983   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
3984   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3985   if (ECEntryIt != MaskCache.end())
3986     return ECEntryIt->second;
3987
3988   VectorParts SrcMask = createBlockInMask(Src);
3989
3990   // The terminator has to be a branch inst!
3991   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3992   assert(BI && "Unexpected terminator found");
3993
3994   if (BI->isConditional()) {
3995     VectorParts EdgeMask = getVectorValue(BI->getCondition());
3996
3997     if (BI->getSuccessor(0) != Dst)
3998       for (unsigned part = 0; part < UF; ++part)
3999         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
4000
4001     for (unsigned part = 0; part < UF; ++part)
4002       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
4003
4004     MaskCache[Edge] = EdgeMask;
4005     return EdgeMask;
4006   }
4007
4008   MaskCache[Edge] = SrcMask;
4009   return SrcMask;
4010 }
4011
4012 InnerLoopVectorizer::VectorParts
4013 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
4014   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
4015
4016   // Loop incoming mask is all-one.
4017   if (OrigLoop->getHeader() == BB) {
4018     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
4019     return getVectorValue(C);
4020   }
4021
4022   // This is the block mask. We OR all incoming edges, and with zero.
4023   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
4024   VectorParts BlockMask = getVectorValue(Zero);
4025
4026   // For each pred:
4027   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
4028     VectorParts EM = createEdgeMask(*it, BB);
4029     for (unsigned part = 0; part < UF; ++part)
4030       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
4031   }
4032
4033   return BlockMask;
4034 }
4035
4036 void InnerLoopVectorizer::widenPHIInstruction(
4037     Instruction *PN, InnerLoopVectorizer::VectorParts &Entry, unsigned UF,
4038     unsigned VF, PhiVector *PV) {
4039   PHINode *P = cast<PHINode>(PN);
4040   // Handle recurrences.
4041   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4042     for (unsigned part = 0; part < UF; ++part) {
4043       // This is phase one of vectorizing PHIs.
4044       Type *VecTy =
4045           (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4046       Entry[part] = PHINode::Create(
4047           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4048     }
4049     PV->push_back(P);
4050     return;
4051   }
4052
4053   setDebugLocFromInst(Builder, P);
4054   // Check for PHI nodes that are lowered to vector selects.
4055   if (P->getParent() != OrigLoop->getHeader()) {
4056     // We know that all PHIs in non-header blocks are converted into
4057     // selects, so we don't have to worry about the insertion order and we
4058     // can just use the builder.
4059     // At this point we generate the predication tree. There may be
4060     // duplications since this is a simple recursive scan, but future
4061     // optimizations will clean it up.
4062
4063     unsigned NumIncoming = P->getNumIncomingValues();
4064
4065     // Generate a sequence of selects of the form:
4066     // SELECT(Mask3, In3,
4067     //      SELECT(Mask2, In2,
4068     //                   ( ...)))
4069     for (unsigned In = 0; In < NumIncoming; In++) {
4070       VectorParts Cond =
4071           createEdgeMask(P->getIncomingBlock(In), P->getParent());
4072       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
4073
4074       for (unsigned part = 0; part < UF; ++part) {
4075         // We might have single edge PHIs (blocks) - use an identity
4076         // 'select' for the first PHI operand.
4077         if (In == 0)
4078           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]);
4079         else
4080           // Select between the current value and the previous incoming edge
4081           // based on the incoming mask.
4082           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part],
4083                                              "predphi");
4084       }
4085     }
4086     return;
4087   }
4088
4089   // This PHINode must be an induction variable.
4090   // Make sure that we know about it.
4091   assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
4092
4093   InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4094   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4095
4096   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4097   // which can be found from the original scalar operations.
4098   switch (II.getKind()) {
4099   case InductionDescriptor::IK_NoInduction:
4100     llvm_unreachable("Unknown induction");
4101   case InductionDescriptor::IK_IntInduction:
4102     return widenIntInduction(P, Entry);
4103   case InductionDescriptor::IK_PtrInduction:
4104     // Handle the pointer induction variable case.
4105     assert(P->getType()->isPointerTy() && "Unexpected type.");
4106     // This is the normalized GEP that starts counting at zero.
4107     Value *PtrInd = Induction;
4108     PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4109     // This is the vector of results. Notice that we don't generate
4110     // vector geps because scalar geps result in better code.
4111     for (unsigned part = 0; part < UF; ++part) {
4112       if (VF == 1) {
4113         int EltIndex = part;
4114         Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
4115         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4116         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4117         SclrGep->setName("next.gep");
4118         Entry[part] = SclrGep;
4119         continue;
4120       }
4121
4122       Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
4123       for (unsigned int i = 0; i < VF; ++i) {
4124         int EltIndex = i + part * VF;
4125         Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
4126         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4127         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4128         SclrGep->setName("next.gep");
4129         VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
4130                                              Builder.getInt32(i), "insert.gep");
4131       }
4132       Entry[part] = VecVal;
4133     }
4134     return;
4135   }
4136 }
4137
4138 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
4139   // For each instruction in the old loop.
4140   for (Instruction &I : *BB) {
4141     VectorParts &Entry = WidenMap.get(&I);
4142
4143     switch (I.getOpcode()) {
4144     case Instruction::Br:
4145       // Nothing to do for PHIs and BR, since we already took care of the
4146       // loop control flow instructions.
4147       continue;
4148     case Instruction::PHI: {
4149       // Vectorize PHINodes.
4150       widenPHIInstruction(&I, Entry, UF, VF, PV);
4151       continue;
4152     } // End of PHI.
4153
4154     case Instruction::Add:
4155     case Instruction::FAdd:
4156     case Instruction::Sub:
4157     case Instruction::FSub:
4158     case Instruction::Mul:
4159     case Instruction::FMul:
4160     case Instruction::UDiv:
4161     case Instruction::SDiv:
4162     case Instruction::FDiv:
4163     case Instruction::URem:
4164     case Instruction::SRem:
4165     case Instruction::FRem:
4166     case Instruction::Shl:
4167     case Instruction::LShr:
4168     case Instruction::AShr:
4169     case Instruction::And:
4170     case Instruction::Or:
4171     case Instruction::Xor: {
4172       // Just widen binops.
4173       auto *BinOp = cast<BinaryOperator>(&I);
4174       setDebugLocFromInst(Builder, BinOp);
4175       VectorParts &A = getVectorValue(BinOp->getOperand(0));
4176       VectorParts &B = getVectorValue(BinOp->getOperand(1));
4177
4178       // Use this vector value for all users of the original instruction.
4179       for (unsigned Part = 0; Part < UF; ++Part) {
4180         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
4181
4182         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4183           VecOp->copyIRFlags(BinOp);
4184
4185         Entry[Part] = V;
4186       }
4187
4188       addMetadata(Entry, BinOp);
4189       break;
4190     }
4191     case Instruction::Select: {
4192       // Widen selects.
4193       // If the selector is loop invariant we can create a select
4194       // instruction with a scalar condition. Otherwise, use vector-select.
4195       auto *SE = PSE.getSE();
4196       bool InvariantCond =
4197           SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4198       setDebugLocFromInst(Builder, &I);
4199
4200       // The condition can be loop invariant  but still defined inside the
4201       // loop. This means that we can't just use the original 'cond' value.
4202       // We have to take the 'vectorized' value and pick the first lane.
4203       // Instcombine will make this a no-op.
4204       VectorParts &Cond = getVectorValue(I.getOperand(0));
4205       VectorParts &Op0 = getVectorValue(I.getOperand(1));
4206       VectorParts &Op1 = getVectorValue(I.getOperand(2));
4207
4208       Value *ScalarCond =
4209           (VF == 1)
4210               ? Cond[0]
4211               : Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
4212
4213       for (unsigned Part = 0; Part < UF; ++Part) {
4214         Entry[Part] = Builder.CreateSelect(
4215             InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]);
4216       }
4217
4218       addMetadata(Entry, &I);
4219       break;
4220     }
4221
4222     case Instruction::ICmp:
4223     case Instruction::FCmp: {
4224       // Widen compares. Generate vector compares.
4225       bool FCmp = (I.getOpcode() == Instruction::FCmp);
4226       auto *Cmp = dyn_cast<CmpInst>(&I);
4227       setDebugLocFromInst(Builder, Cmp);
4228       VectorParts &A = getVectorValue(Cmp->getOperand(0));
4229       VectorParts &B = getVectorValue(Cmp->getOperand(1));
4230       for (unsigned Part = 0; Part < UF; ++Part) {
4231         Value *C = nullptr;
4232         if (FCmp) {
4233           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
4234           cast<FCmpInst>(C)->copyFastMathFlags(Cmp);
4235         } else {
4236           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
4237         }
4238         Entry[Part] = C;
4239       }
4240
4241       addMetadata(Entry, &I);
4242       break;
4243     }
4244
4245     case Instruction::Store:
4246     case Instruction::Load:
4247       vectorizeMemoryInstruction(&I);
4248       break;
4249     case Instruction::ZExt:
4250     case Instruction::SExt:
4251     case Instruction::FPToUI:
4252     case Instruction::FPToSI:
4253     case Instruction::FPExt:
4254     case Instruction::PtrToInt:
4255     case Instruction::IntToPtr:
4256     case Instruction::SIToFP:
4257     case Instruction::UIToFP:
4258     case Instruction::Trunc:
4259     case Instruction::FPTrunc:
4260     case Instruction::BitCast: {
4261       auto *CI = dyn_cast<CastInst>(&I);
4262       setDebugLocFromInst(Builder, CI);
4263
4264       // Optimize the special case where the source is a constant integer
4265       // induction variable. Notice that we can only optimize the 'trunc' case
4266       // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
4267       // (c) other casts depend on pointer size.
4268       auto ID = Legal->getInductionVars()->lookup(OldInduction);
4269       if (isa<TruncInst>(CI) && CI->getOperand(0) == OldInduction &&
4270           ID.getConstIntStepValue()) {
4271         widenIntInduction(OldInduction, Entry, cast<TruncInst>(CI));
4272         addMetadata(Entry, &I);
4273         break;
4274       }
4275
4276       /// Vectorize casts.
4277       Type *DestTy =
4278           (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4279
4280       VectorParts &A = getVectorValue(CI->getOperand(0));
4281       for (unsigned Part = 0; Part < UF; ++Part)
4282         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
4283       addMetadata(Entry, &I);
4284       break;
4285     }
4286
4287     case Instruction::Call: {
4288       // Ignore dbg intrinsics.
4289       if (isa<DbgInfoIntrinsic>(I))
4290         break;
4291       setDebugLocFromInst(Builder, &I);
4292
4293       Module *M = BB->getParent()->getParent();
4294       auto *CI = cast<CallInst>(&I);
4295
4296       StringRef FnName = CI->getCalledFunction()->getName();
4297       Function *F = CI->getCalledFunction();
4298       Type *RetTy = ToVectorTy(CI->getType(), VF);
4299       SmallVector<Type *, 4> Tys;
4300       for (Value *ArgOperand : CI->arg_operands())
4301         Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4302
4303       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4304       if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
4305                  ID == Intrinsic::lifetime_start)) {
4306         scalarizeInstruction(&I);
4307         break;
4308       }
4309       // The flag shows whether we use Intrinsic or a usual Call for vectorized
4310       // version of the instruction.
4311       // Is it beneficial to perform intrinsic call compared to lib call?
4312       bool NeedToScalarize;
4313       unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4314       bool UseVectorIntrinsic =
4315           ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4316       if (!UseVectorIntrinsic && NeedToScalarize) {
4317         scalarizeInstruction(&I);
4318         break;
4319       }
4320
4321       for (unsigned Part = 0; Part < UF; ++Part) {
4322         SmallVector<Value *, 4> Args;
4323         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4324           Value *Arg = CI->getArgOperand(i);
4325           // Some intrinsics have a scalar argument - don't replace it with a
4326           // vector.
4327           if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
4328             VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
4329             Arg = VectorArg[Part];
4330           }
4331           Args.push_back(Arg);
4332         }
4333
4334         Function *VectorF;
4335         if (UseVectorIntrinsic) {
4336           // Use vector version of the intrinsic.
4337           Type *TysForDecl[] = {CI->getType()};
4338           if (VF > 1)
4339             TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4340           VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4341         } else {
4342           // Use vector version of the library call.
4343           StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4344           assert(!VFnName.empty() && "Vector function name is empty.");
4345           VectorF = M->getFunction(VFnName);
4346           if (!VectorF) {
4347             // Generate a declaration
4348             FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4349             VectorF =
4350                 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4351             VectorF->copyAttributesFrom(F);
4352           }
4353         }
4354         assert(VectorF && "Can't create vector function.");
4355
4356         SmallVector<OperandBundleDef, 1> OpBundles;
4357         CI->getOperandBundlesAsDefs(OpBundles);
4358         CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4359
4360         if (isa<FPMathOperator>(V))
4361           V->copyFastMathFlags(CI);
4362
4363         Entry[Part] = V;
4364       }
4365
4366       addMetadata(Entry, &I);
4367       break;
4368     }
4369
4370     default:
4371       // All other instructions are unsupported. Scalarize them.
4372       scalarizeInstruction(&I);
4373       break;
4374     } // end of switch.
4375   }   // end of for_each instr.
4376 }
4377
4378 void InnerLoopVectorizer::updateAnalysis() {
4379   // Forget the original basic block.
4380   PSE.getSE()->forgetLoop(OrigLoop);
4381
4382   // Update the dominator tree information.
4383   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
4384          "Entry does not dominate exit.");
4385
4386   // We don't predicate stores by this point, so the vector body should be a
4387   // single loop.
4388   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
4389
4390   DT->addNewBlock(LoopMiddleBlock, LoopVectorBody);
4391   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4392   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4393   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4394
4395   DEBUG(DT->verifyDomTree());
4396 }
4397
4398 /// \brief Check whether it is safe to if-convert this phi node.
4399 ///
4400 /// Phi nodes with constant expressions that can trap are not safe to if
4401 /// convert.
4402 static bool canIfConvertPHINodes(BasicBlock *BB) {
4403   for (Instruction &I : *BB) {
4404     auto *Phi = dyn_cast<PHINode>(&I);
4405     if (!Phi)
4406       return true;
4407     for (Value *V : Phi->incoming_values())
4408       if (auto *C = dyn_cast<Constant>(V))
4409         if (C->canTrap())
4410           return false;
4411   }
4412   return true;
4413 }
4414
4415 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4416   if (!EnableIfConversion) {
4417     emitAnalysis(VectorizationReport() << "if-conversion is disabled");
4418     return false;
4419   }
4420
4421   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
4422
4423   // A list of pointers that we can safely read and write to.
4424   SmallPtrSet<Value *, 8> SafePointes;
4425
4426   // Collect safe addresses.
4427   for (BasicBlock *BB : TheLoop->blocks()) {
4428     if (blockNeedsPredication(BB))
4429       continue;
4430
4431     for (Instruction &I : *BB) {
4432       if (auto *LI = dyn_cast<LoadInst>(&I))
4433         SafePointes.insert(LI->getPointerOperand());
4434       else if (auto *SI = dyn_cast<StoreInst>(&I))
4435         SafePointes.insert(SI->getPointerOperand());
4436     }
4437   }
4438
4439   // Collect the blocks that need predication.
4440   BasicBlock *Header = TheLoop->getHeader();
4441   for (BasicBlock *BB : TheLoop->blocks()) {
4442     // We don't support switch statements inside loops.
4443     if (!isa<BranchInst>(BB->getTerminator())) {
4444       emitAnalysis(VectorizationReport(BB->getTerminator())
4445                    << "loop contains a switch statement");
4446       return false;
4447     }
4448
4449     // We must be able to predicate all blocks that need to be predicated.
4450     if (blockNeedsPredication(BB)) {
4451       if (!blockCanBePredicated(BB, SafePointes)) {
4452         emitAnalysis(VectorizationReport(BB->getTerminator())
4453                      << "control flow cannot be substituted for a select");
4454         return false;
4455       }
4456     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4457       emitAnalysis(VectorizationReport(BB->getTerminator())
4458                    << "control flow cannot be substituted for a select");
4459       return false;
4460     }
4461   }
4462
4463   // We can if-convert this loop.
4464   return true;
4465 }
4466
4467 bool LoopVectorizationLegality::canVectorize() {
4468   // We must have a loop in canonical form. Loops with indirectbr in them cannot
4469   // be canonicalized.
4470   if (!TheLoop->getLoopPreheader()) {
4471     emitAnalysis(VectorizationReport()
4472                  << "loop control flow is not understood by vectorizer");
4473     return false;
4474   }
4475
4476   // FIXME: The code is currently dead, since the loop gets sent to
4477   // LoopVectorizationLegality is already an innermost loop.
4478   //
4479   // We can only vectorize innermost loops.
4480   if (!TheLoop->empty()) {
4481     emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
4482     return false;
4483   }
4484
4485   // We must have a single backedge.
4486   if (TheLoop->getNumBackEdges() != 1) {
4487     emitAnalysis(VectorizationReport()
4488                  << "loop control flow is not understood by vectorizer");
4489     return false;
4490   }
4491
4492   // We must have a single exiting block.
4493   if (!TheLoop->getExitingBlock()) {
4494     emitAnalysis(VectorizationReport()
4495                  << "loop control flow is not understood by vectorizer");
4496     return false;
4497   }
4498
4499   // We only handle bottom-tested loops, i.e. loop in which the condition is
4500   // checked at the end of each iteration. With that we can assume that all
4501   // instructions in the loop are executed the same number of times.
4502   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4503     emitAnalysis(VectorizationReport()
4504                  << "loop control flow is not understood by vectorizer");
4505     return false;
4506   }
4507
4508   // We need to have a loop header.
4509   DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
4510                << '\n');
4511
4512   // Check if we can if-convert non-single-bb loops.
4513   unsigned NumBlocks = TheLoop->getNumBlocks();
4514   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4515     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
4516     return false;
4517   }
4518
4519   // ScalarEvolution needs to be able to find the exit count.
4520   const SCEV *ExitCount = PSE.getBackedgeTakenCount();
4521   if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
4522     emitAnalysis(VectorizationReport()
4523                  << "could not determine number of loop iterations");
4524     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
4525     return false;
4526   }
4527
4528   // Check if we can vectorize the instructions and CFG in this loop.
4529   if (!canVectorizeInstrs()) {
4530     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
4531     return false;
4532   }
4533
4534   // Go over each instruction and look at memory deps.
4535   if (!canVectorizeMemory()) {
4536     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4537     return false;
4538   }
4539
4540   // Collect all of the variables that remain uniform after vectorization.
4541   collectLoopUniforms();
4542
4543   DEBUG(dbgs() << "LV: We can vectorize this loop"
4544                << (LAI->getRuntimePointerChecking()->Need
4545                        ? " (with a runtime bound check)"
4546                        : "")
4547                << "!\n");
4548
4549   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4550
4551   // If an override option has been passed in for interleaved accesses, use it.
4552   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4553     UseInterleaved = EnableInterleavedMemAccesses;
4554
4555   // Analyze interleaved memory accesses.
4556   if (UseInterleaved)
4557     InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
4558
4559   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4560   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4561     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4562
4563   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
4564     emitAnalysis(VectorizationReport()
4565                  << "Too many SCEV assumptions need to be made and checked "
4566                  << "at runtime");
4567     DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
4568     return false;
4569   }
4570
4571   // Okay! We can vectorize. At this point we don't have any other mem analysis
4572   // which may limit our maximum vectorization factor, so just return true with
4573   // no restrictions.
4574   return true;
4575 }
4576
4577 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4578   if (Ty->isPointerTy())
4579     return DL.getIntPtrType(Ty);
4580
4581   // It is possible that char's or short's overflow when we ask for the loop's
4582   // trip count, work around this by changing the type size.
4583   if (Ty->getScalarSizeInBits() < 32)
4584     return Type::getInt32Ty(Ty->getContext());
4585
4586   return Ty;
4587 }
4588
4589 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4590   Ty0 = convertPointerToIntegerType(DL, Ty0);
4591   Ty1 = convertPointerToIntegerType(DL, Ty1);
4592   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4593     return Ty0;
4594   return Ty1;
4595 }
4596
4597 /// \brief Check that the instruction has outside loop users and is not an
4598 /// identified reduction variable.
4599 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4600                                SmallPtrSetImpl<Value *> &AllowedExit) {
4601   // Reduction and Induction instructions are allowed to have exit users. All
4602   // other instructions must not have external users.
4603   if (!AllowedExit.count(Inst))
4604     // Check that all of the users of the loop are inside the BB.
4605     for (User *U : Inst->users()) {
4606       Instruction *UI = cast<Instruction>(U);
4607       // This user may be a reduction exit value.
4608       if (!TheLoop->contains(UI)) {
4609         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4610         return true;
4611       }
4612     }
4613   return false;
4614 }
4615
4616 void LoopVectorizationLegality::addInductionPhi(
4617     PHINode *Phi, const InductionDescriptor &ID,
4618     SmallPtrSetImpl<Value *> &AllowedExit) {
4619   Inductions[Phi] = ID;
4620   Type *PhiTy = Phi->getType();
4621   const DataLayout &DL = Phi->getModule()->getDataLayout();
4622
4623   // Get the widest type.
4624   if (!WidestIndTy)
4625     WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4626   else
4627     WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4628
4629   // Int inductions are special because we only allow one IV.
4630   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4631       ID.getConstIntStepValue() &&
4632       ID.getConstIntStepValue()->isOne() &&
4633       isa<Constant>(ID.getStartValue()) &&
4634       cast<Constant>(ID.getStartValue())->isNullValue()) {
4635
4636     // Use the phi node with the widest type as induction. Use the last
4637     // one if there are multiple (no good reason for doing this other
4638     // than it is expedient). We've checked that it begins at zero and
4639     // steps by one, so this is a canonical induction variable.
4640     if (!Induction || PhiTy == WidestIndTy)
4641       Induction = Phi;
4642   }
4643
4644   // Both the PHI node itself, and the "post-increment" value feeding
4645   // back into the PHI node may have external users.
4646   AllowedExit.insert(Phi);
4647   AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
4648
4649   DEBUG(dbgs() << "LV: Found an induction variable.\n");
4650   return;
4651 }
4652
4653 bool LoopVectorizationLegality::canVectorizeInstrs() {
4654   BasicBlock *Header = TheLoop->getHeader();
4655
4656   // Look for the attribute signaling the absence of NaNs.
4657   Function &F = *Header->getParent();
4658   HasFunNoNaNAttr =
4659       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4660
4661   // For each block in the loop.
4662   for (BasicBlock *BB : TheLoop->blocks()) {
4663     // Scan the instructions in the block and look for hazards.
4664     for (Instruction &I : *BB) {
4665       if (auto *Phi = dyn_cast<PHINode>(&I)) {
4666         Type *PhiTy = Phi->getType();
4667         // Check that this PHI type is allowed.
4668         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
4669             !PhiTy->isPointerTy()) {
4670           emitAnalysis(VectorizationReport(Phi)
4671                        << "loop control flow is not understood by vectorizer");
4672           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4673           return false;
4674         }
4675
4676         // If this PHINode is not in the header block, then we know that we
4677         // can convert it to select during if-conversion. No need to check if
4678         // the PHIs in this block are induction or reduction variables.
4679         if (BB != Header) {
4680           // Check that this instruction has no outside users or is an
4681           // identified reduction value with an outside user.
4682           if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
4683             continue;
4684           emitAnalysis(VectorizationReport(Phi)
4685                        << "value could not be identified as "
4686                           "an induction or reduction variable");
4687           return false;
4688         }
4689
4690         // We only allow if-converted PHIs with exactly two incoming values.
4691         if (Phi->getNumIncomingValues() != 2) {
4692           emitAnalysis(VectorizationReport(Phi)
4693                        << "control flow not understood by vectorizer");
4694           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4695           return false;
4696         }
4697
4698         RecurrenceDescriptor RedDes;
4699         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
4700           if (RedDes.hasUnsafeAlgebra())
4701             Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
4702           AllowedExit.insert(RedDes.getLoopExitInstr());
4703           Reductions[Phi] = RedDes;
4704           continue;
4705         }
4706
4707         InductionDescriptor ID;
4708         if (InductionDescriptor::isInductionPHI(Phi, PSE, ID)) {
4709           addInductionPhi(Phi, ID, AllowedExit);
4710           continue;
4711         }
4712
4713         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) {
4714           FirstOrderRecurrences.insert(Phi);
4715           continue;
4716         }
4717
4718         // As a last resort, coerce the PHI to a AddRec expression
4719         // and re-try classifying it a an induction PHI.
4720         if (InductionDescriptor::isInductionPHI(Phi, PSE, ID, true)) {
4721           addInductionPhi(Phi, ID, AllowedExit);
4722           continue;
4723         }
4724
4725         emitAnalysis(VectorizationReport(Phi)
4726                      << "value that could not be identified as "
4727                         "reduction is used outside the loop");
4728         DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
4729         return false;
4730       } // end of PHI handling
4731
4732       // We handle calls that:
4733       //   * Are debug info intrinsics.
4734       //   * Have a mapping to an IR intrinsic.
4735       //   * Have a vector version available.
4736       auto *CI = dyn_cast<CallInst>(&I);
4737       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
4738           !isa<DbgInfoIntrinsic>(CI) &&
4739           !(CI->getCalledFunction() && TLI &&
4740             TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4741         emitAnalysis(VectorizationReport(CI)
4742                      << "call instruction cannot be vectorized");
4743         DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4744         return false;
4745       }
4746
4747       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4748       // second argument is the same (i.e. loop invariant)
4749       if (CI && hasVectorInstrinsicScalarOpd(
4750                     getVectorIntrinsicIDForCall(CI, TLI), 1)) {
4751         auto *SE = PSE.getSE();
4752         if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
4753           emitAnalysis(VectorizationReport(CI)
4754                        << "intrinsic instruction cannot be vectorized");
4755           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4756           return false;
4757         }
4758       }
4759
4760       // Check that the instruction return type is vectorizable.
4761       // Also, we can't vectorize extractelement instructions.
4762       if ((!VectorType::isValidElementType(I.getType()) &&
4763            !I.getType()->isVoidTy()) ||
4764           isa<ExtractElementInst>(I)) {
4765         emitAnalysis(VectorizationReport(&I)
4766                      << "instruction return type cannot be vectorized");
4767         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4768         return false;
4769       }
4770
4771       // Check that the stored type is vectorizable.
4772       if (auto *ST = dyn_cast<StoreInst>(&I)) {
4773         Type *T = ST->getValueOperand()->getType();
4774         if (!VectorType::isValidElementType(T)) {
4775           emitAnalysis(VectorizationReport(ST)
4776                        << "store instruction cannot be vectorized");
4777           return false;
4778         }
4779
4780         // FP instructions can allow unsafe algebra, thus vectorizable by
4781         // non-IEEE-754 compliant SIMD units.
4782         // This applies to floating-point math operations and calls, not memory
4783         // operations, shuffles, or casts, as they don't change precision or
4784         // semantics.
4785       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
4786                  !I.hasUnsafeAlgebra()) {
4787         DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
4788         Hints->setPotentiallyUnsafe();
4789       }
4790
4791       // Reduction instructions are allowed to have exit users.
4792       // All other instructions must not have external users.
4793       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
4794         emitAnalysis(VectorizationReport(&I)
4795                      << "value cannot be used outside the loop");
4796         return false;
4797       }
4798
4799     } // next instr.
4800   }
4801
4802   if (!Induction) {
4803     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4804     if (Inductions.empty()) {
4805       emitAnalysis(VectorizationReport()
4806                    << "loop induction variable could not be identified");
4807       return false;
4808     }
4809   }
4810
4811   // Now we know the widest induction type, check if our found induction
4812   // is the same size. If it's not, unset it here and InnerLoopVectorizer
4813   // will create another.
4814   if (Induction && WidestIndTy != Induction->getType())
4815     Induction = nullptr;
4816
4817   return true;
4818 }
4819
4820 void LoopVectorizationLegality::collectLoopUniforms() {
4821   // We now know that the loop is vectorizable!
4822   // Collect variables that will remain uniform after vectorization.
4823
4824   // If V is not an instruction inside the current loop, it is a Value
4825   // outside of the scope which we are interesting in.
4826   auto isOutOfScope = [&](Value *V) -> bool {
4827     Instruction *I = dyn_cast<Instruction>(V);
4828     return (!I || !TheLoop->contains(I));
4829   };
4830
4831   SetVector<Instruction *> Worklist;
4832   BasicBlock *Latch = TheLoop->getLoopLatch();
4833   // Start with the conditional branch.
4834   if (!isOutOfScope(Latch->getTerminator()->getOperand(0))) {
4835     Instruction *Cmp = cast<Instruction>(Latch->getTerminator()->getOperand(0));
4836     Worklist.insert(Cmp);
4837     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
4838   }
4839
4840   // Also add all consecutive pointer values; these values will be uniform
4841   // after vectorization (and subsequent cleanup).
4842   for (auto *BB : TheLoop->blocks()) {
4843     for (auto &I : *BB) {
4844       if (I.getType()->isPointerTy() && isConsecutivePtr(&I)) {
4845         Worklist.insert(&I);
4846         DEBUG(dbgs() << "LV: Found uniform instruction: " << I << "\n");
4847       }
4848     }
4849   }
4850
4851   // Expand Worklist in topological order: whenever a new instruction
4852   // is added , its users should be either already inside Worklist, or
4853   // out of scope. It ensures a uniform instruction will only be used
4854   // by uniform instructions or out of scope instructions.
4855   unsigned idx = 0;
4856   do {
4857     Instruction *I = Worklist[idx++];
4858
4859     for (auto OV : I->operand_values()) {
4860       if (isOutOfScope(OV))
4861         continue;
4862       auto *OI = cast<Instruction>(OV);
4863       if (all_of(OI->users(), [&](User *U) -> bool {
4864             return isOutOfScope(U) || Worklist.count(cast<Instruction>(U));
4865           })) {
4866         Worklist.insert(OI);
4867         DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
4868       }
4869     }
4870   } while (idx != Worklist.size());
4871
4872   // For an instruction to be added into Worklist above, all its users inside
4873   // the current loop should be already added into Worklist. This condition
4874   // cannot be true for phi instructions which is always in a dependence loop.
4875   // Because any instruction in the dependence cycle always depends on others
4876   // in the cycle to be added into Worklist first, the result is no ones in
4877   // the cycle will be added into Worklist in the end.
4878   // That is why we process PHI separately.
4879   for (auto &Induction : *getInductionVars()) {
4880     auto *PN = Induction.first;
4881     auto *UpdateV = PN->getIncomingValueForBlock(TheLoop->getLoopLatch());
4882     if (all_of(PN->users(),
4883                [&](User *U) -> bool {
4884                  return U == UpdateV || isOutOfScope(U) ||
4885                         Worklist.count(cast<Instruction>(U));
4886                }) &&
4887         all_of(UpdateV->users(), [&](User *U) -> bool {
4888           return U == PN || isOutOfScope(U) ||
4889                  Worklist.count(cast<Instruction>(U));
4890         })) {
4891       Worklist.insert(cast<Instruction>(PN));
4892       Worklist.insert(cast<Instruction>(UpdateV));
4893       DEBUG(dbgs() << "LV: Found uniform instruction: " << *PN << "\n");
4894       DEBUG(dbgs() << "LV: Found uniform instruction: " << *UpdateV << "\n");
4895     }
4896   }
4897
4898   Uniforms.insert(Worklist.begin(), Worklist.end());
4899 }
4900
4901 bool LoopVectorizationLegality::canVectorizeMemory() {
4902   LAI = &(*GetLAA)(*TheLoop);
4903   InterleaveInfo.setLAI(LAI);
4904   auto &OptionalReport = LAI->getReport();
4905   if (OptionalReport)
4906     emitAnalysis(VectorizationReport(*OptionalReport));
4907   if (!LAI->canVectorizeMemory())
4908     return false;
4909
4910   if (LAI->hasStoreToLoopInvariantAddress()) {
4911     emitAnalysis(
4912         VectorizationReport()
4913         << "write to a loop invariant address could not be vectorized");
4914     DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4915     return false;
4916   }
4917
4918   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4919   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
4920
4921   return true;
4922 }
4923
4924 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4925   Value *In0 = const_cast<Value *>(V);
4926   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4927   if (!PN)
4928     return false;
4929
4930   return Inductions.count(PN);
4931 }
4932
4933 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
4934   return FirstOrderRecurrences.count(Phi);
4935 }
4936
4937 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4938   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4939 }
4940
4941 bool LoopVectorizationLegality::blockCanBePredicated(
4942     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
4943   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4944
4945   for (Instruction &I : *BB) {
4946     // Check that we don't have a constant expression that can trap as operand.
4947     for (Value *Operand : I.operands()) {
4948       if (auto *C = dyn_cast<Constant>(Operand))
4949         if (C->canTrap())
4950           return false;
4951     }
4952     // We might be able to hoist the load.
4953     if (I.mayReadFromMemory()) {
4954       auto *LI = dyn_cast<LoadInst>(&I);
4955       if (!LI)
4956         return false;
4957       if (!SafePtrs.count(LI->getPointerOperand())) {
4958         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
4959             isLegalMaskedGather(LI->getType())) {
4960           MaskedOp.insert(LI);
4961           continue;
4962         }
4963         // !llvm.mem.parallel_loop_access implies if-conversion safety.
4964         if (IsAnnotatedParallel)
4965           continue;
4966         return false;
4967       }
4968     }
4969
4970     // We don't predicate stores at the moment.
4971     if (I.mayWriteToMemory()) {
4972       auto *SI = dyn_cast<StoreInst>(&I);
4973       // We only support predication of stores in basic blocks with one
4974       // predecessor.
4975       if (!SI)
4976         return false;
4977
4978       // Build a masked store if it is legal for the target.
4979       if (isLegalMaskedStore(SI->getValueOperand()->getType(),
4980                              SI->getPointerOperand()) ||
4981           isLegalMaskedScatter(SI->getValueOperand()->getType())) {
4982         MaskedOp.insert(SI);
4983         continue;
4984       }
4985
4986       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4987       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4988
4989       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4990           !isSinglePredecessor)
4991         return false;
4992     }
4993     if (I.mayThrow())
4994       return false;
4995
4996     // The instructions below can trap.
4997     switch (I.getOpcode()) {
4998     default:
4999       continue;
5000     case Instruction::UDiv:
5001     case Instruction::SDiv:
5002     case Instruction::URem:
5003     case Instruction::SRem:
5004       return false;
5005     }
5006   }
5007
5008   return true;
5009 }
5010
5011 void InterleavedAccessInfo::collectConstStrideAccesses(
5012     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
5013     const ValueToValueMap &Strides) {
5014
5015   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5016
5017   // Since it's desired that the load/store instructions be maintained in
5018   // "program order" for the interleaved access analysis, we have to visit the
5019   // blocks in the loop in reverse postorder (i.e., in a topological order).
5020   // Such an ordering will ensure that any load/store that may be executed
5021   // before a second load/store will precede the second load/store in
5022   // AccessStrideInfo.
5023   LoopBlocksDFS DFS(TheLoop);
5024   DFS.perform(LI);
5025   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
5026     for (auto &I : *BB) {
5027       auto *LI = dyn_cast<LoadInst>(&I);
5028       auto *SI = dyn_cast<StoreInst>(&I);
5029       if (!LI && !SI)
5030         continue;
5031
5032       Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
5033       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides);
5034
5035       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
5036       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
5037       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
5038
5039       // An alignment of 0 means target ABI alignment.
5040       unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
5041       if (!Align)
5042         Align = DL.getABITypeAlignment(PtrTy->getElementType());
5043
5044       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
5045     }
5046 }
5047
5048 // Analyze interleaved accesses and collect them into interleaved load and
5049 // store groups.
5050 //
5051 // When generating code for an interleaved load group, we effectively hoist all
5052 // loads in the group to the location of the first load in program order. When
5053 // generating code for an interleaved store group, we sink all stores to the
5054 // location of the last store. This code motion can change the order of load
5055 // and store instructions and may break dependences.
5056 //
5057 // The code generation strategy mentioned above ensures that we won't violate
5058 // any write-after-read (WAR) dependences.
5059 //
5060 // E.g., for the WAR dependence:  a = A[i];      // (1)
5061 //                                A[i] = b;      // (2)
5062 //
5063 // The store group of (2) is always inserted at or below (2), and the load
5064 // group of (1) is always inserted at or above (1). Thus, the instructions will
5065 // never be reordered. All other dependences are checked to ensure the
5066 // correctness of the instruction reordering.
5067 //
5068 // The algorithm visits all memory accesses in the loop in bottom-up program
5069 // order. Program order is established by traversing the blocks in the loop in
5070 // reverse postorder when collecting the accesses.
5071 //
5072 // We visit the memory accesses in bottom-up order because it can simplify the
5073 // construction of store groups in the presence of write-after-write (WAW)
5074 // dependences.
5075 //
5076 // E.g., for the WAW dependence:  A[i] = a;      // (1)
5077 //                                A[i] = b;      // (2)
5078 //                                A[i + 1] = c;  // (3)
5079 //
5080 // We will first create a store group with (3) and (2). (1) can't be added to
5081 // this group because it and (2) are dependent. However, (1) can be grouped
5082 // with other accesses that may precede it in program order. Note that a
5083 // bottom-up order does not imply that WAW dependences should not be checked.
5084 void InterleavedAccessInfo::analyzeInterleaving(
5085     const ValueToValueMap &Strides) {
5086   DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
5087
5088   // Holds all accesses with a constant stride.
5089   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
5090   collectConstStrideAccesses(AccessStrideInfo, Strides);
5091
5092   if (AccessStrideInfo.empty())
5093     return;
5094
5095   // Collect the dependences in the loop.
5096   collectDependences();
5097
5098   // Holds all interleaved store groups temporarily.
5099   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
5100   // Holds all interleaved load groups temporarily.
5101   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
5102
5103   // Search in bottom-up program order for pairs of accesses (A and B) that can
5104   // form interleaved load or store groups. In the algorithm below, access A
5105   // precedes access B in program order. We initialize a group for B in the
5106   // outer loop of the algorithm, and then in the inner loop, we attempt to
5107   // insert each A into B's group if:
5108   //
5109   //  1. A and B have the same stride,
5110   //  2. A and B have the same memory object size, and
5111   //  3. A belongs in B's group according to its distance from B.
5112   //
5113   // Special care is taken to ensure group formation will not break any
5114   // dependences.
5115   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
5116        BI != E; ++BI) {
5117     Instruction *B = BI->first;
5118     StrideDescriptor DesB = BI->second;
5119
5120     // Initialize a group for B if it has an allowable stride. Even if we don't
5121     // create a group for B, we continue with the bottom-up algorithm to ensure
5122     // we don't break any of B's dependences.
5123     InterleaveGroup *Group = nullptr;
5124     if (isStrided(DesB.Stride)) {
5125       Group = getInterleaveGroup(B);
5126       if (!Group) {
5127         DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n');
5128         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
5129       }
5130       if (B->mayWriteToMemory())
5131         StoreGroups.insert(Group);
5132       else
5133         LoadGroups.insert(Group);
5134     }
5135
5136     for (auto AI = std::next(BI); AI != E; ++AI) {
5137       Instruction *A = AI->first;
5138       StrideDescriptor DesA = AI->second;
5139
5140       // Our code motion strategy implies that we can't have dependences
5141       // between accesses in an interleaved group and other accesses located
5142       // between the first and last member of the group. Note that this also
5143       // means that a group can't have more than one member at a given offset.
5144       // The accesses in a group can have dependences with other accesses, but
5145       // we must ensure we don't extend the boundaries of the group such that
5146       // we encompass those dependent accesses.
5147       //
5148       // For example, assume we have the sequence of accesses shown below in a
5149       // stride-2 loop:
5150       //
5151       //  (1, 2) is a group | A[i]   = a;  // (1)
5152       //                    | A[i-1] = b;  // (2) |
5153       //                      A[i-3] = c;  // (3)
5154       //                      A[i]   = d;  // (4) | (2, 4) is not a group
5155       //
5156       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
5157       // but not with (4). If we did, the dependent access (3) would be within
5158       // the boundaries of the (2, 4) group.
5159       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
5160
5161         // If a dependence exists and A is already in a group, we know that A
5162         // must be a store since A precedes B and WAR dependences are allowed.
5163         // Thus, A would be sunk below B. We release A's group to prevent this
5164         // illegal code motion. A will then be free to form another group with
5165         // instructions that precede it.
5166         if (isInterleaved(A)) {
5167           InterleaveGroup *StoreGroup = getInterleaveGroup(A);
5168           StoreGroups.remove(StoreGroup);
5169           releaseGroup(StoreGroup);
5170         }
5171
5172         // If a dependence exists and A is not already in a group (or it was
5173         // and we just released it), B might be hoisted above A (if B is a
5174         // load) or another store might be sunk below A (if B is a store). In
5175         // either case, we can't add additional instructions to B's group. B
5176         // will only form a group with instructions that it precedes.
5177         break;
5178       }
5179
5180       // At this point, we've checked for illegal code motion. If either A or B
5181       // isn't strided, there's nothing left to do.
5182       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
5183         continue;
5184
5185       // Ignore A if it's already in a group or isn't the same kind of memory
5186       // operation as B.
5187       if (isInterleaved(A) || A->mayReadFromMemory() != B->mayReadFromMemory())
5188         continue;
5189
5190       // Check rules 1 and 2. Ignore A if its stride or size is different from
5191       // that of B.
5192       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
5193         continue;
5194
5195       // Calculate the distance from A to B.
5196       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
5197           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
5198       if (!DistToB)
5199         continue;
5200       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
5201
5202       // Check rule 3. Ignore A if its distance to B is not a multiple of the
5203       // size.
5204       if (DistanceToB % static_cast<int64_t>(DesB.Size))
5205         continue;
5206
5207       // Ignore A if either A or B is in a predicated block. Although we
5208       // currently prevent group formation for predicated accesses, we may be
5209       // able to relax this limitation in the future once we handle more
5210       // complicated blocks.
5211       if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
5212         continue;
5213
5214       // The index of A is the index of B plus A's distance to B in multiples
5215       // of the size.
5216       int IndexA =
5217           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
5218
5219       // Try to insert A into B's group.
5220       if (Group->insertMember(A, IndexA, DesA.Align)) {
5221         DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
5222                      << "    into the interleave group with" << *B << '\n');
5223         InterleaveGroupMap[A] = Group;
5224
5225         // Set the first load in program order as the insert position.
5226         if (A->mayReadFromMemory())
5227           Group->setInsertPos(A);
5228       }
5229     } // Iteration over A accesses.
5230   } // Iteration over B accesses.
5231
5232   // Remove interleaved store groups with gaps.
5233   for (InterleaveGroup *Group : StoreGroups)
5234     if (Group->getNumMembers() != Group->getFactor())
5235       releaseGroup(Group);
5236
5237   // If there is a non-reversed interleaved load group with gaps, we will need
5238   // to execute at least one scalar epilogue iteration. This will ensure that
5239   // we don't speculatively access memory out-of-bounds. Note that we only need
5240   // to look for a member at index factor - 1, since every group must have a
5241   // member at index zero.
5242   for (InterleaveGroup *Group : LoadGroups)
5243     if (!Group->getMember(Group->getFactor() - 1)) {
5244       if (Group->isReverse()) {
5245         releaseGroup(Group);
5246       } else {
5247         DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
5248         RequiresScalarEpilogue = true;
5249       }
5250     }
5251 }
5252
5253 LoopVectorizationCostModel::VectorizationFactor
5254 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
5255   // Width 1 means no vectorize
5256   VectorizationFactor Factor = {1U, 0U};
5257   if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
5258     emitAnalysis(
5259         VectorizationReport()
5260         << "runtime pointer checks needed. Enable vectorization of this "
5261            "loop with '#pragma clang loop vectorize(enable)' when "
5262            "compiling with -Os/-Oz");
5263     DEBUG(dbgs()
5264           << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
5265     return Factor;
5266   }
5267
5268   if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
5269     emitAnalysis(
5270         VectorizationReport()
5271         << "store that is conditionally executed prevents vectorization");
5272     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5273     return Factor;
5274   }
5275
5276   // Find the trip count.
5277   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5278   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5279
5280   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5281   unsigned SmallestType, WidestType;
5282   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5283   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5284   unsigned MaxSafeDepDist = -1U;
5285
5286   // Get the maximum safe dependence distance in bits computed by LAA. If the
5287   // loop contains any interleaved accesses, we divide the dependence distance
5288   // by the maximum interleave factor of all interleaved groups. Note that
5289   // although the division ensures correctness, this is a fairly conservative
5290   // computation because the maximum distance computed by LAA may not involve
5291   // any of the interleaved accesses.
5292   if (Legal->getMaxSafeDepDistBytes() != -1U)
5293     MaxSafeDepDist =
5294         Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor();
5295
5296   WidestRegister =
5297       ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist);
5298   unsigned MaxVectorSize = WidestRegister / WidestType;
5299
5300   DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
5301                << WidestType << " bits.\n");
5302   DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister
5303                << " bits.\n");
5304
5305   if (MaxVectorSize == 0) {
5306     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5307     MaxVectorSize = 1;
5308   }
5309
5310   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
5311                                 " into one vector!");
5312
5313   unsigned VF = MaxVectorSize;
5314   if (MaximizeBandwidth && !OptForSize) {
5315     // Collect all viable vectorization factors.
5316     SmallVector<unsigned, 8> VFs;
5317     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
5318     for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
5319       VFs.push_back(VS);
5320
5321     // For each VF calculate its register usage.
5322     auto RUs = calculateRegisterUsage(VFs);
5323
5324     // Select the largest VF which doesn't require more registers than existing
5325     // ones.
5326     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
5327     for (int i = RUs.size() - 1; i >= 0; --i) {
5328       if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
5329         VF = VFs[i];
5330         break;
5331       }
5332     }
5333   }
5334
5335   // If we optimize the program for size, avoid creating the tail loop.
5336   if (OptForSize) {
5337     // If we are unable to calculate the trip count then don't try to vectorize.
5338     if (TC < 2) {
5339       emitAnalysis(
5340           VectorizationReport()
5341           << "unable to calculate the loop count due to complex control flow");
5342       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
5343       return Factor;
5344     }
5345
5346     // Find the maximum SIMD width that can fit within the trip count.
5347     VF = TC % MaxVectorSize;
5348
5349     if (VF == 0)
5350       VF = MaxVectorSize;
5351     else {
5352       // If the trip count that we found modulo the vectorization factor is not
5353       // zero then we require a tail.
5354       emitAnalysis(VectorizationReport()
5355                    << "cannot optimize for size and vectorize at the "
5356                       "same time. Enable vectorization of this loop "
5357                       "with '#pragma clang loop vectorize(enable)' "
5358                       "when compiling with -Os/-Oz");
5359       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
5360       return Factor;
5361     }
5362   }
5363
5364   int UserVF = Hints->getWidth();
5365   if (UserVF != 0) {
5366     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5367     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5368
5369     Factor.Width = UserVF;
5370     return Factor;
5371   }
5372
5373   float Cost = expectedCost(1).first;
5374 #ifndef NDEBUG
5375   const float ScalarCost = Cost;
5376 #endif /* NDEBUG */
5377   unsigned Width = 1;
5378   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5379
5380   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5381   // Ignore scalar width, because the user explicitly wants vectorization.
5382   if (ForceVectorization && VF > 1) {
5383     Width = 2;
5384     Cost = expectedCost(Width).first / (float)Width;
5385   }
5386
5387   for (unsigned i = 2; i <= VF; i *= 2) {
5388     // Notice that the vector loop needs to be executed less times, so
5389     // we need to divide the cost of the vector loops by the width of
5390     // the vector elements.
5391     VectorizationCostTy C = expectedCost(i);
5392     float VectorCost = C.first / (float)i;
5393     DEBUG(dbgs() << "LV: Vector loop of width " << i
5394                  << " costs: " << (int)VectorCost << ".\n");
5395     if (!C.second && !ForceVectorization) {
5396       DEBUG(
5397           dbgs() << "LV: Not considering vector loop of width " << i
5398                  << " because it will not generate any vector instructions.\n");
5399       continue;
5400     }
5401     if (VectorCost < Cost) {
5402       Cost = VectorCost;
5403       Width = i;
5404     }
5405   }
5406
5407   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5408         << "LV: Vectorization seems to be not beneficial, "
5409         << "but was forced by a user.\n");
5410   DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
5411   Factor.Width = Width;
5412   Factor.Cost = Width * Cost;
5413   return Factor;
5414 }
5415
5416 std::pair<unsigned, unsigned>
5417 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5418   unsigned MinWidth = -1U;
5419   unsigned MaxWidth = 8;
5420   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5421
5422   // For each block.
5423   for (BasicBlock *BB : TheLoop->blocks()) {
5424     // For each instruction in the loop.
5425     for (Instruction &I : *BB) {
5426       Type *T = I.getType();
5427
5428       // Skip ignored values.
5429       if (ValuesToIgnore.count(&I))
5430         continue;
5431
5432       // Only examine Loads, Stores and PHINodes.
5433       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5434         continue;
5435
5436       // Examine PHI nodes that are reduction variables. Update the type to
5437       // account for the recurrence type.
5438       if (auto *PN = dyn_cast<PHINode>(&I)) {
5439         if (!Legal->isReductionVariable(PN))
5440           continue;
5441         RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
5442         T = RdxDesc.getRecurrenceType();
5443       }
5444
5445       // Examine the stored values.
5446       if (auto *ST = dyn_cast<StoreInst>(&I))
5447         T = ST->getValueOperand()->getType();
5448
5449       // Ignore loaded pointer types and stored pointer types that are not
5450       // consecutive. However, we do want to take consecutive stores/loads of
5451       // pointer vectors into account.
5452       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I))
5453         continue;
5454
5455       MinWidth = std::min(MinWidth,
5456                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5457       MaxWidth = std::max(MaxWidth,
5458                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5459     }
5460   }
5461
5462   return {MinWidth, MaxWidth};
5463 }
5464
5465 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
5466                                                            unsigned VF,
5467                                                            unsigned LoopCost) {
5468
5469   // -- The interleave heuristics --
5470   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5471   // There are many micro-architectural considerations that we can't predict
5472   // at this level. For example, frontend pressure (on decode or fetch) due to
5473   // code size, or the number and capabilities of the execution ports.
5474   //
5475   // We use the following heuristics to select the interleave count:
5476   // 1. If the code has reductions, then we interleave to break the cross
5477   // iteration dependency.
5478   // 2. If the loop is really small, then we interleave to reduce the loop
5479   // overhead.
5480   // 3. We don't interleave if we think that we will spill registers to memory
5481   // due to the increased register pressure.
5482
5483   // When we optimize for size, we don't interleave.
5484   if (OptForSize)
5485     return 1;
5486
5487   // We used the distance for the interleave count.
5488   if (Legal->getMaxSafeDepDistBytes() != -1U)
5489     return 1;
5490
5491   // Do not interleave loops with a relatively small trip count.
5492   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5493   if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
5494     return 1;
5495
5496   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5497   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5498                << " registers\n");
5499
5500   if (VF == 1) {
5501     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5502       TargetNumRegisters = ForceTargetNumScalarRegs;
5503   } else {
5504     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5505       TargetNumRegisters = ForceTargetNumVectorRegs;
5506   }
5507
5508   RegisterUsage R = calculateRegisterUsage({VF})[0];
5509   // We divide by these constants so assume that we have at least one
5510   // instruction that uses at least one register.
5511   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5512   R.NumInstructions = std::max(R.NumInstructions, 1U);
5513
5514   // We calculate the interleave count using the following formula.
5515   // Subtract the number of loop invariants from the number of available
5516   // registers. These registers are used by all of the interleaved instances.
5517   // Next, divide the remaining registers by the number of registers that is
5518   // required by the loop, in order to estimate how many parallel instances
5519   // fit without causing spills. All of this is rounded down if necessary to be
5520   // a power of two. We want power of two interleave count to simplify any
5521   // addressing operations or alignment considerations.
5522   unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5523                               R.MaxLocalUsers);
5524
5525   // Don't count the induction variable as interleaved.
5526   if (EnableIndVarRegisterHeur)
5527     IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5528                        std::max(1U, (R.MaxLocalUsers - 1)));
5529
5530   // Clamp the interleave ranges to reasonable counts.
5531   unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
5532
5533   // Check if the user has overridden the max.
5534   if (VF == 1) {
5535     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5536       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5537   } else {
5538     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5539       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5540   }
5541
5542   // If we did not calculate the cost for VF (because the user selected the VF)
5543   // then we calculate the cost of VF here.
5544   if (LoopCost == 0)
5545     LoopCost = expectedCost(VF).first;
5546
5547   // Clamp the calculated IC to be between the 1 and the max interleave count
5548   // that the target allows.
5549   if (IC > MaxInterleaveCount)
5550     IC = MaxInterleaveCount;
5551   else if (IC < 1)
5552     IC = 1;
5553
5554   // Interleave if we vectorized this loop and there is a reduction that could
5555   // benefit from interleaving.
5556   if (VF > 1 && Legal->getReductionVars()->size()) {
5557     DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5558     return IC;
5559   }
5560
5561   // Note that if we've already vectorized the loop we will have done the
5562   // runtime check and so interleaving won't require further checks.
5563   bool InterleavingRequiresRuntimePointerCheck =
5564       (VF == 1 && Legal->getRuntimePointerChecking()->Need);
5565
5566   // We want to interleave small loops in order to reduce the loop overhead and
5567   // potentially expose ILP opportunities.
5568   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5569   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
5570     // We assume that the cost overhead is 1 and we use the cost model
5571     // to estimate the cost of the loop and interleave until the cost of the
5572     // loop overhead is about 5% of the cost of the loop.
5573     unsigned SmallIC =
5574         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5575
5576     // Interleave until store/load ports (estimated by max interleave count) are
5577     // saturated.
5578     unsigned NumStores = Legal->getNumStores();
5579     unsigned NumLoads = Legal->getNumLoads();
5580     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5581     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5582
5583     // If we have a scalar reduction (vector reductions are already dealt with
5584     // by this point), we can increase the critical path length if the loop
5585     // we're interleaving is inside another loop. Limit, by default to 2, so the
5586     // critical path only gets increased by one reduction operation.
5587     if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) {
5588       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5589       SmallIC = std::min(SmallIC, F);
5590       StoresIC = std::min(StoresIC, F);
5591       LoadsIC = std::min(LoadsIC, F);
5592     }
5593
5594     if (EnableLoadStoreRuntimeInterleave &&
5595         std::max(StoresIC, LoadsIC) > SmallIC) {
5596       DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5597       return std::max(StoresIC, LoadsIC);
5598     }
5599
5600     DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5601     return SmallIC;
5602   }
5603
5604   // Interleave if this is a large loop (small loops are already dealt with by
5605   // this point) that could benefit from interleaving.
5606   bool HasReductions = (Legal->getReductionVars()->size() > 0);
5607   if (TTI.enableAggressiveInterleaving(HasReductions)) {
5608     DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5609     return IC;
5610   }
5611
5612   DEBUG(dbgs() << "LV: Not Interleaving.\n");
5613   return 1;
5614 }
5615
5616 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5617 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
5618   // This function calculates the register usage by measuring the highest number
5619   // of values that are alive at a single location. Obviously, this is a very
5620   // rough estimation. We scan the loop in a topological order in order and
5621   // assign a number to each instruction. We use RPO to ensure that defs are
5622   // met before their users. We assume that each instruction that has in-loop
5623   // users starts an interval. We record every time that an in-loop value is
5624   // used, so we have a list of the first and last occurrences of each
5625   // instruction. Next, we transpose this data structure into a multi map that
5626   // holds the list of intervals that *end* at a specific location. This multi
5627   // map allows us to perform a linear search. We scan the instructions linearly
5628   // and record each time that a new interval starts, by placing it in a set.
5629   // If we find this value in the multi-map then we remove it from the set.
5630   // The max register usage is the maximum size of the set.
5631   // We also search for instructions that are defined outside the loop, but are
5632   // used inside the loop. We need this number separately from the max-interval
5633   // usage number because when we unroll, loop-invariant values do not take
5634   // more register.
5635   LoopBlocksDFS DFS(TheLoop);
5636   DFS.perform(LI);
5637
5638   RegisterUsage RU;
5639   RU.NumInstructions = 0;
5640
5641   // Each 'key' in the map opens a new interval. The values
5642   // of the map are the index of the 'last seen' usage of the
5643   // instruction that is the key.
5644   typedef DenseMap<Instruction *, unsigned> IntervalMap;
5645   // Maps instruction to its index.
5646   DenseMap<unsigned, Instruction *> IdxToInstr;
5647   // Marks the end of each interval.
5648   IntervalMap EndPoint;
5649   // Saves the list of instruction indices that are used in the loop.
5650   SmallSet<Instruction *, 8> Ends;
5651   // Saves the list of values that are used in the loop but are
5652   // defined outside the loop, such as arguments and constants.
5653   SmallPtrSet<Value *, 8> LoopInvariants;
5654
5655   unsigned Index = 0;
5656   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5657     RU.NumInstructions += BB->size();
5658     for (Instruction &I : *BB) {
5659       IdxToInstr[Index++] = &I;
5660
5661       // Save the end location of each USE.
5662       for (Value *U : I.operands()) {
5663         auto *Instr = dyn_cast<Instruction>(U);
5664
5665         // Ignore non-instruction values such as arguments, constants, etc.
5666         if (!Instr)
5667           continue;
5668
5669         // If this instruction is outside the loop then record it and continue.
5670         if (!TheLoop->contains(Instr)) {
5671           LoopInvariants.insert(Instr);
5672           continue;
5673         }
5674
5675         // Overwrite previous end points.
5676         EndPoint[Instr] = Index;
5677         Ends.insert(Instr);
5678       }
5679     }
5680   }
5681
5682   // Saves the list of intervals that end with the index in 'key'.
5683   typedef SmallVector<Instruction *, 2> InstrList;
5684   DenseMap<unsigned, InstrList> TransposeEnds;
5685
5686   // Transpose the EndPoints to a list of values that end at each index.
5687   for (auto &Interval : EndPoint)
5688     TransposeEnds[Interval.second].push_back(Interval.first);
5689
5690   SmallSet<Instruction *, 8> OpenIntervals;
5691
5692   // Get the size of the widest register.
5693   unsigned MaxSafeDepDist = -1U;
5694   if (Legal->getMaxSafeDepDistBytes() != -1U)
5695     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5696   unsigned WidestRegister =
5697       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
5698   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5699
5700   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5701   SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
5702
5703   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5704
5705   // A lambda that gets the register usage for the given type and VF.
5706   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
5707     if (Ty->isTokenTy())
5708       return 0U;
5709     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5710     return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5711   };
5712
5713   for (unsigned int i = 0; i < Index; ++i) {
5714     Instruction *I = IdxToInstr[i];
5715     // Ignore instructions that are never used within the loop.
5716     if (!Ends.count(I))
5717       continue;
5718
5719     // Remove all of the instructions that end at this location.
5720     InstrList &List = TransposeEnds[i];
5721     for (Instruction *ToRemove : List)
5722       OpenIntervals.erase(ToRemove);
5723
5724     // Skip ignored values.
5725     if (ValuesToIgnore.count(I))
5726       continue;
5727
5728     // For each VF find the maximum usage of registers.
5729     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5730       if (VFs[j] == 1) {
5731         MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
5732         continue;
5733       }
5734
5735       // Count the number of live intervals.
5736       unsigned RegUsage = 0;
5737       for (auto Inst : OpenIntervals) {
5738         // Skip ignored values for VF > 1.
5739         if (VecValuesToIgnore.count(Inst))
5740           continue;
5741         RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
5742       }
5743       MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
5744     }
5745
5746     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
5747                  << OpenIntervals.size() << '\n');
5748
5749     // Add the current instruction to the list of open intervals.
5750     OpenIntervals.insert(I);
5751   }
5752
5753   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
5754     unsigned Invariant = 0;
5755     if (VFs[i] == 1)
5756       Invariant = LoopInvariants.size();
5757     else {
5758       for (auto Inst : LoopInvariants)
5759         Invariant += GetRegUsage(Inst->getType(), VFs[i]);
5760     }
5761
5762     DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
5763     DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
5764     DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5765     DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
5766
5767     RU.LoopInvariantRegs = Invariant;
5768     RU.MaxLocalUsers = MaxUsages[i];
5769     RUs[i] = RU;
5770   }
5771
5772   return RUs;
5773 }
5774
5775 LoopVectorizationCostModel::VectorizationCostTy
5776 LoopVectorizationCostModel::expectedCost(unsigned VF) {
5777   VectorizationCostTy Cost;
5778
5779   // For each block.
5780   for (BasicBlock *BB : TheLoop->blocks()) {
5781     VectorizationCostTy BlockCost;
5782
5783     // For each instruction in the old loop.
5784     for (Instruction &I : *BB) {
5785       // Skip dbg intrinsics.
5786       if (isa<DbgInfoIntrinsic>(I))
5787         continue;
5788
5789       // Skip ignored values.
5790       if (ValuesToIgnore.count(&I))
5791         continue;
5792
5793       VectorizationCostTy C = getInstructionCost(&I, VF);
5794
5795       // Check if we should override the cost.
5796       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5797         C.first = ForceTargetInstructionCost;
5798
5799       BlockCost.first += C.first;
5800       BlockCost.second |= C.second;
5801       DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "
5802                    << VF << " For instruction: " << I << '\n');
5803     }
5804
5805     // We assume that if-converted blocks have a 50% chance of being executed.
5806     // When the code is scalar then some of the blocks are avoided due to CF.
5807     // When the code is vectorized we execute all code paths.
5808     if (VF == 1 && Legal->blockNeedsPredication(BB))
5809       BlockCost.first /= 2;
5810
5811     Cost.first += BlockCost.first;
5812     Cost.second |= BlockCost.second;
5813   }
5814
5815   return Cost;
5816 }
5817
5818 /// \brief Check if the load/store instruction \p I may be translated into
5819 /// gather/scatter during vectorization.
5820 ///
5821 /// Pointer \p Ptr specifies address in memory for the given scalar memory
5822 /// instruction. We need it to retrieve data type.
5823 /// Using gather/scatter is possible when it is supported by target.
5824 static bool isGatherOrScatterLegal(Instruction *I, Value *Ptr,
5825                                    LoopVectorizationLegality *Legal) {
5826   auto *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
5827   return (isa<LoadInst>(I) && Legal->isLegalMaskedGather(DataTy)) ||
5828          (isa<StoreInst>(I) && Legal->isLegalMaskedScatter(DataTy));
5829 }
5830
5831 /// \brief Check whether the address computation for a non-consecutive memory
5832 /// access looks like an unlikely candidate for being merged into the indexing
5833 /// mode.
5834 ///
5835 /// We look for a GEP which has one index that is an induction variable and all
5836 /// other indices are loop invariant. If the stride of this access is also
5837 /// within a small bound we decide that this address computation can likely be
5838 /// merged into the addressing mode.
5839 /// In all other cases, we identify the address computation as complex.
5840 static bool isLikelyComplexAddressComputation(Value *Ptr,
5841                                               LoopVectorizationLegality *Legal,
5842                                               ScalarEvolution *SE,
5843                                               const Loop *TheLoop) {
5844   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5845   if (!Gep)
5846     return true;
5847
5848   // We are looking for a gep with all loop invariant indices except for one
5849   // which should be an induction variable.
5850   unsigned NumOperands = Gep->getNumOperands();
5851   for (unsigned i = 1; i < NumOperands; ++i) {
5852     Value *Opd = Gep->getOperand(i);
5853     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5854         !Legal->isInductionVariable(Opd))
5855       return true;
5856   }
5857
5858   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5859   // can likely be merged into the address computation.
5860   unsigned MaxMergeDistance = 64;
5861
5862   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5863   if (!AddRec)
5864     return true;
5865
5866   // Check the step is constant.
5867   const SCEV *Step = AddRec->getStepRecurrence(*SE);
5868   // Calculate the pointer stride and check if it is consecutive.
5869   const auto *C = dyn_cast<SCEVConstant>(Step);
5870   if (!C)
5871     return true;
5872
5873   const APInt &APStepVal = C->getAPInt();
5874
5875   // Huge step value - give up.
5876   if (APStepVal.getBitWidth() > 64)
5877     return true;
5878
5879   int64_t StepVal = APStepVal.getSExtValue();
5880
5881   return StepVal > MaxMergeDistance;
5882 }
5883
5884 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5885   return Legal->hasStride(I->getOperand(0)) ||
5886          Legal->hasStride(I->getOperand(1));
5887 }
5888
5889 LoopVectorizationCostModel::VectorizationCostTy
5890 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5891   // If we know that this instruction will remain uniform, check the cost of
5892   // the scalar version.
5893   if (Legal->isUniformAfterVectorization(I))
5894     VF = 1;
5895
5896   Type *VectorTy;
5897   unsigned C = getInstructionCost(I, VF, VectorTy);
5898
5899   bool TypeNotScalarized =
5900       VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF;
5901   return VectorizationCostTy(C, TypeNotScalarized);
5902 }
5903
5904 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
5905                                                         unsigned VF,
5906                                                         Type *&VectorTy) {
5907   Type *RetTy = I->getType();
5908   if (VF > 1 && MinBWs.count(I))
5909     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
5910   VectorTy = ToVectorTy(RetTy, VF);
5911   auto SE = PSE.getSE();
5912
5913   // TODO: We need to estimate the cost of intrinsic calls.
5914   switch (I->getOpcode()) {
5915   case Instruction::GetElementPtr:
5916     // We mark this instruction as zero-cost because the cost of GEPs in
5917     // vectorized code depends on whether the corresponding memory instruction
5918     // is scalarized or not. Therefore, we handle GEPs with the memory
5919     // instruction cost.
5920     return 0;
5921   case Instruction::Br: {
5922     return TTI.getCFInstrCost(I->getOpcode());
5923   }
5924   case Instruction::PHI: {
5925     auto *Phi = cast<PHINode>(I);
5926
5927     // First-order recurrences are replaced by vector shuffles inside the loop.
5928     if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
5929       return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5930                                 VectorTy, VF - 1, VectorTy);
5931
5932     // TODO: IF-converted IFs become selects.
5933     return 0;
5934   }
5935   case Instruction::Add:
5936   case Instruction::FAdd:
5937   case Instruction::Sub:
5938   case Instruction::FSub:
5939   case Instruction::Mul:
5940   case Instruction::FMul:
5941   case Instruction::UDiv:
5942   case Instruction::SDiv:
5943   case Instruction::FDiv:
5944   case Instruction::URem:
5945   case Instruction::SRem:
5946   case Instruction::FRem:
5947   case Instruction::Shl:
5948   case Instruction::LShr:
5949   case Instruction::AShr:
5950   case Instruction::And:
5951   case Instruction::Or:
5952   case Instruction::Xor: {
5953     // Since we will replace the stride by 1 the multiplication should go away.
5954     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5955       return 0;
5956     // Certain instructions can be cheaper to vectorize if they have a constant
5957     // second vector operand. One example of this are shifts on x86.
5958     TargetTransformInfo::OperandValueKind Op1VK =
5959         TargetTransformInfo::OK_AnyValue;
5960     TargetTransformInfo::OperandValueKind Op2VK =
5961         TargetTransformInfo::OK_AnyValue;
5962     TargetTransformInfo::OperandValueProperties Op1VP =
5963         TargetTransformInfo::OP_None;
5964     TargetTransformInfo::OperandValueProperties Op2VP =
5965         TargetTransformInfo::OP_None;
5966     Value *Op2 = I->getOperand(1);
5967
5968     // Check for a splat of a constant or for a non uniform vector of constants.
5969     if (isa<ConstantInt>(Op2)) {
5970       ConstantInt *CInt = cast<ConstantInt>(Op2);
5971       if (CInt && CInt->getValue().isPowerOf2())
5972         Op2VP = TargetTransformInfo::OP_PowerOf2;
5973       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5974     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5975       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5976       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5977       if (SplatValue) {
5978         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5979         if (CInt && CInt->getValue().isPowerOf2())
5980           Op2VP = TargetTransformInfo::OP_PowerOf2;
5981         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5982       }
5983     }
5984
5985     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5986                                       Op1VP, Op2VP);
5987   }
5988   case Instruction::Select: {
5989     SelectInst *SI = cast<SelectInst>(I);
5990     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5991     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5992     Type *CondTy = SI->getCondition()->getType();
5993     if (!ScalarCond)
5994       CondTy = VectorType::get(CondTy, VF);
5995
5996     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5997   }
5998   case Instruction::ICmp:
5999   case Instruction::FCmp: {
6000     Type *ValTy = I->getOperand(0)->getType();
6001     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6002     auto It = MinBWs.find(Op0AsInstruction);
6003     if (VF > 1 && It != MinBWs.end())
6004       ValTy = IntegerType::get(ValTy->getContext(), It->second);
6005     VectorTy = ToVectorTy(ValTy, VF);
6006     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
6007   }
6008   case Instruction::Store:
6009   case Instruction::Load: {
6010     StoreInst *SI = dyn_cast<StoreInst>(I);
6011     LoadInst *LI = dyn_cast<LoadInst>(I);
6012     Type *ValTy = (SI ? SI->getValueOperand()->getType() : LI->getType());
6013     VectorTy = ToVectorTy(ValTy, VF);
6014
6015     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
6016     unsigned AS =
6017         SI ? SI->getPointerAddressSpace() : LI->getPointerAddressSpace();
6018     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
6019     // We add the cost of address computation here instead of with the gep
6020     // instruction because only here we know whether the operation is
6021     // scalarized.
6022     if (VF == 1)
6023       return TTI.getAddressComputationCost(VectorTy) +
6024              TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6025
6026     if (LI && Legal->isUniform(Ptr)) {
6027       // Scalar load + broadcast
6028       unsigned Cost = TTI.getAddressComputationCost(ValTy->getScalarType());
6029       Cost += TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
6030                                   Alignment, AS);
6031       return Cost +
6032              TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, ValTy);
6033     }
6034
6035     // For an interleaved access, calculate the total cost of the whole
6036     // interleave group.
6037     if (Legal->isAccessInterleaved(I)) {
6038       auto Group = Legal->getInterleavedAccessGroup(I);
6039       assert(Group && "Fail to get an interleaved access group.");
6040
6041       // Only calculate the cost once at the insert position.
6042       if (Group->getInsertPos() != I)
6043         return 0;
6044
6045       unsigned InterleaveFactor = Group->getFactor();
6046       Type *WideVecTy =
6047           VectorType::get(VectorTy->getVectorElementType(),
6048                           VectorTy->getVectorNumElements() * InterleaveFactor);
6049
6050       // Holds the indices of existing members in an interleaved load group.
6051       // An interleaved store group doesn't need this as it doesn't allow gaps.
6052       SmallVector<unsigned, 4> Indices;
6053       if (LI) {
6054         for (unsigned i = 0; i < InterleaveFactor; i++)
6055           if (Group->getMember(i))
6056             Indices.push_back(i);
6057       }
6058
6059       // Calculate the cost of the whole interleaved group.
6060       unsigned Cost = TTI.getInterleavedMemoryOpCost(
6061           I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
6062           Group->getAlignment(), AS);
6063
6064       if (Group->isReverse())
6065         Cost +=
6066             Group->getNumMembers() *
6067             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6068
6069       // FIXME: The interleaved load group with a huge gap could be even more
6070       // expensive than scalar operations. Then we could ignore such group and
6071       // use scalar operations instead.
6072       return Cost;
6073     }
6074
6075     // Scalarized loads/stores.
6076     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6077     bool UseGatherOrScatter =
6078         (ConsecutiveStride == 0) && isGatherOrScatterLegal(I, Ptr, Legal);
6079
6080     bool Reverse = ConsecutiveStride < 0;
6081     const DataLayout &DL = I->getModule()->getDataLayout();
6082     uint64_t ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
6083     uint64_t VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
6084     if ((!ConsecutiveStride && !UseGatherOrScatter) ||
6085         ScalarAllocatedSize != VectorElementSize) {
6086       bool IsComplexComputation =
6087           isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
6088       unsigned Cost = 0;
6089       // The cost of extracting from the value vector and pointer vector.
6090       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6091       for (unsigned i = 0; i < VF; ++i) {
6092         //  The cost of extracting the pointer operand.
6093         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
6094         // In case of STORE, the cost of ExtractElement from the vector.
6095         // In case of LOAD, the cost of InsertElement into the returned
6096         // vector.
6097         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement
6098                                           : Instruction::InsertElement,
6099                                        VectorTy, i);
6100       }
6101
6102       // The cost of the scalar loads/stores.
6103       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
6104       Cost += VF *
6105               TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
6106                                   Alignment, AS);
6107       return Cost;
6108     }
6109
6110     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
6111     if (UseGatherOrScatter) {
6112       assert(ConsecutiveStride == 0 &&
6113              "Gather/Scatter are not used for consecutive stride");
6114       return Cost +
6115              TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
6116                                         Legal->isMaskRequired(I), Alignment);
6117     }
6118     // Wide load/stores.
6119     if (Legal->isMaskRequired(I))
6120       Cost +=
6121           TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6122     else
6123       Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6124
6125     if (Reverse)
6126       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6127     return Cost;
6128   }
6129   case Instruction::ZExt:
6130   case Instruction::SExt:
6131   case Instruction::FPToUI:
6132   case Instruction::FPToSI:
6133   case Instruction::FPExt:
6134   case Instruction::PtrToInt:
6135   case Instruction::IntToPtr:
6136   case Instruction::SIToFP:
6137   case Instruction::UIToFP:
6138   case Instruction::Trunc:
6139   case Instruction::FPTrunc:
6140   case Instruction::BitCast: {
6141     // We optimize the truncation of induction variable.
6142     // The cost of these is the same as the scalar operation.
6143     if (I->getOpcode() == Instruction::Trunc &&
6144         Legal->isInductionVariable(I->getOperand(0)))
6145       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
6146                                   I->getOperand(0)->getType());
6147
6148     Type *SrcScalarTy = I->getOperand(0)->getType();
6149     Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
6150     if (VF > 1 && MinBWs.count(I)) {
6151       // This cast is going to be shrunk. This may remove the cast or it might
6152       // turn it into slightly different cast. For example, if MinBW == 16,
6153       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
6154       //
6155       // Calculate the modified src and dest types.
6156       Type *MinVecTy = VectorTy;
6157       if (I->getOpcode() == Instruction::Trunc) {
6158         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
6159         VectorTy =
6160             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6161       } else if (I->getOpcode() == Instruction::ZExt ||
6162                  I->getOpcode() == Instruction::SExt) {
6163         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
6164         VectorTy =
6165             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6166       }
6167     }
6168
6169     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
6170   }
6171   case Instruction::Call: {
6172     bool NeedToScalarize;
6173     CallInst *CI = cast<CallInst>(I);
6174     unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
6175     if (getVectorIntrinsicIDForCall(CI, TLI))
6176       return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
6177     return CallCost;
6178   }
6179   default: {
6180     // We are scalarizing the instruction. Return the cost of the scalar
6181     // instruction, plus the cost of insert and extract into vector
6182     // elements, times the vector width.
6183     unsigned Cost = 0;
6184
6185     if (!RetTy->isVoidTy() && VF != 1) {
6186       unsigned InsCost =
6187           TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy);
6188       unsigned ExtCost =
6189           TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy);
6190
6191       // The cost of inserting the results plus extracting each one of the
6192       // operands.
6193       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
6194     }
6195
6196     // The cost of executing VF copies of the scalar instruction. This opcode
6197     // is unknown. Assume that it is the same as 'mul'.
6198     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
6199     return Cost;
6200   }
6201   } // end of switch.
6202 }
6203
6204 char LoopVectorize::ID = 0;
6205 static const char lv_name[] = "Loop Vectorization";
6206 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
6207 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6208 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
6209 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6210 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
6211 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6212 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
6213 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6214 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6215 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
6216 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
6217 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6218 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
6219 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
6220 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
6221
6222 namespace llvm {
6223 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
6224   return new LoopVectorize(NoUnrolling, AlwaysVectorize);
6225 }
6226 }
6227
6228 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
6229   // Check for a store.
6230   if (auto *ST = dyn_cast<StoreInst>(Inst))
6231     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
6232
6233   // Check for a load.
6234   if (auto *LI = dyn_cast<LoadInst>(Inst))
6235     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
6236
6237   return false;
6238 }
6239
6240 void LoopVectorizationCostModel::collectValuesToIgnore() {
6241   // Ignore ephemeral values.
6242   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
6243
6244   // Ignore type-promoting instructions we identified during reduction
6245   // detection.
6246   for (auto &Reduction : *Legal->getReductionVars()) {
6247     RecurrenceDescriptor &RedDes = Reduction.second;
6248     SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6249     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
6250   }
6251
6252   // Ignore induction phis that are only used in either GetElementPtr or ICmp
6253   // instruction to exit loop. Induction variables usually have large types and
6254   // can have big impact when estimating register usage.
6255   // This is for when VF > 1.
6256   for (auto &Induction : *Legal->getInductionVars()) {
6257     auto *PN = Induction.first;
6258     auto *UpdateV = PN->getIncomingValueForBlock(TheLoop->getLoopLatch());
6259
6260     // Check that the PHI is only used by the induction increment (UpdateV) or
6261     // by GEPs. Then check that UpdateV is only used by a compare instruction,
6262     // the loop header PHI, or by GEPs.
6263     // FIXME: Need precise def-use analysis to determine if this instruction
6264     // variable will be vectorized.
6265     if (all_of(PN->users(),
6266                [&](const User *U) -> bool {
6267                  return U == UpdateV || isa<GetElementPtrInst>(U);
6268                }) &&
6269         all_of(UpdateV->users(), [&](const User *U) -> bool {
6270           return U == PN || isa<ICmpInst>(U) || isa<GetElementPtrInst>(U);
6271         })) {
6272       VecValuesToIgnore.insert(PN);
6273       VecValuesToIgnore.insert(UpdateV);
6274     }
6275   }
6276
6277   // Ignore instructions that will not be vectorized.
6278   // This is for when VF > 1.
6279   for (BasicBlock *BB : TheLoop->blocks()) {
6280     for (auto &Inst : *BB) {
6281       switch (Inst.getOpcode())
6282       case Instruction::GetElementPtr: {
6283         // Ignore GEP if its last operand is an induction variable so that it is
6284         // a consecutive load/store and won't be vectorized as scatter/gather
6285         // pattern.
6286
6287         GetElementPtrInst *Gep = cast<GetElementPtrInst>(&Inst);
6288         unsigned NumOperands = Gep->getNumOperands();
6289         unsigned InductionOperand = getGEPInductionOperand(Gep);
6290         bool GepToIgnore = true;
6291
6292         // Check that all of the gep indices are uniform except for the
6293         // induction operand.
6294         for (unsigned i = 0; i != NumOperands; ++i) {
6295           if (i != InductionOperand &&
6296               !PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)),
6297                                             TheLoop)) {
6298             GepToIgnore = false;
6299             break;
6300           }
6301         }
6302
6303         if (GepToIgnore)
6304           VecValuesToIgnore.insert(&Inst);
6305         break;
6306       }
6307     }
6308   }
6309 }
6310
6311 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
6312                                              bool IfPredicateStore) {
6313   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
6314   // Holds vector parameters or scalars, in case of uniform vals.
6315   SmallVector<VectorParts, 4> Params;
6316
6317   setDebugLocFromInst(Builder, Instr);
6318
6319   // Find all of the vectorized parameters.
6320   for (Value *SrcOp : Instr->operands()) {
6321     // If we are accessing the old induction variable, use the new one.
6322     if (SrcOp == OldInduction) {
6323       Params.push_back(getVectorValue(SrcOp));
6324       continue;
6325     }
6326
6327     // Try using previously calculated values.
6328     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
6329
6330     // If the src is an instruction that appeared earlier in the basic block
6331     // then it should already be vectorized.
6332     if (SrcInst && OrigLoop->contains(SrcInst)) {
6333       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
6334       // The parameter is a vector value from earlier.
6335       Params.push_back(WidenMap.get(SrcInst));
6336     } else {
6337       // The parameter is a scalar from outside the loop. Maybe even a constant.
6338       VectorParts Scalars;
6339       Scalars.append(UF, SrcOp);
6340       Params.push_back(Scalars);
6341     }
6342   }
6343
6344   assert(Params.size() == Instr->getNumOperands() &&
6345          "Invalid number of operands");
6346
6347   // Does this instruction return a value ?
6348   bool IsVoidRetTy = Instr->getType()->isVoidTy();
6349
6350   Value *UndefVec = IsVoidRetTy ? nullptr : UndefValue::get(Instr->getType());
6351   // Create a new entry in the WidenMap and initialize it to Undef or Null.
6352   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
6353
6354   VectorParts Cond;
6355   if (IfPredicateStore) {
6356     assert(Instr->getParent()->getSinglePredecessor() &&
6357            "Only support single predecessor blocks");
6358     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
6359                           Instr->getParent());
6360   }
6361
6362   // For each vector unroll 'part':
6363   for (unsigned Part = 0; Part < UF; ++Part) {
6364     // For each scalar that we create:
6365
6366     // Start an "if (pred) a[i] = ..." block.
6367     Value *Cmp = nullptr;
6368     if (IfPredicateStore) {
6369       if (Cond[Part]->getType()->isVectorTy())
6370         Cond[Part] =
6371             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
6372       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
6373                                ConstantInt::get(Cond[Part]->getType(), 1));
6374     }
6375
6376     Instruction *Cloned = Instr->clone();
6377     if (!IsVoidRetTy)
6378       Cloned->setName(Instr->getName() + ".cloned");
6379     // Replace the operands of the cloned instructions with extracted scalars.
6380     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6381       Value *Op = Params[op][Part];
6382       Cloned->setOperand(op, Op);
6383     }
6384
6385     // Place the cloned scalar in the new loop.
6386     Builder.Insert(Cloned);
6387
6388     // If we just cloned a new assumption, add it the assumption cache.
6389     if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
6390       if (II->getIntrinsicID() == Intrinsic::assume)
6391         AC->registerAssumption(II);
6392
6393     // If the original scalar returns a value we need to place it in a vector
6394     // so that future users will be able to use it.
6395     if (!IsVoidRetTy)
6396       VecResults[Part] = Cloned;
6397
6398     // End if-block.
6399     if (IfPredicateStore)
6400       PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned), Cmp));
6401   }
6402 }
6403
6404 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
6405   auto *SI = dyn_cast<StoreInst>(Instr);
6406   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
6407
6408   return scalarizeInstruction(Instr, IfPredicateStore);
6409 }
6410
6411 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
6412
6413 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
6414
6415 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
6416   // When unrolling and the VF is 1, we only need to add a simple scalar.
6417   Type *ITy = Val->getType();
6418   assert(!ITy->isVectorTy() && "Val must be a scalar");
6419   Constant *C = ConstantInt::get(ITy, StartIdx);
6420   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
6421 }
6422
6423 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
6424   SmallVector<Metadata *, 4> MDs;
6425   // Reserve first location for self reference to the LoopID metadata node.
6426   MDs.push_back(nullptr);
6427   bool IsUnrollMetadata = false;
6428   MDNode *LoopID = L->getLoopID();
6429   if (LoopID) {
6430     // First find existing loop unrolling disable metadata.
6431     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
6432       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
6433       if (MD) {
6434         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
6435         IsUnrollMetadata =
6436             S && S->getString().startswith("llvm.loop.unroll.disable");
6437       }
6438       MDs.push_back(LoopID->getOperand(i));
6439     }
6440   }
6441
6442   if (!IsUnrollMetadata) {
6443     // Add runtime unroll disable metadata.
6444     LLVMContext &Context = L->getHeader()->getContext();
6445     SmallVector<Metadata *, 1> DisableOperands;
6446     DisableOperands.push_back(
6447         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
6448     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
6449     MDs.push_back(DisableNode);
6450     MDNode *NewLoopID = MDNode::get(Context, MDs);
6451     // Set operand 0 to refer to the loop id itself.
6452     NewLoopID->replaceOperandWith(0, NewLoopID);
6453     L->setLoopID(NewLoopID);
6454   }
6455 }
6456
6457 bool LoopVectorizePass::processLoop(Loop *L) {
6458   assert(L->empty() && "Only process inner loops.");
6459
6460 #ifndef NDEBUG
6461   const std::string DebugLocStr = getDebugLocString(L);
6462 #endif /* NDEBUG */
6463
6464   DEBUG(dbgs() << "\nLV: Checking a loop in \""
6465                << L->getHeader()->getParent()->getName() << "\" from "
6466                << DebugLocStr << "\n");
6467
6468   LoopVectorizeHints Hints(L, DisableUnrolling);
6469
6470   DEBUG(dbgs() << "LV: Loop hints:"
6471                << " force="
6472                << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
6473                        ? "disabled"
6474                        : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
6475                               ? "enabled"
6476                               : "?"))
6477                << " width=" << Hints.getWidth()
6478                << " unroll=" << Hints.getInterleave() << "\n");
6479
6480   // Function containing loop
6481   Function *F = L->getHeader()->getParent();
6482
6483   // Looking at the diagnostic output is the only way to determine if a loop
6484   // was vectorized (other than looking at the IR or machine code), so it
6485   // is important to generate an optimization remark for each loop. Most of
6486   // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
6487   // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
6488   // less verbose reporting vectorized loops and unvectorized loops that may
6489   // benefit from vectorization, respectively.
6490
6491   if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
6492     DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
6493     return false;
6494   }
6495
6496   // Check the loop for a trip count threshold:
6497   // do not vectorize loops with a tiny trip count.
6498   const unsigned TC = SE->getSmallConstantTripCount(L);
6499   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
6500     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
6501                  << "This loop is not worth vectorizing.");
6502     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
6503       DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
6504     else {
6505       DEBUG(dbgs() << "\n");
6506       emitAnalysisDiag(F, L, Hints, VectorizationReport()
6507                                         << "vectorization is not beneficial "
6508                                            "and is not explicitly forced");
6509       return false;
6510     }
6511   }
6512
6513   PredicatedScalarEvolution PSE(*SE, *L);
6514
6515   // Check if it is legal to vectorize the loop.
6516   LoopVectorizationRequirements Requirements;
6517   LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI,
6518                                 &Requirements, &Hints);
6519   if (!LVL.canVectorize()) {
6520     DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
6521     emitMissedWarning(F, L, Hints);
6522     return false;
6523   }
6524
6525   // Use the cost model.
6526   LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, F,
6527                                 &Hints);
6528   CM.collectValuesToIgnore();
6529
6530   // Check the function attributes to find out if this function should be
6531   // optimized for size.
6532   bool OptForSize =
6533       Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
6534
6535   // Compute the weighted frequency of this loop being executed and see if it
6536   // is less than 20% of the function entry baseline frequency. Note that we
6537   // always have a canonical loop here because we think we *can* vectorize.
6538   // FIXME: This is hidden behind a flag due to pervasive problems with
6539   // exactly what block frequency models.
6540   if (LoopVectorizeWithBlockFrequency) {
6541     BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
6542     if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
6543         LoopEntryFreq < ColdEntryFreq)
6544       OptForSize = true;
6545   }
6546
6547   // Check the function attributes to see if implicit floats are allowed.
6548   // FIXME: This check doesn't seem possibly correct -- what if the loop is
6549   // an integer loop and the vector instructions selected are purely integer
6550   // vector instructions?
6551   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
6552     DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
6553                     "attribute is used.\n");
6554     emitAnalysisDiag(
6555         F, L, Hints,
6556         VectorizationReport()
6557             << "loop not vectorized due to NoImplicitFloat attribute");
6558     emitMissedWarning(F, L, Hints);
6559     return false;
6560   }
6561
6562   // Check if the target supports potentially unsafe FP vectorization.
6563   // FIXME: Add a check for the type of safety issue (denormal, signaling)
6564   // for the target we're vectorizing for, to make sure none of the
6565   // additional fp-math flags can help.
6566   if (Hints.isPotentiallyUnsafe() &&
6567       TTI->isFPVectorizationPotentiallyUnsafe()) {
6568     DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
6569     emitAnalysisDiag(F, L, Hints,
6570                      VectorizationReport()
6571                          << "loop not vectorized due to unsafe FP support.");
6572     emitMissedWarning(F, L, Hints);
6573     return false;
6574   }
6575
6576   // Select the optimal vectorization factor.
6577   const LoopVectorizationCostModel::VectorizationFactor VF =
6578       CM.selectVectorizationFactor(OptForSize);
6579
6580   // Select the interleave count.
6581   unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
6582
6583   // Get user interleave count.
6584   unsigned UserIC = Hints.getInterleave();
6585
6586   // Identify the diagnostic messages that should be produced.
6587   std::string VecDiagMsg, IntDiagMsg;
6588   bool VectorizeLoop = true, InterleaveLoop = true;
6589
6590   if (Requirements.doesNotMeet(F, L, Hints)) {
6591     DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
6592                     "requirements.\n");
6593     emitMissedWarning(F, L, Hints);
6594     return false;
6595   }
6596
6597   if (VF.Width == 1) {
6598     DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
6599     VecDiagMsg =
6600         "the cost-model indicates that vectorization is not beneficial";
6601     VectorizeLoop = false;
6602   }
6603
6604   if (IC == 1 && UserIC <= 1) {
6605     // Tell the user interleaving is not beneficial.
6606     DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
6607     IntDiagMsg =
6608         "the cost-model indicates that interleaving is not beneficial";
6609     InterleaveLoop = false;
6610     if (UserIC == 1)
6611       IntDiagMsg +=
6612           " and is explicitly disabled or interleave count is set to 1";
6613   } else if (IC > 1 && UserIC == 1) {
6614     // Tell the user interleaving is beneficial, but it explicitly disabled.
6615     DEBUG(dbgs()
6616           << "LV: Interleaving is beneficial but is explicitly disabled.");
6617     IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
6618                  "but is explicitly disabled or interleave count is set to 1";
6619     InterleaveLoop = false;
6620   }
6621
6622   // Override IC if user provided an interleave count.
6623   IC = UserIC > 0 ? UserIC : IC;
6624
6625   // Emit diagnostic messages, if any.
6626   const char *VAPassName = Hints.vectorizeAnalysisPassName();
6627   if (!VectorizeLoop && !InterleaveLoop) {
6628     // Do not vectorize or interleaving the loop.
6629     emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
6630                                    L->getStartLoc(), VecDiagMsg);
6631     emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
6632                                    L->getStartLoc(), IntDiagMsg);
6633     return false;
6634   } else if (!VectorizeLoop && InterleaveLoop) {
6635     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
6636     emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
6637                                    L->getStartLoc(), VecDiagMsg);
6638   } else if (VectorizeLoop && !InterleaveLoop) {
6639     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
6640                  << DebugLocStr << '\n');
6641     emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
6642                                    L->getStartLoc(), IntDiagMsg);
6643   } else if (VectorizeLoop && InterleaveLoop) {
6644     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
6645                  << DebugLocStr << '\n');
6646     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
6647   }
6648
6649   if (!VectorizeLoop) {
6650     assert(IC > 1 && "interleave count should not be 1 or 0");
6651     // If we decided that it is not legal to vectorize the loop, then
6652     // interleave it.
6653     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, IC);
6654     Unroller.vectorize(&LVL, CM.MinBWs, CM.VecValuesToIgnore);
6655
6656     emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
6657                            Twine("interleaved loop (interleaved count: ") +
6658                                Twine(IC) + ")");
6659   } else {
6660     // If we decided that it is *legal* to vectorize the loop, then do it.
6661     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, VF.Width, IC);
6662     LB.vectorize(&LVL, CM.MinBWs, CM.VecValuesToIgnore);
6663     ++LoopsVectorized;
6664
6665     // Add metadata to disable runtime unrolling a scalar loop when there are
6666     // no runtime checks about strides and memory. A scalar loop that is
6667     // rarely used is not worth unrolling.
6668     if (!LB.areSafetyChecksAdded())
6669       AddRuntimeUnrollDisableMetaData(L);
6670
6671     // Report the vectorization decision.
6672     emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
6673                            Twine("vectorized loop (vectorization width: ") +
6674                                Twine(VF.Width) + ", interleaved count: " +
6675                                Twine(IC) + ")");
6676   }
6677
6678   // Mark the loop as already vectorized to avoid vectorizing again.
6679   Hints.setAlreadyVectorized();
6680
6681   DEBUG(verifyFunction(*L->getHeader()->getParent()));
6682   return true;
6683 }
6684
6685 bool LoopVectorizePass::runImpl(
6686     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
6687     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
6688     DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
6689     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_) {
6690
6691   SE = &SE_;
6692   LI = &LI_;
6693   TTI = &TTI_;
6694   DT = &DT_;
6695   BFI = &BFI_;
6696   TLI = TLI_;
6697   AA = &AA_;
6698   AC = &AC_;
6699   GetLAA = &GetLAA_;
6700   DB = &DB_;
6701
6702   // Compute some weights outside of the loop over the loops. Compute this
6703   // using a BranchProbability to re-use its scaling math.
6704   const BranchProbability ColdProb(1, 5); // 20%
6705   ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
6706
6707   // Don't attempt if
6708   // 1. the target claims to have no vector registers, and
6709   // 2. interleaving won't help ILP.
6710   //
6711   // The second condition is necessary because, even if the target has no
6712   // vector registers, loop vectorization may still enable scalar
6713   // interleaving.
6714   if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
6715     return false;
6716
6717   // Build up a worklist of inner-loops to vectorize. This is necessary as
6718   // the act of vectorizing or partially unrolling a loop creates new loops
6719   // and can invalidate iterators across the loops.
6720   SmallVector<Loop *, 8> Worklist;
6721
6722   for (Loop *L : *LI)
6723     addAcyclicInnerLoop(*L, Worklist);
6724
6725   LoopsAnalyzed += Worklist.size();
6726
6727   // Now walk the identified inner loops.
6728   bool Changed = false;
6729   while (!Worklist.empty())
6730     Changed |= processLoop(Worklist.pop_back_val());
6731
6732   // Process each loop nest in the function.
6733   return Changed;
6734
6735 }
6736
6737
6738 PreservedAnalyses LoopVectorizePass::run(Function &F,
6739                                          FunctionAnalysisManager &AM) {
6740     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
6741     auto &LI = AM.getResult<LoopAnalysis>(F);
6742     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
6743     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
6744     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
6745     auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
6746     auto &AA = AM.getResult<AAManager>(F);
6747     auto &AC = AM.getResult<AssumptionAnalysis>(F);
6748     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
6749
6750     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
6751     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
6752         [&](Loop &L) -> const LoopAccessInfo & {
6753       return LAM.getResult<LoopAccessAnalysis>(L);
6754     };
6755     bool Changed = runImpl(F, SE, LI, TTI, DT, BFI, TLI, DB, AA, AC, GetLAA);
6756     if (!Changed)
6757       return PreservedAnalyses::all();
6758     PreservedAnalyses PA;
6759     PA.preserve<LoopAnalysis>();
6760     PA.preserve<DominatorTreeAnalysis>();
6761     PA.preserve<BasicAA>();
6762     PA.preserve<GlobalsAA>();
6763     return PA;
6764 }