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