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