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