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