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