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