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