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