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