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