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