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