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