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