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