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