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