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