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