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