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