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