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