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