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.
4288   auto &PreviousParts = getVectorValue(Previous);
4289 
4290   // Set the insertion point after the previous value if it is an instruction.
4291   // Note that the previous value may have been constant-folded so it is not
4292   // guaranteed to be an instruction in the vector loop.
4293   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousParts[UF - 1]))
4294     Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4295   else
4296     Builder.SetInsertPoint(
4297         &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1])));
4298 
4299   // We will construct a vector for the recurrence by combining the values for
4300   // the current and previous iterations. This is the required shuffle mask.
4301   SmallVector<Constant *, 8> ShuffleMask(VF);
4302   ShuffleMask[0] = Builder.getInt32(VF - 1);
4303   for (unsigned I = 1; I < VF; ++I)
4304     ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4305 
4306   // The vector from which to take the initial value for the current iteration
4307   // (actual or unrolled). Initially, this is the vector phi node.
4308   Value *Incoming = VecPhi;
4309 
4310   // Shuffle the current and previous vector and update the vector parts.
4311   for (unsigned Part = 0; Part < UF; ++Part) {
4312     auto *Shuffle =
4313         VF > 1
4314             ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part],
4315                                           ConstantVector::get(ShuffleMask))
4316             : Incoming;
4317     PhiParts[Part]->replaceAllUsesWith(Shuffle);
4318     cast<Instruction>(PhiParts[Part])->eraseFromParent();
4319     PhiParts[Part] = Shuffle;
4320     Incoming = PreviousParts[Part];
4321   }
4322 
4323   // Fix the latch value of the new recurrence in the vector loop.
4324   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4325 
4326   // Extract the last vector element in the middle block. This will be the
4327   // initial value for the recurrence when jumping to the scalar loop.
4328   auto *Extract = Incoming;
4329   if (VF > 1) {
4330     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4331     Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1),
4332                                            "vector.recur.extract");
4333   }
4334 
4335   // Fix the initial value of the original recurrence in the scalar loop.
4336   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4337   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4338   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4339     auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit;
4340     Start->addIncoming(Incoming, BB);
4341   }
4342 
4343   Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4344   Phi->setName("scalar.recur");
4345 
4346   // Finally, fix users of the recurrence outside the loop. The users will need
4347   // either the last value of the scalar recurrence or the last value of the
4348   // vector recurrence we extracted in the middle block. Since the loop is in
4349   // LCSSA form, we just need to find the phi node for the original scalar
4350   // recurrence in the exit block, and then add an edge for the middle block.
4351   for (auto &I : *LoopExitBlock) {
4352     auto *LCSSAPhi = dyn_cast<PHINode>(&I);
4353     if (!LCSSAPhi)
4354       break;
4355     if (LCSSAPhi->getIncomingValue(0) == Phi) {
4356       LCSSAPhi->addIncoming(Extract, LoopMiddleBlock);
4357       break;
4358     }
4359   }
4360 }
4361 
4362 void InnerLoopVectorizer::fixLCSSAPHIs() {
4363   for (Instruction &LEI : *LoopExitBlock) {
4364     auto *LCSSAPhi = dyn_cast<PHINode>(&LEI);
4365     if (!LCSSAPhi)
4366       break;
4367     if (LCSSAPhi->getNumIncomingValues() == 1)
4368       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
4369                             LoopMiddleBlock);
4370   }
4371 }
4372 
4373 void InnerLoopVectorizer::collectTriviallyDeadInstructions() {
4374   BasicBlock *Latch = OrigLoop->getLoopLatch();
4375 
4376   // We create new control-flow for the vectorized loop, so the original
4377   // condition will be dead after vectorization if it's only used by the
4378   // branch.
4379   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4380   if (Cmp && Cmp->hasOneUse())
4381     DeadInstructions.insert(Cmp);
4382 
4383   // We create new "steps" for induction variable updates to which the original
4384   // induction variables map. An original update instruction will be dead if
4385   // all its users except the induction variable are dead.
4386   for (auto &Induction : *Legal->getInductionVars()) {
4387     PHINode *Ind = Induction.first;
4388     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4389     if (all_of(IndUpdate->users(), [&](User *U) -> bool {
4390           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
4391         }))
4392       DeadInstructions.insert(IndUpdate);
4393   }
4394 }
4395 
4396 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4397 
4398   // The basic block and loop containing the predicated instruction.
4399   auto *PredBB = PredInst->getParent();
4400   auto *VectorLoop = LI->getLoopFor(PredBB);
4401 
4402   // Initialize a worklist with the operands of the predicated instruction.
4403   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4404 
4405   // Holds instructions that we need to analyze again. An instruction may be
4406   // reanalyzed if we don't yet know if we can sink it or not.
4407   SmallVector<Instruction *, 8> InstsToReanalyze;
4408 
4409   // Returns true if a given use occurs in the predicated block. Phi nodes use
4410   // their operands in their corresponding predecessor blocks.
4411   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4412     auto *I = cast<Instruction>(U.getUser());
4413     BasicBlock *BB = I->getParent();
4414     if (auto *Phi = dyn_cast<PHINode>(I))
4415       BB = Phi->getIncomingBlock(
4416           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4417     return BB == PredBB;
4418   };
4419 
4420   // Iteratively sink the scalarized operands of the predicated instruction
4421   // into the block we created for it. When an instruction is sunk, it's
4422   // operands are then added to the worklist. The algorithm ends after one pass
4423   // through the worklist doesn't sink a single instruction.
4424   bool Changed;
4425   do {
4426 
4427     // Add the instructions that need to be reanalyzed to the worklist, and
4428     // reset the changed indicator.
4429     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4430     InstsToReanalyze.clear();
4431     Changed = false;
4432 
4433     while (!Worklist.empty()) {
4434       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4435 
4436       // We can't sink an instruction if it is a phi node, is already in the
4437       // predicated block, is not in the loop, or may have side effects.
4438       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4439           !VectorLoop->contains(I) || I->mayHaveSideEffects())
4440         continue;
4441 
4442       // It's legal to sink the instruction if all its uses occur in the
4443       // predicated block. Otherwise, there's nothing to do yet, and we may
4444       // need to reanalyze the instruction.
4445       if (!all_of(I->uses(), isBlockOfUsePredicated)) {
4446         InstsToReanalyze.push_back(I);
4447         continue;
4448       }
4449 
4450       // Move the instruction to the beginning of the predicated block, and add
4451       // it's operands to the worklist.
4452       I->moveBefore(&*PredBB->getFirstInsertionPt());
4453       Worklist.insert(I->op_begin(), I->op_end());
4454 
4455       // The sinking may have enabled other instructions to be sunk, so we will
4456       // need to iterate.
4457       Changed = true;
4458     }
4459   } while (Changed);
4460 }
4461 
4462 void InnerLoopVectorizer::predicateInstructions() {
4463 
4464   // For each instruction I marked for predication on value C, split I into its
4465   // own basic block to form an if-then construct over C. Since I may be fed by
4466   // an extractelement instruction or other scalar operand, we try to
4467   // iteratively sink its scalar operands into the predicated block. If I feeds
4468   // an insertelement instruction, we try to move this instruction into the
4469   // predicated block as well. For non-void types, a phi node will be created
4470   // for the resulting value (either vector or scalar).
4471   //
4472   // So for some predicated instruction, e.g. the conditional sdiv in:
4473   //
4474   // for.body:
4475   //  ...
4476   //  %add = add nsw i32 %mul, %0
4477   //  %cmp5 = icmp sgt i32 %2, 7
4478   //  br i1 %cmp5, label %if.then, label %if.end
4479   //
4480   // if.then:
4481   //  %div = sdiv i32 %0, %1
4482   //  br label %if.end
4483   //
4484   // if.end:
4485   //  %x.0 = phi i32 [ %div, %if.then ], [ %add, %for.body ]
4486   //
4487   // the sdiv at this point is scalarized and if-converted using a select.
4488   // The inactive elements in the vector are not used, but the predicated
4489   // instruction is still executed for all vector elements, essentially:
4490   //
4491   // vector.body:
4492   //  ...
4493   //  %17 = add nsw <2 x i32> %16, %wide.load
4494   //  %29 = extractelement <2 x i32> %wide.load, i32 0
4495   //  %30 = extractelement <2 x i32> %wide.load51, i32 0
4496   //  %31 = sdiv i32 %29, %30
4497   //  %32 = insertelement <2 x i32> undef, i32 %31, i32 0
4498   //  %35 = extractelement <2 x i32> %wide.load, i32 1
4499   //  %36 = extractelement <2 x i32> %wide.load51, i32 1
4500   //  %37 = sdiv i32 %35, %36
4501   //  %38 = insertelement <2 x i32> %32, i32 %37, i32 1
4502   //  %predphi = select <2 x i1> %26, <2 x i32> %38, <2 x i32> %17
4503   //
4504   // Predication will now re-introduce the original control flow to avoid false
4505   // side-effects by the sdiv instructions on the inactive elements, yielding
4506   // (after cleanup):
4507   //
4508   // vector.body:
4509   //  ...
4510   //  %5 = add nsw <2 x i32> %4, %wide.load
4511   //  %8 = icmp sgt <2 x i32> %wide.load52, <i32 7, i32 7>
4512   //  %9 = extractelement <2 x i1> %8, i32 0
4513   //  br i1 %9, label %pred.sdiv.if, label %pred.sdiv.continue
4514   //
4515   // pred.sdiv.if:
4516   //  %10 = extractelement <2 x i32> %wide.load, i32 0
4517   //  %11 = extractelement <2 x i32> %wide.load51, i32 0
4518   //  %12 = sdiv i32 %10, %11
4519   //  %13 = insertelement <2 x i32> undef, i32 %12, i32 0
4520   //  br label %pred.sdiv.continue
4521   //
4522   // pred.sdiv.continue:
4523   //  %14 = phi <2 x i32> [ undef, %vector.body ], [ %13, %pred.sdiv.if ]
4524   //  %15 = extractelement <2 x i1> %8, i32 1
4525   //  br i1 %15, label %pred.sdiv.if54, label %pred.sdiv.continue55
4526   //
4527   // pred.sdiv.if54:
4528   //  %16 = extractelement <2 x i32> %wide.load, i32 1
4529   //  %17 = extractelement <2 x i32> %wide.load51, i32 1
4530   //  %18 = sdiv i32 %16, %17
4531   //  %19 = insertelement <2 x i32> %14, i32 %18, i32 1
4532   //  br label %pred.sdiv.continue55
4533   //
4534   // pred.sdiv.continue55:
4535   //  %20 = phi <2 x i32> [ %14, %pred.sdiv.continue ], [ %19, %pred.sdiv.if54 ]
4536   //  %predphi = select <2 x i1> %8, <2 x i32> %20, <2 x i32> %5
4537 
4538   for (auto KV : PredicatedInstructions) {
4539     BasicBlock::iterator I(KV.first);
4540     BasicBlock *Head = I->getParent();
4541     auto *BB = SplitBlock(Head, &*std::next(I), DT, LI);
4542     auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
4543                                         /*BranchWeights=*/nullptr, DT, LI);
4544     I->moveBefore(T);
4545     sinkScalarOperands(&*I);
4546 
4547     I->getParent()->setName(Twine("pred.") + I->getOpcodeName() + ".if");
4548     BB->setName(Twine("pred.") + I->getOpcodeName() + ".continue");
4549 
4550     // If the instruction is non-void create a Phi node at reconvergence point.
4551     if (!I->getType()->isVoidTy()) {
4552       Value *IncomingTrue = nullptr;
4553       Value *IncomingFalse = nullptr;
4554 
4555       if (I->hasOneUse() && isa<InsertElementInst>(*I->user_begin())) {
4556         // If the predicated instruction is feeding an insert-element, move it
4557         // into the Then block; Phi node will be created for the vector.
4558         InsertElementInst *IEI = cast<InsertElementInst>(*I->user_begin());
4559         IEI->moveBefore(T);
4560         IncomingTrue = IEI; // the new vector with the inserted element.
4561         IncomingFalse = IEI->getOperand(0); // the unmodified vector
4562       } else {
4563         // Phi node will be created for the scalar predicated instruction.
4564         IncomingTrue = &*I;
4565         IncomingFalse = UndefValue::get(I->getType());
4566       }
4567 
4568       BasicBlock *PostDom = I->getParent()->getSingleSuccessor();
4569       assert(PostDom && "Then block has multiple successors");
4570       PHINode *Phi =
4571           PHINode::Create(IncomingTrue->getType(), 2, "", &PostDom->front());
4572       IncomingTrue->replaceAllUsesWith(Phi);
4573       Phi->addIncoming(IncomingFalse, Head);
4574       Phi->addIncoming(IncomingTrue, I->getParent());
4575     }
4576   }
4577 
4578   DEBUG(DT->verifyDomTree());
4579 }
4580 
4581 InnerLoopVectorizer::VectorParts
4582 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
4583   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
4584 
4585   // Look for cached value.
4586   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
4587   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
4588   if (ECEntryIt != MaskCache.end())
4589     return ECEntryIt->second;
4590 
4591   VectorParts SrcMask = createBlockInMask(Src);
4592 
4593   // The terminator has to be a branch inst!
4594   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
4595   assert(BI && "Unexpected terminator found");
4596 
4597   if (BI->isConditional()) {
4598     VectorParts EdgeMask = getVectorValue(BI->getCondition());
4599 
4600     if (BI->getSuccessor(0) != Dst)
4601       for (unsigned part = 0; part < UF; ++part)
4602         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
4603 
4604     for (unsigned part = 0; part < UF; ++part)
4605       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
4606 
4607     MaskCache[Edge] = EdgeMask;
4608     return EdgeMask;
4609   }
4610 
4611   MaskCache[Edge] = SrcMask;
4612   return SrcMask;
4613 }
4614 
4615 InnerLoopVectorizer::VectorParts
4616 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
4617   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
4618 
4619   // Loop incoming mask is all-one.
4620   if (OrigLoop->getHeader() == BB) {
4621     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
4622     return getVectorValue(C);
4623   }
4624 
4625   // This is the block mask. We OR all incoming edges, and with zero.
4626   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
4627   VectorParts BlockMask = getVectorValue(Zero);
4628 
4629   // For each pred:
4630   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
4631     VectorParts EM = createEdgeMask(*it, BB);
4632     for (unsigned part = 0; part < UF; ++part)
4633       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
4634   }
4635 
4636   return BlockMask;
4637 }
4638 
4639 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
4640                                               unsigned VF, PhiVector *PV) {
4641   PHINode *P = cast<PHINode>(PN);
4642   // Handle recurrences.
4643   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4644     VectorParts Entry(UF);
4645     for (unsigned part = 0; part < UF; ++part) {
4646       // This is phase one of vectorizing PHIs.
4647       Type *VecTy =
4648           (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4649       Entry[part] = PHINode::Create(
4650           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4651     }
4652     VectorLoopValueMap.initVector(P, Entry);
4653     PV->push_back(P);
4654     return;
4655   }
4656 
4657   setDebugLocFromInst(Builder, P);
4658   // Check for PHI nodes that are lowered to vector selects.
4659   if (P->getParent() != OrigLoop->getHeader()) {
4660     // We know that all PHIs in non-header blocks are converted into
4661     // selects, so we don't have to worry about the insertion order and we
4662     // can just use the builder.
4663     // At this point we generate the predication tree. There may be
4664     // duplications since this is a simple recursive scan, but future
4665     // optimizations will clean it up.
4666 
4667     unsigned NumIncoming = P->getNumIncomingValues();
4668 
4669     // Generate a sequence of selects of the form:
4670     // SELECT(Mask3, In3,
4671     //      SELECT(Mask2, In2,
4672     //                   ( ...)))
4673     VectorParts Entry(UF);
4674     for (unsigned In = 0; In < NumIncoming; In++) {
4675       VectorParts Cond =
4676           createEdgeMask(P->getIncomingBlock(In), P->getParent());
4677       const VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
4678 
4679       for (unsigned part = 0; part < UF; ++part) {
4680         // We might have single edge PHIs (blocks) - use an identity
4681         // 'select' for the first PHI operand.
4682         if (In == 0)
4683           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]);
4684         else
4685           // Select between the current value and the previous incoming edge
4686           // based on the incoming mask.
4687           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part],
4688                                              "predphi");
4689       }
4690     }
4691     VectorLoopValueMap.initVector(P, Entry);
4692     return;
4693   }
4694 
4695   // This PHINode must be an induction variable.
4696   // Make sure that we know about it.
4697   assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
4698 
4699   InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4700   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4701 
4702   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4703   // which can be found from the original scalar operations.
4704   switch (II.getKind()) {
4705   case InductionDescriptor::IK_NoInduction:
4706     llvm_unreachable("Unknown induction");
4707   case InductionDescriptor::IK_IntInduction:
4708   case InductionDescriptor::IK_FpInduction:
4709     return widenIntOrFpInduction(P);
4710   case InductionDescriptor::IK_PtrInduction: {
4711     // Handle the pointer induction variable case.
4712     assert(P->getType()->isPointerTy() && "Unexpected type.");
4713     // This is the normalized GEP that starts counting at zero.
4714     Value *PtrInd = Induction;
4715     PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4716     // Determine the number of scalars we need to generate for each unroll
4717     // iteration. If the instruction is uniform, we only need to generate the
4718     // first lane. Otherwise, we generate all VF values.
4719     unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4720     // These are the scalar results. Notice that we don't generate vector GEPs
4721     // because scalar GEPs result in better code.
4722     ScalarParts Entry(UF);
4723     for (unsigned Part = 0; Part < UF; ++Part) {
4724       Entry[Part].resize(VF);
4725       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4726         Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
4727         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4728         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4729         SclrGep->setName("next.gep");
4730         Entry[Part][Lane] = SclrGep;
4731       }
4732     }
4733     VectorLoopValueMap.initScalar(P, Entry);
4734     return;
4735   }
4736   }
4737 }
4738 
4739 /// A helper function for checking whether an integer division-related
4740 /// instruction may divide by zero (in which case it must be predicated if
4741 /// executed conditionally in the scalar code).
4742 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4743 /// Non-zero divisors that are non compile-time constants will not be
4744 /// converted into multiplication, so we will still end up scalarizing
4745 /// the division, but can do so w/o predication.
4746 static bool mayDivideByZero(Instruction &I) {
4747   assert((I.getOpcode() == Instruction::UDiv ||
4748           I.getOpcode() == Instruction::SDiv ||
4749           I.getOpcode() == Instruction::URem ||
4750           I.getOpcode() == Instruction::SRem) &&
4751          "Unexpected instruction");
4752   Value *Divisor = I.getOperand(1);
4753   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4754   return !CInt || CInt->isZero();
4755 }
4756 
4757 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
4758   // For each instruction in the old loop.
4759   for (Instruction &I : *BB) {
4760 
4761     // If the instruction will become trivially dead when vectorized, we don't
4762     // need to generate it.
4763     if (DeadInstructions.count(&I))
4764       continue;
4765 
4766     // Scalarize instructions that should remain scalar after vectorization.
4767     if (VF > 1 &&
4768         !(isa<BranchInst>(&I) || isa<PHINode>(&I) ||
4769           isa<DbgInfoIntrinsic>(&I)) &&
4770         shouldScalarizeInstruction(&I)) {
4771       scalarizeInstruction(&I, Legal->isScalarWithPredication(&I));
4772       continue;
4773     }
4774 
4775     switch (I.getOpcode()) {
4776     case Instruction::Br:
4777       // Nothing to do for PHIs and BR, since we already took care of the
4778       // loop control flow instructions.
4779       continue;
4780     case Instruction::PHI: {
4781       // Vectorize PHINodes.
4782       widenPHIInstruction(&I, UF, VF, PV);
4783       continue;
4784     } // End of PHI.
4785 
4786     case Instruction::UDiv:
4787     case Instruction::SDiv:
4788     case Instruction::SRem:
4789     case Instruction::URem:
4790       // Scalarize with predication if this instruction may divide by zero and
4791       // block execution is conditional, otherwise fallthrough.
4792       if (Legal->isScalarWithPredication(&I)) {
4793         scalarizeInstruction(&I, true);
4794         continue;
4795       }
4796     case Instruction::Add:
4797     case Instruction::FAdd:
4798     case Instruction::Sub:
4799     case Instruction::FSub:
4800     case Instruction::Mul:
4801     case Instruction::FMul:
4802     case Instruction::FDiv:
4803     case Instruction::FRem:
4804     case Instruction::Shl:
4805     case Instruction::LShr:
4806     case Instruction::AShr:
4807     case Instruction::And:
4808     case Instruction::Or:
4809     case Instruction::Xor: {
4810       // Just widen binops.
4811       auto *BinOp = cast<BinaryOperator>(&I);
4812       setDebugLocFromInst(Builder, BinOp);
4813       const VectorParts &A = getVectorValue(BinOp->getOperand(0));
4814       const VectorParts &B = getVectorValue(BinOp->getOperand(1));
4815 
4816       // Use this vector value for all users of the original instruction.
4817       VectorParts Entry(UF);
4818       for (unsigned Part = 0; Part < UF; ++Part) {
4819         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
4820 
4821         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4822           VecOp->copyIRFlags(BinOp);
4823 
4824         Entry[Part] = V;
4825       }
4826 
4827       VectorLoopValueMap.initVector(&I, Entry);
4828       addMetadata(Entry, BinOp);
4829       break;
4830     }
4831     case Instruction::Select: {
4832       // Widen selects.
4833       // If the selector is loop invariant we can create a select
4834       // instruction with a scalar condition. Otherwise, use vector-select.
4835       auto *SE = PSE.getSE();
4836       bool InvariantCond =
4837           SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4838       setDebugLocFromInst(Builder, &I);
4839 
4840       // The condition can be loop invariant  but still defined inside the
4841       // loop. This means that we can't just use the original 'cond' value.
4842       // We have to take the 'vectorized' value and pick the first lane.
4843       // Instcombine will make this a no-op.
4844       const VectorParts &Cond = getVectorValue(I.getOperand(0));
4845       const VectorParts &Op0 = getVectorValue(I.getOperand(1));
4846       const VectorParts &Op1 = getVectorValue(I.getOperand(2));
4847 
4848       auto *ScalarCond = getScalarValue(I.getOperand(0), 0, 0);
4849 
4850       VectorParts Entry(UF);
4851       for (unsigned Part = 0; Part < UF; ++Part) {
4852         Entry[Part] = Builder.CreateSelect(
4853             InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]);
4854       }
4855 
4856       VectorLoopValueMap.initVector(&I, Entry);
4857       addMetadata(Entry, &I);
4858       break;
4859     }
4860 
4861     case Instruction::ICmp:
4862     case Instruction::FCmp: {
4863       // Widen compares. Generate vector compares.
4864       bool FCmp = (I.getOpcode() == Instruction::FCmp);
4865       auto *Cmp = dyn_cast<CmpInst>(&I);
4866       setDebugLocFromInst(Builder, Cmp);
4867       const VectorParts &A = getVectorValue(Cmp->getOperand(0));
4868       const VectorParts &B = getVectorValue(Cmp->getOperand(1));
4869       VectorParts Entry(UF);
4870       for (unsigned Part = 0; Part < UF; ++Part) {
4871         Value *C = nullptr;
4872         if (FCmp) {
4873           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
4874           cast<FCmpInst>(C)->copyFastMathFlags(Cmp);
4875         } else {
4876           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
4877         }
4878         Entry[Part] = C;
4879       }
4880 
4881       VectorLoopValueMap.initVector(&I, Entry);
4882       addMetadata(Entry, &I);
4883       break;
4884     }
4885 
4886     case Instruction::Store:
4887     case Instruction::Load:
4888       vectorizeMemoryInstruction(&I);
4889       break;
4890     case Instruction::ZExt:
4891     case Instruction::SExt:
4892     case Instruction::FPToUI:
4893     case Instruction::FPToSI:
4894     case Instruction::FPExt:
4895     case Instruction::PtrToInt:
4896     case Instruction::IntToPtr:
4897     case Instruction::SIToFP:
4898     case Instruction::UIToFP:
4899     case Instruction::Trunc:
4900     case Instruction::FPTrunc:
4901     case Instruction::BitCast: {
4902       auto *CI = dyn_cast<CastInst>(&I);
4903       setDebugLocFromInst(Builder, CI);
4904 
4905       // Optimize the special case where the source is a constant integer
4906       // induction variable. Notice that we can only optimize the 'trunc' case
4907       // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
4908       // (c) other casts depend on pointer size.
4909       if (Cost->isOptimizableIVTruncate(CI, VF)) {
4910         widenIntOrFpInduction(cast<PHINode>(CI->getOperand(0)),
4911                               cast<TruncInst>(CI));
4912         break;
4913       }
4914 
4915       /// Vectorize casts.
4916       Type *DestTy =
4917           (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4918 
4919       const VectorParts &A = getVectorValue(CI->getOperand(0));
4920       VectorParts Entry(UF);
4921       for (unsigned Part = 0; Part < UF; ++Part)
4922         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
4923       VectorLoopValueMap.initVector(&I, Entry);
4924       addMetadata(Entry, &I);
4925       break;
4926     }
4927 
4928     case Instruction::Call: {
4929       // Ignore dbg intrinsics.
4930       if (isa<DbgInfoIntrinsic>(I))
4931         break;
4932       setDebugLocFromInst(Builder, &I);
4933 
4934       Module *M = BB->getParent()->getParent();
4935       auto *CI = cast<CallInst>(&I);
4936 
4937       StringRef FnName = CI->getCalledFunction()->getName();
4938       Function *F = CI->getCalledFunction();
4939       Type *RetTy = ToVectorTy(CI->getType(), VF);
4940       SmallVector<Type *, 4> Tys;
4941       for (Value *ArgOperand : CI->arg_operands())
4942         Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4943 
4944       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4945       if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
4946                  ID == Intrinsic::lifetime_start)) {
4947         scalarizeInstruction(&I);
4948         break;
4949       }
4950       // The flag shows whether we use Intrinsic or a usual Call for vectorized
4951       // version of the instruction.
4952       // Is it beneficial to perform intrinsic call compared to lib call?
4953       bool NeedToScalarize;
4954       unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4955       bool UseVectorIntrinsic =
4956           ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4957       if (!UseVectorIntrinsic && NeedToScalarize) {
4958         scalarizeInstruction(&I);
4959         break;
4960       }
4961 
4962       VectorParts Entry(UF);
4963       for (unsigned Part = 0; Part < UF; ++Part) {
4964         SmallVector<Value *, 4> Args;
4965         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4966           Value *Arg = CI->getArgOperand(i);
4967           // Some intrinsics have a scalar argument - don't replace it with a
4968           // vector.
4969           if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
4970             const VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
4971             Arg = VectorArg[Part];
4972           }
4973           Args.push_back(Arg);
4974         }
4975 
4976         Function *VectorF;
4977         if (UseVectorIntrinsic) {
4978           // Use vector version of the intrinsic.
4979           Type *TysForDecl[] = {CI->getType()};
4980           if (VF > 1)
4981             TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4982           VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4983         } else {
4984           // Use vector version of the library call.
4985           StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4986           assert(!VFnName.empty() && "Vector function name is empty.");
4987           VectorF = M->getFunction(VFnName);
4988           if (!VectorF) {
4989             // Generate a declaration
4990             FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4991             VectorF =
4992                 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4993             VectorF->copyAttributesFrom(F);
4994           }
4995         }
4996         assert(VectorF && "Can't create vector function.");
4997 
4998         SmallVector<OperandBundleDef, 1> OpBundles;
4999         CI->getOperandBundlesAsDefs(OpBundles);
5000         CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5001 
5002         if (isa<FPMathOperator>(V))
5003           V->copyFastMathFlags(CI);
5004 
5005         Entry[Part] = V;
5006       }
5007 
5008       VectorLoopValueMap.initVector(&I, Entry);
5009       addMetadata(Entry, &I);
5010       break;
5011     }
5012 
5013     default:
5014       // All other instructions are unsupported. Scalarize them.
5015       scalarizeInstruction(&I);
5016       break;
5017     } // end of switch.
5018   }   // end of for_each instr.
5019 }
5020 
5021 void InnerLoopVectorizer::updateAnalysis() {
5022   // Forget the original basic block.
5023   PSE.getSE()->forgetLoop(OrigLoop);
5024 
5025   // Update the dominator tree information.
5026   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
5027          "Entry does not dominate exit.");
5028 
5029   // We don't predicate stores by this point, so the vector body should be a
5030   // single loop.
5031   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
5032 
5033   DT->addNewBlock(LoopMiddleBlock, LoopVectorBody);
5034   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
5035   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
5036   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
5037 
5038   DEBUG(DT->verifyDomTree());
5039 }
5040 
5041 /// \brief Check whether it is safe to if-convert this phi node.
5042 ///
5043 /// Phi nodes with constant expressions that can trap are not safe to if
5044 /// convert.
5045 static bool canIfConvertPHINodes(BasicBlock *BB) {
5046   for (Instruction &I : *BB) {
5047     auto *Phi = dyn_cast<PHINode>(&I);
5048     if (!Phi)
5049       return true;
5050     for (Value *V : Phi->incoming_values())
5051       if (auto *C = dyn_cast<Constant>(V))
5052         if (C->canTrap())
5053           return false;
5054   }
5055   return true;
5056 }
5057 
5058 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
5059   if (!EnableIfConversion) {
5060     ORE->emit(createMissedAnalysis("IfConversionDisabled")
5061               << "if-conversion is disabled");
5062     return false;
5063   }
5064 
5065   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
5066 
5067   // A list of pointers that we can safely read and write to.
5068   SmallPtrSet<Value *, 8> SafePointes;
5069 
5070   // Collect safe addresses.
5071   for (BasicBlock *BB : TheLoop->blocks()) {
5072     if (blockNeedsPredication(BB))
5073       continue;
5074 
5075     for (Instruction &I : *BB)
5076       if (auto *Ptr = getPointerOperand(&I))
5077         SafePointes.insert(Ptr);
5078   }
5079 
5080   // Collect the blocks that need predication.
5081   BasicBlock *Header = TheLoop->getHeader();
5082   for (BasicBlock *BB : TheLoop->blocks()) {
5083     // We don't support switch statements inside loops.
5084     if (!isa<BranchInst>(BB->getTerminator())) {
5085       ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
5086                 << "loop contains a switch statement");
5087       return false;
5088     }
5089 
5090     // We must be able to predicate all blocks that need to be predicated.
5091     if (blockNeedsPredication(BB)) {
5092       if (!blockCanBePredicated(BB, SafePointes)) {
5093         ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
5094                   << "control flow cannot be substituted for a select");
5095         return false;
5096       }
5097     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
5098       ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
5099                 << "control flow cannot be substituted for a select");
5100       return false;
5101     }
5102   }
5103 
5104   // We can if-convert this loop.
5105   return true;
5106 }
5107 
5108 bool LoopVectorizationLegality::canVectorize() {
5109   // We must have a loop in canonical form. Loops with indirectbr in them cannot
5110   // be canonicalized.
5111   if (!TheLoop->getLoopPreheader()) {
5112     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5113               << "loop control flow is not understood by vectorizer");
5114     return false;
5115   }
5116 
5117   // FIXME: The code is currently dead, since the loop gets sent to
5118   // LoopVectorizationLegality is already an innermost loop.
5119   //
5120   // We can only vectorize innermost loops.
5121   if (!TheLoop->empty()) {
5122     ORE->emit(createMissedAnalysis("NotInnermostLoop")
5123               << "loop is not the innermost loop");
5124     return false;
5125   }
5126 
5127   // We must have a single backedge.
5128   if (TheLoop->getNumBackEdges() != 1) {
5129     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5130               << "loop control flow is not understood by vectorizer");
5131     return false;
5132   }
5133 
5134   // We must have a single exiting block.
5135   if (!TheLoop->getExitingBlock()) {
5136     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5137               << "loop control flow is not understood by vectorizer");
5138     return false;
5139   }
5140 
5141   // We only handle bottom-tested loops, i.e. loop in which the condition is
5142   // checked at the end of each iteration. With that we can assume that all
5143   // instructions in the loop are executed the same number of times.
5144   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5145     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5146               << "loop control flow is not understood by vectorizer");
5147     return false;
5148   }
5149 
5150   // We need to have a loop header.
5151   DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
5152                << '\n');
5153 
5154   // Check if we can if-convert non-single-bb loops.
5155   unsigned NumBlocks = TheLoop->getNumBlocks();
5156   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
5157     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
5158     return false;
5159   }
5160 
5161   // ScalarEvolution needs to be able to find the exit count.
5162   const SCEV *ExitCount = PSE.getBackedgeTakenCount();
5163   if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
5164     ORE->emit(createMissedAnalysis("CantComputeNumberOfIterations")
5165               << "could not determine number of loop iterations");
5166     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
5167     return false;
5168   }
5169 
5170   // Check if we can vectorize the instructions and CFG in this loop.
5171   if (!canVectorizeInstrs()) {
5172     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
5173     return false;
5174   }
5175 
5176   // Go over each instruction and look at memory deps.
5177   if (!canVectorizeMemory()) {
5178     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
5179     return false;
5180   }
5181 
5182   DEBUG(dbgs() << "LV: We can vectorize this loop"
5183                << (LAI->getRuntimePointerChecking()->Need
5184                        ? " (with a runtime bound check)"
5185                        : "")
5186                << "!\n");
5187 
5188   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
5189 
5190   // If an override option has been passed in for interleaved accesses, use it.
5191   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
5192     UseInterleaved = EnableInterleavedMemAccesses;
5193 
5194   // Analyze interleaved memory accesses.
5195   if (UseInterleaved)
5196     InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
5197 
5198   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
5199   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
5200     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
5201 
5202   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
5203     ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
5204               << "Too many SCEV assumptions need to be made and checked "
5205               << "at runtime");
5206     DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
5207     return false;
5208   }
5209 
5210   // Okay! We can vectorize. At this point we don't have any other mem analysis
5211   // which may limit our maximum vectorization factor, so just return true with
5212   // no restrictions.
5213   return true;
5214 }
5215 
5216 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
5217   if (Ty->isPointerTy())
5218     return DL.getIntPtrType(Ty);
5219 
5220   // It is possible that char's or short's overflow when we ask for the loop's
5221   // trip count, work around this by changing the type size.
5222   if (Ty->getScalarSizeInBits() < 32)
5223     return Type::getInt32Ty(Ty->getContext());
5224 
5225   return Ty;
5226 }
5227 
5228 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
5229   Ty0 = convertPointerToIntegerType(DL, Ty0);
5230   Ty1 = convertPointerToIntegerType(DL, Ty1);
5231   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
5232     return Ty0;
5233   return Ty1;
5234 }
5235 
5236 /// \brief Check that the instruction has outside loop users and is not an
5237 /// identified reduction variable.
5238 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
5239                                SmallPtrSetImpl<Value *> &AllowedExit) {
5240   // Reduction and Induction instructions are allowed to have exit users. All
5241   // other instructions must not have external users.
5242   if (!AllowedExit.count(Inst))
5243     // Check that all of the users of the loop are inside the BB.
5244     for (User *U : Inst->users()) {
5245       Instruction *UI = cast<Instruction>(U);
5246       // This user may be a reduction exit value.
5247       if (!TheLoop->contains(UI)) {
5248         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
5249         return true;
5250       }
5251     }
5252   return false;
5253 }
5254 
5255 void LoopVectorizationLegality::addInductionPhi(
5256     PHINode *Phi, const InductionDescriptor &ID,
5257     SmallPtrSetImpl<Value *> &AllowedExit) {
5258   Inductions[Phi] = ID;
5259   Type *PhiTy = Phi->getType();
5260   const DataLayout &DL = Phi->getModule()->getDataLayout();
5261 
5262   // Get the widest type.
5263   if (!PhiTy->isFloatingPointTy()) {
5264     if (!WidestIndTy)
5265       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
5266     else
5267       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
5268   }
5269 
5270   // Int inductions are special because we only allow one IV.
5271   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
5272       ID.getConstIntStepValue() &&
5273       ID.getConstIntStepValue()->isOne() &&
5274       isa<Constant>(ID.getStartValue()) &&
5275       cast<Constant>(ID.getStartValue())->isNullValue()) {
5276 
5277     // Use the phi node with the widest type as induction. Use the last
5278     // one if there are multiple (no good reason for doing this other
5279     // than it is expedient). We've checked that it begins at zero and
5280     // steps by one, so this is a canonical induction variable.
5281     if (!PrimaryInduction || PhiTy == WidestIndTy)
5282       PrimaryInduction = Phi;
5283   }
5284 
5285   // Both the PHI node itself, and the "post-increment" value feeding
5286   // back into the PHI node may have external users.
5287   AllowedExit.insert(Phi);
5288   AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
5289 
5290   DEBUG(dbgs() << "LV: Found an induction variable.\n");
5291   return;
5292 }
5293 
5294 bool LoopVectorizationLegality::canVectorizeInstrs() {
5295   BasicBlock *Header = TheLoop->getHeader();
5296 
5297   // Look for the attribute signaling the absence of NaNs.
5298   Function &F = *Header->getParent();
5299   HasFunNoNaNAttr =
5300       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
5301 
5302   // For each block in the loop.
5303   for (BasicBlock *BB : TheLoop->blocks()) {
5304     // Scan the instructions in the block and look for hazards.
5305     for (Instruction &I : *BB) {
5306       if (auto *Phi = dyn_cast<PHINode>(&I)) {
5307         Type *PhiTy = Phi->getType();
5308         // Check that this PHI type is allowed.
5309         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
5310             !PhiTy->isPointerTy()) {
5311           ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5312                     << "loop control flow is not understood by vectorizer");
5313           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
5314           return false;
5315         }
5316 
5317         // If this PHINode is not in the header block, then we know that we
5318         // can convert it to select during if-conversion. No need to check if
5319         // the PHIs in this block are induction or reduction variables.
5320         if (BB != Header) {
5321           // Check that this instruction has no outside users or is an
5322           // identified reduction value with an outside user.
5323           if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
5324             continue;
5325           ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi)
5326                     << "value could not be identified as "
5327                        "an induction or reduction variable");
5328           return false;
5329         }
5330 
5331         // We only allow if-converted PHIs with exactly two incoming values.
5332         if (Phi->getNumIncomingValues() != 2) {
5333           ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5334                     << "control flow not understood by vectorizer");
5335           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
5336           return false;
5337         }
5338 
5339         RecurrenceDescriptor RedDes;
5340         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
5341           if (RedDes.hasUnsafeAlgebra())
5342             Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
5343           AllowedExit.insert(RedDes.getLoopExitInstr());
5344           Reductions[Phi] = RedDes;
5345           continue;
5346         }
5347 
5348         InductionDescriptor ID;
5349         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
5350           addInductionPhi(Phi, ID, AllowedExit);
5351           if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
5352             Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
5353           continue;
5354         }
5355 
5356         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) {
5357           FirstOrderRecurrences.insert(Phi);
5358           continue;
5359         }
5360 
5361         // As a last resort, coerce the PHI to a AddRec expression
5362         // and re-try classifying it a an induction PHI.
5363         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
5364           addInductionPhi(Phi, ID, AllowedExit);
5365           continue;
5366         }
5367 
5368         ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
5369                   << "value that could not be identified as "
5370                      "reduction is used outside the loop");
5371         DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
5372         return false;
5373       } // end of PHI handling
5374 
5375       // We handle calls that:
5376       //   * Are debug info intrinsics.
5377       //   * Have a mapping to an IR intrinsic.
5378       //   * Have a vector version available.
5379       auto *CI = dyn_cast<CallInst>(&I);
5380       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
5381           !isa<DbgInfoIntrinsic>(CI) &&
5382           !(CI->getCalledFunction() && TLI &&
5383             TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5384         ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
5385                   << "call instruction cannot be vectorized");
5386         DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
5387         return false;
5388       }
5389 
5390       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
5391       // second argument is the same (i.e. loop invariant)
5392       if (CI && hasVectorInstrinsicScalarOpd(
5393                     getVectorIntrinsicIDForCall(CI, TLI), 1)) {
5394         auto *SE = PSE.getSE();
5395         if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
5396           ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
5397                     << "intrinsic instruction cannot be vectorized");
5398           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
5399           return false;
5400         }
5401       }
5402 
5403       // Check that the instruction return type is vectorizable.
5404       // Also, we can't vectorize extractelement instructions.
5405       if ((!VectorType::isValidElementType(I.getType()) &&
5406            !I.getType()->isVoidTy()) ||
5407           isa<ExtractElementInst>(I)) {
5408         ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
5409                   << "instruction return type cannot be vectorized");
5410         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
5411         return false;
5412       }
5413 
5414       // Check that the stored type is vectorizable.
5415       if (auto *ST = dyn_cast<StoreInst>(&I)) {
5416         Type *T = ST->getValueOperand()->getType();
5417         if (!VectorType::isValidElementType(T)) {
5418           ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
5419                     << "store instruction cannot be vectorized");
5420           return false;
5421         }
5422 
5423         // FP instructions can allow unsafe algebra, thus vectorizable by
5424         // non-IEEE-754 compliant SIMD units.
5425         // This applies to floating-point math operations and calls, not memory
5426         // operations, shuffles, or casts, as they don't change precision or
5427         // semantics.
5428       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
5429                  !I.hasUnsafeAlgebra()) {
5430         DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
5431         Hints->setPotentiallyUnsafe();
5432       }
5433 
5434       // Reduction instructions are allowed to have exit users.
5435       // All other instructions must not have external users.
5436       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
5437         ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
5438                   << "value cannot be used outside the loop");
5439         return false;
5440       }
5441 
5442     } // next instr.
5443   }
5444 
5445   if (!PrimaryInduction) {
5446     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
5447     if (Inductions.empty()) {
5448       ORE->emit(createMissedAnalysis("NoInductionVariable")
5449                 << "loop induction variable could not be identified");
5450       return false;
5451     }
5452   }
5453 
5454   // Now we know the widest induction type, check if our found induction
5455   // is the same size. If it's not, unset it here and InnerLoopVectorizer
5456   // will create another.
5457   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5458     PrimaryInduction = nullptr;
5459 
5460   return true;
5461 }
5462 
5463 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
5464 
5465   // We should not collect Scalars more than once per VF. Right now,
5466   // this function is called from collectUniformsAndScalars(), which
5467   // already does this check. Collecting Scalars for VF=1 does not make any
5468   // sense.
5469 
5470   assert(VF >= 2 && !Scalars.count(VF) &&
5471          "This function should not be visited twice for the same VF");
5472 
5473   // If an instruction is uniform after vectorization, it will remain scalar.
5474   Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
5475 
5476   // Collect the getelementptr instructions that will not be vectorized. A
5477   // getelementptr instruction is only vectorized if it is used for a legal
5478   // gather or scatter operation.
5479   for (auto *BB : TheLoop->blocks())
5480     for (auto &I : *BB) {
5481       if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
5482         Scalars[VF].insert(GEP);
5483         continue;
5484       }
5485       auto *Ptr = getPointerOperand(&I);
5486       if (!Ptr)
5487         continue;
5488       auto *GEP = getGEPInstruction(Ptr);
5489       if (GEP && getWideningDecision(&I, VF) == CM_GatherScatter)
5490         Scalars[VF].erase(GEP);
5491     }
5492 
5493   // An induction variable will remain scalar if all users of the induction
5494   // variable and induction variable update remain scalar.
5495   auto *Latch = TheLoop->getLoopLatch();
5496   for (auto &Induction : *Legal->getInductionVars()) {
5497     auto *Ind = Induction.first;
5498     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5499 
5500     // Determine if all users of the induction variable are scalar after
5501     // vectorization.
5502     auto ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
5503       auto *I = cast<Instruction>(U);
5504       return I == IndUpdate || !TheLoop->contains(I) || Scalars[VF].count(I);
5505     });
5506     if (!ScalarInd)
5507       continue;
5508 
5509     // Determine if all users of the induction variable update instruction are
5510     // scalar after vectorization.
5511     auto ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5512       auto *I = cast<Instruction>(U);
5513       return I == Ind || !TheLoop->contains(I) || Scalars[VF].count(I);
5514     });
5515     if (!ScalarIndUpdate)
5516       continue;
5517 
5518     // The induction variable and its update instruction will remain scalar.
5519     Scalars[VF].insert(Ind);
5520     Scalars[VF].insert(IndUpdate);
5521   }
5522 }
5523 
5524 bool LoopVectorizationLegality::isScalarWithPredication(Instruction *I) {
5525   if (!blockNeedsPredication(I->getParent()))
5526     return false;
5527   switch(I->getOpcode()) {
5528   default:
5529     break;
5530   case Instruction::Store:
5531     return !isMaskRequired(I);
5532   case Instruction::UDiv:
5533   case Instruction::SDiv:
5534   case Instruction::SRem:
5535   case Instruction::URem:
5536     return mayDivideByZero(*I);
5537   }
5538   return false;
5539 }
5540 
5541 bool LoopVectorizationLegality::memoryInstructionCanBeWidened(Instruction *I,
5542                                                               unsigned VF) {
5543   // Get and ensure we have a valid memory instruction.
5544   LoadInst *LI = dyn_cast<LoadInst>(I);
5545   StoreInst *SI = dyn_cast<StoreInst>(I);
5546   assert((LI || SI) && "Invalid memory instruction");
5547 
5548   auto *Ptr = getPointerOperand(I);
5549 
5550   // In order to be widened, the pointer should be consecutive, first of all.
5551   if (!isConsecutivePtr(Ptr))
5552     return false;
5553 
5554   // If the instruction is a store located in a predicated block, it will be
5555   // scalarized.
5556   if (isScalarWithPredication(I))
5557     return false;
5558 
5559   // If the instruction's allocated size doesn't equal it's type size, it
5560   // requires padding and will be scalarized.
5561   auto &DL = I->getModule()->getDataLayout();
5562   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5563   if (hasIrregularType(ScalarTy, DL, VF))
5564     return false;
5565 
5566   return true;
5567 }
5568 
5569 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
5570 
5571   // We should not collect Uniforms more than once per VF. Right now,
5572   // this function is called from collectUniformsAndScalars(), which
5573   // already does this check. Collecting Uniforms for VF=1 does not make any
5574   // sense.
5575 
5576   assert(VF >= 2 && !Uniforms.count(VF) &&
5577          "This function should not be visited twice for the same VF");
5578 
5579   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5580   // not analyze again.  Uniforms.count(VF) will return 1.
5581   Uniforms[VF].clear();
5582 
5583   // We now know that the loop is vectorizable!
5584   // Collect instructions inside the loop that will remain uniform after
5585   // vectorization.
5586 
5587   // Global values, params and instructions outside of current loop are out of
5588   // scope.
5589   auto isOutOfScope = [&](Value *V) -> bool {
5590     Instruction *I = dyn_cast<Instruction>(V);
5591     return (!I || !TheLoop->contains(I));
5592   };
5593 
5594   SetVector<Instruction *> Worklist;
5595   BasicBlock *Latch = TheLoop->getLoopLatch();
5596 
5597   // Start with the conditional branch. If the branch condition is an
5598   // instruction contained in the loop that is only used by the branch, it is
5599   // uniform.
5600   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5601   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
5602     Worklist.insert(Cmp);
5603     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
5604   }
5605 
5606   // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5607   // are pointers that are treated like consecutive pointers during
5608   // vectorization. The pointer operands of interleaved accesses are an
5609   // example.
5610   SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5611 
5612   // Holds pointer operands of instructions that are possibly non-uniform.
5613   SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5614 
5615   auto isUniformDecision = [&](Instruction *I, unsigned VF) {
5616     InstWidening WideningDecision = getWideningDecision(I, VF);
5617     assert(WideningDecision != CM_Unknown &&
5618            "Widening decision should be ready at this moment");
5619 
5620     return (WideningDecision == CM_Widen ||
5621             WideningDecision == CM_Interleave);
5622   };
5623   // Iterate over the instructions in the loop, and collect all
5624   // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5625   // that a consecutive-like pointer operand will be scalarized, we collect it
5626   // in PossibleNonUniformPtrs instead. We use two sets here because a single
5627   // getelementptr instruction can be used by both vectorized and scalarized
5628   // memory instructions. For example, if a loop loads and stores from the same
5629   // location, but the store is conditional, the store will be scalarized, and
5630   // the getelementptr won't remain uniform.
5631   for (auto *BB : TheLoop->blocks())
5632     for (auto &I : *BB) {
5633 
5634       // If there's no pointer operand, there's nothing to do.
5635       auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I));
5636       if (!Ptr)
5637         continue;
5638 
5639       // True if all users of Ptr are memory accesses that have Ptr as their
5640       // pointer operand.
5641       auto UsersAreMemAccesses = all_of(Ptr->users(), [&](User *U) -> bool {
5642         return getPointerOperand(U) == Ptr;
5643       });
5644 
5645       // Ensure the memory instruction will not be scalarized or used by
5646       // gather/scatter, making its pointer operand non-uniform. If the pointer
5647       // operand is used by any instruction other than a memory access, we
5648       // conservatively assume the pointer operand may be non-uniform.
5649       if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5650         PossibleNonUniformPtrs.insert(Ptr);
5651 
5652       // If the memory instruction will be vectorized and its pointer operand
5653       // is consecutive-like, or interleaving - the pointer operand should
5654       // remain uniform.
5655       else
5656         ConsecutiveLikePtrs.insert(Ptr);
5657     }
5658 
5659   // Add to the Worklist all consecutive and consecutive-like pointers that
5660   // aren't also identified as possibly non-uniform.
5661   for (auto *V : ConsecutiveLikePtrs)
5662     if (!PossibleNonUniformPtrs.count(V)) {
5663       DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
5664       Worklist.insert(V);
5665     }
5666 
5667   // Expand Worklist in topological order: whenever a new instruction
5668   // is added , its users should be either already inside Worklist, or
5669   // out of scope. It ensures a uniform instruction will only be used
5670   // by uniform instructions or out of scope instructions.
5671   unsigned idx = 0;
5672   while (idx != Worklist.size()) {
5673     Instruction *I = Worklist[idx++];
5674 
5675     for (auto OV : I->operand_values()) {
5676       if (isOutOfScope(OV))
5677         continue;
5678       auto *OI = cast<Instruction>(OV);
5679       if (all_of(OI->users(), [&](User *U) -> bool {
5680             auto *J = cast<Instruction>(U);
5681             return !TheLoop->contains(J) || Worklist.count(J) ||
5682                    (OI == getPointerOperand(J) && isUniformDecision(J, VF));
5683           })) {
5684         Worklist.insert(OI);
5685         DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
5686       }
5687     }
5688   }
5689 
5690   // Returns true if Ptr is the pointer operand of a memory access instruction
5691   // I, and I is known to not require scalarization.
5692   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5693     return getPointerOperand(I) == Ptr && isUniformDecision(I, VF);
5694   };
5695 
5696   // For an instruction to be added into Worklist above, all its users inside
5697   // the loop should also be in Worklist. However, this condition cannot be
5698   // true for phi nodes that form a cyclic dependence. We must process phi
5699   // nodes separately. An induction variable will remain uniform if all users
5700   // of the induction variable and induction variable update remain uniform.
5701   // The code below handles both pointer and non-pointer induction variables.
5702   for (auto &Induction : *Legal->getInductionVars()) {
5703     auto *Ind = Induction.first;
5704     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5705 
5706     // Determine if all users of the induction variable are uniform after
5707     // vectorization.
5708     auto UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
5709       auto *I = cast<Instruction>(U);
5710       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5711              isVectorizedMemAccessUse(I, Ind);
5712     });
5713     if (!UniformInd)
5714       continue;
5715 
5716     // Determine if all users of the induction variable update instruction are
5717     // uniform after vectorization.
5718     auto UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5719       auto *I = cast<Instruction>(U);
5720       return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5721              isVectorizedMemAccessUse(I, IndUpdate);
5722     });
5723     if (!UniformIndUpdate)
5724       continue;
5725 
5726     // The induction variable and its update instruction will remain uniform.
5727     Worklist.insert(Ind);
5728     Worklist.insert(IndUpdate);
5729     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
5730     DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n");
5731   }
5732 
5733   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5734 }
5735 
5736 bool LoopVectorizationLegality::canVectorizeMemory() {
5737   LAI = &(*GetLAA)(*TheLoop);
5738   InterleaveInfo.setLAI(LAI);
5739   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
5740   if (LAR) {
5741     OptimizationRemarkAnalysis VR(Hints->vectorizeAnalysisPassName(),
5742                                   "loop not vectorized: ", *LAR);
5743     ORE->emit(VR);
5744   }
5745   if (!LAI->canVectorizeMemory())
5746     return false;
5747 
5748   if (LAI->hasStoreToLoopInvariantAddress()) {
5749     ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
5750               << "write to a loop invariant address could not be vectorized");
5751     DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
5752     return false;
5753   }
5754 
5755   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5756   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
5757 
5758   return true;
5759 }
5760 
5761 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5762   Value *In0 = const_cast<Value *>(V);
5763   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5764   if (!PN)
5765     return false;
5766 
5767   return Inductions.count(PN);
5768 }
5769 
5770 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
5771   return FirstOrderRecurrences.count(Phi);
5772 }
5773 
5774 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5775   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
5776 }
5777 
5778 bool LoopVectorizationLegality::blockCanBePredicated(
5779     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
5780   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
5781 
5782   for (Instruction &I : *BB) {
5783     // Check that we don't have a constant expression that can trap as operand.
5784     for (Value *Operand : I.operands()) {
5785       if (auto *C = dyn_cast<Constant>(Operand))
5786         if (C->canTrap())
5787           return false;
5788     }
5789     // We might be able to hoist the load.
5790     if (I.mayReadFromMemory()) {
5791       auto *LI = dyn_cast<LoadInst>(&I);
5792       if (!LI)
5793         return false;
5794       if (!SafePtrs.count(LI->getPointerOperand())) {
5795         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
5796             isLegalMaskedGather(LI->getType())) {
5797           MaskedOp.insert(LI);
5798           continue;
5799         }
5800         // !llvm.mem.parallel_loop_access implies if-conversion safety.
5801         if (IsAnnotatedParallel)
5802           continue;
5803         return false;
5804       }
5805     }
5806 
5807     if (I.mayWriteToMemory()) {
5808       auto *SI = dyn_cast<StoreInst>(&I);
5809       // We only support predication of stores in basic blocks with one
5810       // predecessor.
5811       if (!SI)
5812         return false;
5813 
5814       // Build a masked store if it is legal for the target.
5815       if (isLegalMaskedStore(SI->getValueOperand()->getType(),
5816                              SI->getPointerOperand()) ||
5817           isLegalMaskedScatter(SI->getValueOperand()->getType())) {
5818         MaskedOp.insert(SI);
5819         continue;
5820       }
5821 
5822       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
5823       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
5824 
5825       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
5826           !isSinglePredecessor)
5827         return false;
5828     }
5829     if (I.mayThrow())
5830       return false;
5831   }
5832 
5833   return true;
5834 }
5835 
5836 void InterleavedAccessInfo::collectConstStrideAccesses(
5837     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
5838     const ValueToValueMap &Strides) {
5839 
5840   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5841 
5842   // Since it's desired that the load/store instructions be maintained in
5843   // "program order" for the interleaved access analysis, we have to visit the
5844   // blocks in the loop in reverse postorder (i.e., in a topological order).
5845   // Such an ordering will ensure that any load/store that may be executed
5846   // before a second load/store will precede the second load/store in
5847   // AccessStrideInfo.
5848   LoopBlocksDFS DFS(TheLoop);
5849   DFS.perform(LI);
5850   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
5851     for (auto &I : *BB) {
5852       auto *LI = dyn_cast<LoadInst>(&I);
5853       auto *SI = dyn_cast<StoreInst>(&I);
5854       if (!LI && !SI)
5855         continue;
5856 
5857       Value *Ptr = getPointerOperand(&I);
5858       // We don't check wrapping here because we don't know yet if Ptr will be
5859       // part of a full group or a group with gaps. Checking wrapping for all
5860       // pointers (even those that end up in groups with no gaps) will be overly
5861       // conservative. For full groups, wrapping should be ok since if we would
5862       // wrap around the address space we would do a memory access at nullptr
5863       // even without the transformation. The wrapping checks are therefore
5864       // deferred until after we've formed the interleaved groups.
5865       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
5866                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
5867 
5868       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
5869       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
5870       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
5871 
5872       // An alignment of 0 means target ABI alignment.
5873       unsigned Align = getMemInstAlignment(&I);
5874       if (!Align)
5875         Align = DL.getABITypeAlignment(PtrTy->getElementType());
5876 
5877       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
5878     }
5879 }
5880 
5881 // Analyze interleaved accesses and collect them into interleaved load and
5882 // store groups.
5883 //
5884 // When generating code for an interleaved load group, we effectively hoist all
5885 // loads in the group to the location of the first load in program order. When
5886 // generating code for an interleaved store group, we sink all stores to the
5887 // location of the last store. This code motion can change the order of load
5888 // and store instructions and may break dependences.
5889 //
5890 // The code generation strategy mentioned above ensures that we won't violate
5891 // any write-after-read (WAR) dependences.
5892 //
5893 // E.g., for the WAR dependence:  a = A[i];      // (1)
5894 //                                A[i] = b;      // (2)
5895 //
5896 // The store group of (2) is always inserted at or below (2), and the load
5897 // group of (1) is always inserted at or above (1). Thus, the instructions will
5898 // never be reordered. All other dependences are checked to ensure the
5899 // correctness of the instruction reordering.
5900 //
5901 // The algorithm visits all memory accesses in the loop in bottom-up program
5902 // order. Program order is established by traversing the blocks in the loop in
5903 // reverse postorder when collecting the accesses.
5904 //
5905 // We visit the memory accesses in bottom-up order because it can simplify the
5906 // construction of store groups in the presence of write-after-write (WAW)
5907 // dependences.
5908 //
5909 // E.g., for the WAW dependence:  A[i] = a;      // (1)
5910 //                                A[i] = b;      // (2)
5911 //                                A[i + 1] = c;  // (3)
5912 //
5913 // We will first create a store group with (3) and (2). (1) can't be added to
5914 // this group because it and (2) are dependent. However, (1) can be grouped
5915 // with other accesses that may precede it in program order. Note that a
5916 // bottom-up order does not imply that WAW dependences should not be checked.
5917 void InterleavedAccessInfo::analyzeInterleaving(
5918     const ValueToValueMap &Strides) {
5919   DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
5920 
5921   // Holds all accesses with a constant stride.
5922   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
5923   collectConstStrideAccesses(AccessStrideInfo, Strides);
5924 
5925   if (AccessStrideInfo.empty())
5926     return;
5927 
5928   // Collect the dependences in the loop.
5929   collectDependences();
5930 
5931   // Holds all interleaved store groups temporarily.
5932   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
5933   // Holds all interleaved load groups temporarily.
5934   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
5935 
5936   // Search in bottom-up program order for pairs of accesses (A and B) that can
5937   // form interleaved load or store groups. In the algorithm below, access A
5938   // precedes access B in program order. We initialize a group for B in the
5939   // outer loop of the algorithm, and then in the inner loop, we attempt to
5940   // insert each A into B's group if:
5941   //
5942   //  1. A and B have the same stride,
5943   //  2. A and B have the same memory object size, and
5944   //  3. A belongs in B's group according to its distance from B.
5945   //
5946   // Special care is taken to ensure group formation will not break any
5947   // dependences.
5948   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
5949        BI != E; ++BI) {
5950     Instruction *B = BI->first;
5951     StrideDescriptor DesB = BI->second;
5952 
5953     // Initialize a group for B if it has an allowable stride. Even if we don't
5954     // create a group for B, we continue with the bottom-up algorithm to ensure
5955     // we don't break any of B's dependences.
5956     InterleaveGroup *Group = nullptr;
5957     if (isStrided(DesB.Stride)) {
5958       Group = getInterleaveGroup(B);
5959       if (!Group) {
5960         DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n');
5961         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
5962       }
5963       if (B->mayWriteToMemory())
5964         StoreGroups.insert(Group);
5965       else
5966         LoadGroups.insert(Group);
5967     }
5968 
5969     for (auto AI = std::next(BI); AI != E; ++AI) {
5970       Instruction *A = AI->first;
5971       StrideDescriptor DesA = AI->second;
5972 
5973       // Our code motion strategy implies that we can't have dependences
5974       // between accesses in an interleaved group and other accesses located
5975       // between the first and last member of the group. Note that this also
5976       // means that a group can't have more than one member at a given offset.
5977       // The accesses in a group can have dependences with other accesses, but
5978       // we must ensure we don't extend the boundaries of the group such that
5979       // we encompass those dependent accesses.
5980       //
5981       // For example, assume we have the sequence of accesses shown below in a
5982       // stride-2 loop:
5983       //
5984       //  (1, 2) is a group | A[i]   = a;  // (1)
5985       //                    | A[i-1] = b;  // (2) |
5986       //                      A[i-3] = c;  // (3)
5987       //                      A[i]   = d;  // (4) | (2, 4) is not a group
5988       //
5989       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
5990       // but not with (4). If we did, the dependent access (3) would be within
5991       // the boundaries of the (2, 4) group.
5992       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
5993 
5994         // If a dependence exists and A is already in a group, we know that A
5995         // must be a store since A precedes B and WAR dependences are allowed.
5996         // Thus, A would be sunk below B. We release A's group to prevent this
5997         // illegal code motion. A will then be free to form another group with
5998         // instructions that precede it.
5999         if (isInterleaved(A)) {
6000           InterleaveGroup *StoreGroup = getInterleaveGroup(A);
6001           StoreGroups.remove(StoreGroup);
6002           releaseGroup(StoreGroup);
6003         }
6004 
6005         // If a dependence exists and A is not already in a group (or it was
6006         // and we just released it), B might be hoisted above A (if B is a
6007         // load) or another store might be sunk below A (if B is a store). In
6008         // either case, we can't add additional instructions to B's group. B
6009         // will only form a group with instructions that it precedes.
6010         break;
6011       }
6012 
6013       // At this point, we've checked for illegal code motion. If either A or B
6014       // isn't strided, there's nothing left to do.
6015       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
6016         continue;
6017 
6018       // Ignore A if it's already in a group or isn't the same kind of memory
6019       // operation as B.
6020       if (isInterleaved(A) || A->mayReadFromMemory() != B->mayReadFromMemory())
6021         continue;
6022 
6023       // Check rules 1 and 2. Ignore A if its stride or size is different from
6024       // that of B.
6025       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
6026         continue;
6027 
6028       // Ignore A if the memory object of A and B don't belong to the same
6029       // address space
6030       if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
6031         continue;
6032 
6033       // Calculate the distance from A to B.
6034       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
6035           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
6036       if (!DistToB)
6037         continue;
6038       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
6039 
6040       // Check rule 3. Ignore A if its distance to B is not a multiple of the
6041       // size.
6042       if (DistanceToB % static_cast<int64_t>(DesB.Size))
6043         continue;
6044 
6045       // Ignore A if either A or B is in a predicated block. Although we
6046       // currently prevent group formation for predicated accesses, we may be
6047       // able to relax this limitation in the future once we handle more
6048       // complicated blocks.
6049       if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
6050         continue;
6051 
6052       // The index of A is the index of B plus A's distance to B in multiples
6053       // of the size.
6054       int IndexA =
6055           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
6056 
6057       // Try to insert A into B's group.
6058       if (Group->insertMember(A, IndexA, DesA.Align)) {
6059         DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
6060                      << "    into the interleave group with" << *B << '\n');
6061         InterleaveGroupMap[A] = Group;
6062 
6063         // Set the first load in program order as the insert position.
6064         if (A->mayReadFromMemory())
6065           Group->setInsertPos(A);
6066       }
6067     } // Iteration over A accesses.
6068   } // Iteration over B accesses.
6069 
6070   // Remove interleaved store groups with gaps.
6071   for (InterleaveGroup *Group : StoreGroups)
6072     if (Group->getNumMembers() != Group->getFactor())
6073       releaseGroup(Group);
6074 
6075   // Remove interleaved groups with gaps (currently only loads) whose memory
6076   // accesses may wrap around. We have to revisit the getPtrStride analysis,
6077   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
6078   // not check wrapping (see documentation there).
6079   // FORNOW we use Assume=false;
6080   // TODO: Change to Assume=true but making sure we don't exceed the threshold
6081   // of runtime SCEV assumptions checks (thereby potentially failing to
6082   // vectorize altogether).
6083   // Additional optional optimizations:
6084   // TODO: If we are peeling the loop and we know that the first pointer doesn't
6085   // wrap then we can deduce that all pointers in the group don't wrap.
6086   // This means that we can forcefully peel the loop in order to only have to
6087   // check the first pointer for no-wrap. When we'll change to use Assume=true
6088   // we'll only need at most one runtime check per interleaved group.
6089   //
6090   for (InterleaveGroup *Group : LoadGroups) {
6091 
6092     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
6093     // load would wrap around the address space we would do a memory access at
6094     // nullptr even without the transformation.
6095     if (Group->getNumMembers() == Group->getFactor())
6096       continue;
6097 
6098     // Case 2: If first and last members of the group don't wrap this implies
6099     // that all the pointers in the group don't wrap.
6100     // So we check only group member 0 (which is always guaranteed to exist),
6101     // and group member Factor - 1; If the latter doesn't exist we rely on
6102     // peeling (if it is a non-reveresed accsess -- see Case 3).
6103     Value *FirstMemberPtr = getPointerOperand(Group->getMember(0));
6104     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
6105                       /*ShouldCheckWrap=*/true)) {
6106       DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6107                       "first group member potentially pointer-wrapping.\n");
6108       releaseGroup(Group);
6109       continue;
6110     }
6111     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
6112     if (LastMember) {
6113       Value *LastMemberPtr = getPointerOperand(LastMember);
6114       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
6115                         /*ShouldCheckWrap=*/true)) {
6116         DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6117                         "last group member potentially pointer-wrapping.\n");
6118         releaseGroup(Group);
6119       }
6120     } else {
6121       // Case 3: A non-reversed interleaved load group with gaps: We need
6122       // to execute at least one scalar epilogue iteration. This will ensure
6123       // we don't speculatively access memory out-of-bounds. We only need
6124       // to look for a member at index factor - 1, since every group must have
6125       // a member at index zero.
6126       if (Group->isReverse()) {
6127         releaseGroup(Group);
6128         continue;
6129       }
6130       DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
6131       RequiresScalarEpilogue = true;
6132     }
6133   }
6134 }
6135 
6136 LoopVectorizationCostModel::VectorizationFactor
6137 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
6138   // Width 1 means no vectorize
6139   VectorizationFactor Factor = {1U, 0U};
6140   if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
6141     ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
6142               << "runtime pointer checks needed. Enable vectorization of this "
6143                  "loop with '#pragma clang loop vectorize(enable)' when "
6144                  "compiling with -Os/-Oz");
6145     DEBUG(dbgs()
6146           << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
6147     return Factor;
6148   }
6149 
6150   if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
6151     ORE->emit(createMissedAnalysis("ConditionalStore")
6152               << "store that is conditionally executed prevents vectorization");
6153     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
6154     return Factor;
6155   }
6156 
6157   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
6158   unsigned SmallestType, WidestType;
6159   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
6160   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
6161   unsigned MaxSafeDepDist = -1U;
6162 
6163   // Get the maximum safe dependence distance in bits computed by LAA. If the
6164   // loop contains any interleaved accesses, we divide the dependence distance
6165   // by the maximum interleave factor of all interleaved groups. Note that
6166   // although the division ensures correctness, this is a fairly conservative
6167   // computation because the maximum distance computed by LAA may not involve
6168   // any of the interleaved accesses.
6169   if (Legal->getMaxSafeDepDistBytes() != -1U)
6170     MaxSafeDepDist =
6171         Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor();
6172 
6173   WidestRegister =
6174       ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist);
6175   unsigned MaxVectorSize = WidestRegister / WidestType;
6176 
6177   DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
6178                << WidestType << " bits.\n");
6179   DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister
6180                << " bits.\n");
6181 
6182   if (MaxVectorSize == 0) {
6183     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
6184     MaxVectorSize = 1;
6185   }
6186 
6187   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
6188                                 " into one vector!");
6189 
6190   unsigned VF = MaxVectorSize;
6191   if (MaximizeBandwidth && !OptForSize) {
6192     // Collect all viable vectorization factors.
6193     SmallVector<unsigned, 8> VFs;
6194     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
6195     for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
6196       VFs.push_back(VS);
6197 
6198     // For each VF calculate its register usage.
6199     auto RUs = calculateRegisterUsage(VFs);
6200 
6201     // Select the largest VF which doesn't require more registers than existing
6202     // ones.
6203     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
6204     for (int i = RUs.size() - 1; i >= 0; --i) {
6205       if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
6206         VF = VFs[i];
6207         break;
6208       }
6209     }
6210   }
6211 
6212   // If we optimize the program for size, avoid creating the tail loop.
6213   if (OptForSize) {
6214     unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6215     DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
6216 
6217     // If we don't know the precise trip count, don't try to vectorize.
6218     if (TC < 2) {
6219       ORE->emit(
6220           createMissedAnalysis("UnknownLoopCountComplexCFG")
6221           << "unable to calculate the loop count due to complex control flow");
6222       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6223       return Factor;
6224     }
6225 
6226     // Find the maximum SIMD width that can fit within the trip count.
6227     VF = TC % MaxVectorSize;
6228 
6229     if (VF == 0)
6230       VF = MaxVectorSize;
6231     else {
6232       // If the trip count that we found modulo the vectorization factor is not
6233       // zero then we require a tail.
6234       ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
6235                 << "cannot optimize for size and vectorize at the "
6236                    "same time. Enable vectorization of this loop "
6237                    "with '#pragma clang loop vectorize(enable)' "
6238                    "when compiling with -Os/-Oz");
6239       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6240       return Factor;
6241     }
6242   }
6243 
6244   int UserVF = Hints->getWidth();
6245   if (UserVF != 0) {
6246     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
6247     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
6248 
6249     Factor.Width = UserVF;
6250 
6251     collectUniformsAndScalars(UserVF);
6252     collectInstsToScalarize(UserVF);
6253     return Factor;
6254   }
6255 
6256   float Cost = expectedCost(1).first;
6257 #ifndef NDEBUG
6258   const float ScalarCost = Cost;
6259 #endif /* NDEBUG */
6260   unsigned Width = 1;
6261   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
6262 
6263   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6264   // Ignore scalar width, because the user explicitly wants vectorization.
6265   if (ForceVectorization && VF > 1) {
6266     Width = 2;
6267     Cost = expectedCost(Width).first / (float)Width;
6268   }
6269 
6270   for (unsigned i = 2; i <= VF; i *= 2) {
6271     // Notice that the vector loop needs to be executed less times, so
6272     // we need to divide the cost of the vector loops by the width of
6273     // the vector elements.
6274     VectorizationCostTy C = expectedCost(i);
6275     float VectorCost = C.first / (float)i;
6276     DEBUG(dbgs() << "LV: Vector loop of width " << i
6277                  << " costs: " << (int)VectorCost << ".\n");
6278     if (!C.second && !ForceVectorization) {
6279       DEBUG(
6280           dbgs() << "LV: Not considering vector loop of width " << i
6281                  << " because it will not generate any vector instructions.\n");
6282       continue;
6283     }
6284     if (VectorCost < Cost) {
6285       Cost = VectorCost;
6286       Width = i;
6287     }
6288   }
6289 
6290   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
6291         << "LV: Vectorization seems to be not beneficial, "
6292         << "but was forced by a user.\n");
6293   DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
6294   Factor.Width = Width;
6295   Factor.Cost = Width * Cost;
6296   return Factor;
6297 }
6298 
6299 std::pair<unsigned, unsigned>
6300 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6301   unsigned MinWidth = -1U;
6302   unsigned MaxWidth = 8;
6303   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6304 
6305   // For each block.
6306   for (BasicBlock *BB : TheLoop->blocks()) {
6307     // For each instruction in the loop.
6308     for (Instruction &I : *BB) {
6309       Type *T = I.getType();
6310 
6311       // Skip ignored values.
6312       if (ValuesToIgnore.count(&I))
6313         continue;
6314 
6315       // Only examine Loads, Stores and PHINodes.
6316       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6317         continue;
6318 
6319       // Examine PHI nodes that are reduction variables. Update the type to
6320       // account for the recurrence type.
6321       if (auto *PN = dyn_cast<PHINode>(&I)) {
6322         if (!Legal->isReductionVariable(PN))
6323           continue;
6324         RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
6325         T = RdxDesc.getRecurrenceType();
6326       }
6327 
6328       // Examine the stored values.
6329       if (auto *ST = dyn_cast<StoreInst>(&I))
6330         T = ST->getValueOperand()->getType();
6331 
6332       // Ignore loaded pointer types and stored pointer types that are not
6333       // vectorizable.
6334       //
6335       // FIXME: The check here attempts to predict whether a load or store will
6336       //        be vectorized. We only know this for certain after a VF has
6337       //        been selected. Here, we assume that if an access can be
6338       //        vectorized, it will be. We should also look at extending this
6339       //        optimization to non-pointer types.
6340       //
6341       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6342           !Legal->isAccessInterleaved(&I) && !Legal->isLegalGatherOrScatter(&I))
6343         continue;
6344 
6345       MinWidth = std::min(MinWidth,
6346                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6347       MaxWidth = std::max(MaxWidth,
6348                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6349     }
6350   }
6351 
6352   return {MinWidth, MaxWidth};
6353 }
6354 
6355 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
6356                                                            unsigned VF,
6357                                                            unsigned LoopCost) {
6358 
6359   // -- The interleave heuristics --
6360   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6361   // There are many micro-architectural considerations that we can't predict
6362   // at this level. For example, frontend pressure (on decode or fetch) due to
6363   // code size, or the number and capabilities of the execution ports.
6364   //
6365   // We use the following heuristics to select the interleave count:
6366   // 1. If the code has reductions, then we interleave to break the cross
6367   // iteration dependency.
6368   // 2. If the loop is really small, then we interleave to reduce the loop
6369   // overhead.
6370   // 3. We don't interleave if we think that we will spill registers to memory
6371   // due to the increased register pressure.
6372 
6373   // When we optimize for size, we don't interleave.
6374   if (OptForSize)
6375     return 1;
6376 
6377   // We used the distance for the interleave count.
6378   if (Legal->getMaxSafeDepDistBytes() != -1U)
6379     return 1;
6380 
6381   // Do not interleave loops with a relatively small trip count.
6382   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6383   if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
6384     return 1;
6385 
6386   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
6387   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6388                << " registers\n");
6389 
6390   if (VF == 1) {
6391     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6392       TargetNumRegisters = ForceTargetNumScalarRegs;
6393   } else {
6394     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6395       TargetNumRegisters = ForceTargetNumVectorRegs;
6396   }
6397 
6398   RegisterUsage R = calculateRegisterUsage({VF})[0];
6399   // We divide by these constants so assume that we have at least one
6400   // instruction that uses at least one register.
6401   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
6402   R.NumInstructions = std::max(R.NumInstructions, 1U);
6403 
6404   // We calculate the interleave count using the following formula.
6405   // Subtract the number of loop invariants from the number of available
6406   // registers. These registers are used by all of the interleaved instances.
6407   // Next, divide the remaining registers by the number of registers that is
6408   // required by the loop, in order to estimate how many parallel instances
6409   // fit without causing spills. All of this is rounded down if necessary to be
6410   // a power of two. We want power of two interleave count to simplify any
6411   // addressing operations or alignment considerations.
6412   unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
6413                               R.MaxLocalUsers);
6414 
6415   // Don't count the induction variable as interleaved.
6416   if (EnableIndVarRegisterHeur)
6417     IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
6418                        std::max(1U, (R.MaxLocalUsers - 1)));
6419 
6420   // Clamp the interleave ranges to reasonable counts.
6421   unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
6422 
6423   // Check if the user has overridden the max.
6424   if (VF == 1) {
6425     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6426       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6427   } else {
6428     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6429       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6430   }
6431 
6432   // If we did not calculate the cost for VF (because the user selected the VF)
6433   // then we calculate the cost of VF here.
6434   if (LoopCost == 0)
6435     LoopCost = expectedCost(VF).first;
6436 
6437   // Clamp the calculated IC to be between the 1 and the max interleave count
6438   // that the target allows.
6439   if (IC > MaxInterleaveCount)
6440     IC = MaxInterleaveCount;
6441   else if (IC < 1)
6442     IC = 1;
6443 
6444   // Interleave if we vectorized this loop and there is a reduction that could
6445   // benefit from interleaving.
6446   if (VF > 1 && Legal->getReductionVars()->size()) {
6447     DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6448     return IC;
6449   }
6450 
6451   // Note that if we've already vectorized the loop we will have done the
6452   // runtime check and so interleaving won't require further checks.
6453   bool InterleavingRequiresRuntimePointerCheck =
6454       (VF == 1 && Legal->getRuntimePointerChecking()->Need);
6455 
6456   // We want to interleave small loops in order to reduce the loop overhead and
6457   // potentially expose ILP opportunities.
6458   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
6459   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6460     // We assume that the cost overhead is 1 and we use the cost model
6461     // to estimate the cost of the loop and interleave until the cost of the
6462     // loop overhead is about 5% of the cost of the loop.
6463     unsigned SmallIC =
6464         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6465 
6466     // Interleave until store/load ports (estimated by max interleave count) are
6467     // saturated.
6468     unsigned NumStores = Legal->getNumStores();
6469     unsigned NumLoads = Legal->getNumLoads();
6470     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6471     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6472 
6473     // If we have a scalar reduction (vector reductions are already dealt with
6474     // by this point), we can increase the critical path length if the loop
6475     // we're interleaving is inside another loop. Limit, by default to 2, so the
6476     // critical path only gets increased by one reduction operation.
6477     if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) {
6478       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6479       SmallIC = std::min(SmallIC, F);
6480       StoresIC = std::min(StoresIC, F);
6481       LoadsIC = std::min(LoadsIC, F);
6482     }
6483 
6484     if (EnableLoadStoreRuntimeInterleave &&
6485         std::max(StoresIC, LoadsIC) > SmallIC) {
6486       DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6487       return std::max(StoresIC, LoadsIC);
6488     }
6489 
6490     DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6491     return SmallIC;
6492   }
6493 
6494   // Interleave if this is a large loop (small loops are already dealt with by
6495   // this point) that could benefit from interleaving.
6496   bool HasReductions = (Legal->getReductionVars()->size() > 0);
6497   if (TTI.enableAggressiveInterleaving(HasReductions)) {
6498     DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6499     return IC;
6500   }
6501 
6502   DEBUG(dbgs() << "LV: Not Interleaving.\n");
6503   return 1;
6504 }
6505 
6506 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6507 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
6508   // This function calculates the register usage by measuring the highest number
6509   // of values that are alive at a single location. Obviously, this is a very
6510   // rough estimation. We scan the loop in a topological order in order and
6511   // assign a number to each instruction. We use RPO to ensure that defs are
6512   // met before their users. We assume that each instruction that has in-loop
6513   // users starts an interval. We record every time that an in-loop value is
6514   // used, so we have a list of the first and last occurrences of each
6515   // instruction. Next, we transpose this data structure into a multi map that
6516   // holds the list of intervals that *end* at a specific location. This multi
6517   // map allows us to perform a linear search. We scan the instructions linearly
6518   // and record each time that a new interval starts, by placing it in a set.
6519   // If we find this value in the multi-map then we remove it from the set.
6520   // The max register usage is the maximum size of the set.
6521   // We also search for instructions that are defined outside the loop, but are
6522   // used inside the loop. We need this number separately from the max-interval
6523   // usage number because when we unroll, loop-invariant values do not take
6524   // more register.
6525   LoopBlocksDFS DFS(TheLoop);
6526   DFS.perform(LI);
6527 
6528   RegisterUsage RU;
6529   RU.NumInstructions = 0;
6530 
6531   // Each 'key' in the map opens a new interval. The values
6532   // of the map are the index of the 'last seen' usage of the
6533   // instruction that is the key.
6534   typedef DenseMap<Instruction *, unsigned> IntervalMap;
6535   // Maps instruction to its index.
6536   DenseMap<unsigned, Instruction *> IdxToInstr;
6537   // Marks the end of each interval.
6538   IntervalMap EndPoint;
6539   // Saves the list of instruction indices that are used in the loop.
6540   SmallSet<Instruction *, 8> Ends;
6541   // Saves the list of values that are used in the loop but are
6542   // defined outside the loop, such as arguments and constants.
6543   SmallPtrSet<Value *, 8> LoopInvariants;
6544 
6545   unsigned Index = 0;
6546   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6547     RU.NumInstructions += BB->size();
6548     for (Instruction &I : *BB) {
6549       IdxToInstr[Index++] = &I;
6550 
6551       // Save the end location of each USE.
6552       for (Value *U : I.operands()) {
6553         auto *Instr = dyn_cast<Instruction>(U);
6554 
6555         // Ignore non-instruction values such as arguments, constants, etc.
6556         if (!Instr)
6557           continue;
6558 
6559         // If this instruction is outside the loop then record it and continue.
6560         if (!TheLoop->contains(Instr)) {
6561           LoopInvariants.insert(Instr);
6562           continue;
6563         }
6564 
6565         // Overwrite previous end points.
6566         EndPoint[Instr] = Index;
6567         Ends.insert(Instr);
6568       }
6569     }
6570   }
6571 
6572   // Saves the list of intervals that end with the index in 'key'.
6573   typedef SmallVector<Instruction *, 2> InstrList;
6574   DenseMap<unsigned, InstrList> TransposeEnds;
6575 
6576   // Transpose the EndPoints to a list of values that end at each index.
6577   for (auto &Interval : EndPoint)
6578     TransposeEnds[Interval.second].push_back(Interval.first);
6579 
6580   SmallSet<Instruction *, 8> OpenIntervals;
6581 
6582   // Get the size of the widest register.
6583   unsigned MaxSafeDepDist = -1U;
6584   if (Legal->getMaxSafeDepDistBytes() != -1U)
6585     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
6586   unsigned WidestRegister =
6587       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
6588   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6589 
6590   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6591   SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
6592 
6593   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6594 
6595   // A lambda that gets the register usage for the given type and VF.
6596   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
6597     if (Ty->isTokenTy())
6598       return 0U;
6599     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
6600     return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
6601   };
6602 
6603   for (unsigned int i = 0; i < Index; ++i) {
6604     Instruction *I = IdxToInstr[i];
6605 
6606     // Remove all of the instructions that end at this location.
6607     InstrList &List = TransposeEnds[i];
6608     for (Instruction *ToRemove : List)
6609       OpenIntervals.erase(ToRemove);
6610 
6611     // Ignore instructions that are never used within the loop.
6612     if (!Ends.count(I))
6613       continue;
6614 
6615     // Skip ignored values.
6616     if (ValuesToIgnore.count(I))
6617       continue;
6618 
6619     // For each VF find the maximum usage of registers.
6620     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6621       if (VFs[j] == 1) {
6622         MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
6623         continue;
6624       }
6625       collectUniformsAndScalars(VFs[j]);
6626       // Count the number of live intervals.
6627       unsigned RegUsage = 0;
6628       for (auto Inst : OpenIntervals) {
6629         // Skip ignored values for VF > 1.
6630         if (VecValuesToIgnore.count(Inst) ||
6631             isScalarAfterVectorization(Inst, VFs[j]))
6632           continue;
6633         RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
6634       }
6635       MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
6636     }
6637 
6638     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6639                  << OpenIntervals.size() << '\n');
6640 
6641     // Add the current instruction to the list of open intervals.
6642     OpenIntervals.insert(I);
6643   }
6644 
6645   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6646     unsigned Invariant = 0;
6647     if (VFs[i] == 1)
6648       Invariant = LoopInvariants.size();
6649     else {
6650       for (auto Inst : LoopInvariants)
6651         Invariant += GetRegUsage(Inst->getType(), VFs[i]);
6652     }
6653 
6654     DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
6655     DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
6656     DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
6657     DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
6658 
6659     RU.LoopInvariantRegs = Invariant;
6660     RU.MaxLocalUsers = MaxUsages[i];
6661     RUs[i] = RU;
6662   }
6663 
6664   return RUs;
6665 }
6666 
6667 void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
6668 
6669   // If we aren't vectorizing the loop, or if we've already collected the
6670   // instructions to scalarize, there's nothing to do. Collection may already
6671   // have occurred if we have a user-selected VF and are now computing the
6672   // expected cost for interleaving.
6673   if (VF < 2 || InstsToScalarize.count(VF))
6674     return;
6675 
6676   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6677   // not profitable to scalarize any instructions, the presence of VF in the
6678   // map will indicate that we've analyzed it already.
6679   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6680 
6681   // Find all the instructions that are scalar with predication in the loop and
6682   // determine if it would be better to not if-convert the blocks they are in.
6683   // If so, we also record the instructions to scalarize.
6684   for (BasicBlock *BB : TheLoop->blocks()) {
6685     if (!Legal->blockNeedsPredication(BB))
6686       continue;
6687     for (Instruction &I : *BB)
6688       if (Legal->isScalarWithPredication(&I)) {
6689         ScalarCostsTy ScalarCosts;
6690         if (computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6691           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6692       }
6693   }
6694 }
6695 
6696 int LoopVectorizationCostModel::computePredInstDiscount(
6697     Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
6698     unsigned VF) {
6699 
6700   assert(!isUniformAfterVectorization(PredInst, VF) &&
6701          "Instruction marked uniform-after-vectorization will be predicated");
6702 
6703   // Initialize the discount to zero, meaning that the scalar version and the
6704   // vector version cost the same.
6705   int Discount = 0;
6706 
6707   // Holds instructions to analyze. The instructions we visit are mapped in
6708   // ScalarCosts. Those instructions are the ones that would be scalarized if
6709   // we find that the scalar version costs less.
6710   SmallVector<Instruction *, 8> Worklist;
6711 
6712   // Returns true if the given instruction can be scalarized.
6713   auto canBeScalarized = [&](Instruction *I) -> bool {
6714 
6715     // We only attempt to scalarize instructions forming a single-use chain
6716     // from the original predicated block that would otherwise be vectorized.
6717     // Although not strictly necessary, we give up on instructions we know will
6718     // already be scalar to avoid traversing chains that are unlikely to be
6719     // beneficial.
6720     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6721         isScalarAfterVectorization(I, VF))
6722       return false;
6723 
6724     // If the instruction is scalar with predication, it will be analyzed
6725     // separately. We ignore it within the context of PredInst.
6726     if (Legal->isScalarWithPredication(I))
6727       return false;
6728 
6729     // If any of the instruction's operands are uniform after vectorization,
6730     // the instruction cannot be scalarized. This prevents, for example, a
6731     // masked load from being scalarized.
6732     //
6733     // We assume we will only emit a value for lane zero of an instruction
6734     // marked uniform after vectorization, rather than VF identical values.
6735     // Thus, if we scalarize an instruction that uses a uniform, we would
6736     // create uses of values corresponding to the lanes we aren't emitting code
6737     // for. This behavior can be changed by allowing getScalarValue to clone
6738     // the lane zero values for uniforms rather than asserting.
6739     for (Use &U : I->operands())
6740       if (auto *J = dyn_cast<Instruction>(U.get()))
6741         if (isUniformAfterVectorization(J, VF))
6742           return false;
6743 
6744     // Otherwise, we can scalarize the instruction.
6745     return true;
6746   };
6747 
6748   // Returns true if an operand that cannot be scalarized must be extracted
6749   // from a vector. We will account for this scalarization overhead below. Note
6750   // that the non-void predicated instructions are placed in their own blocks,
6751   // and their return values are inserted into vectors. Thus, an extract would
6752   // still be required.
6753   auto needsExtract = [&](Instruction *I) -> bool {
6754     return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
6755   };
6756 
6757   // Compute the expected cost discount from scalarizing the entire expression
6758   // feeding the predicated instruction. We currently only consider expressions
6759   // that are single-use instruction chains.
6760   Worklist.push_back(PredInst);
6761   while (!Worklist.empty()) {
6762     Instruction *I = Worklist.pop_back_val();
6763 
6764     // If we've already analyzed the instruction, there's nothing to do.
6765     if (ScalarCosts.count(I))
6766       continue;
6767 
6768     // Compute the cost of the vector instruction. Note that this cost already
6769     // includes the scalarization overhead of the predicated instruction.
6770     unsigned VectorCost = getInstructionCost(I, VF).first;
6771 
6772     // Compute the cost of the scalarized instruction. This cost is the cost of
6773     // the instruction as if it wasn't if-converted and instead remained in the
6774     // predicated block. We will scale this cost by block probability after
6775     // computing the scalarization overhead.
6776     unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
6777 
6778     // Compute the scalarization overhead of needed insertelement instructions
6779     // and phi nodes.
6780     if (Legal->isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6781       ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
6782                                                  true, false);
6783       ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
6784     }
6785 
6786     // Compute the scalarization overhead of needed extractelement
6787     // instructions. For each of the instruction's operands, if the operand can
6788     // be scalarized, add it to the worklist; otherwise, account for the
6789     // overhead.
6790     for (Use &U : I->operands())
6791       if (auto *J = dyn_cast<Instruction>(U.get())) {
6792         assert(VectorType::isValidElementType(J->getType()) &&
6793                "Instruction has non-scalar type");
6794         if (canBeScalarized(J))
6795           Worklist.push_back(J);
6796         else if (needsExtract(J))
6797           ScalarCost += TTI.getScalarizationOverhead(
6798                               ToVectorTy(J->getType(),VF), false, true);
6799       }
6800 
6801     // Scale the total scalar cost by block probability.
6802     ScalarCost /= getReciprocalPredBlockProb();
6803 
6804     // Compute the discount. A non-negative discount means the vector version
6805     // of the instruction costs more, and scalarizing would be beneficial.
6806     Discount += VectorCost - ScalarCost;
6807     ScalarCosts[I] = ScalarCost;
6808   }
6809 
6810   return Discount;
6811 }
6812 
6813 LoopVectorizationCostModel::VectorizationCostTy
6814 LoopVectorizationCostModel::expectedCost(unsigned VF) {
6815   VectorizationCostTy Cost;
6816 
6817   // Collect Uniform and Scalar instructions after vectorization with VF.
6818   collectUniformsAndScalars(VF);
6819 
6820   // Collect the instructions (and their associated costs) that will be more
6821   // profitable to scalarize.
6822   collectInstsToScalarize(VF);
6823 
6824   // For each block.
6825   for (BasicBlock *BB : TheLoop->blocks()) {
6826     VectorizationCostTy BlockCost;
6827 
6828     // For each instruction in the old loop.
6829     for (Instruction &I : *BB) {
6830       // Skip dbg intrinsics.
6831       if (isa<DbgInfoIntrinsic>(I))
6832         continue;
6833 
6834       // Skip ignored values.
6835       if (ValuesToIgnore.count(&I))
6836         continue;
6837 
6838       VectorizationCostTy C = getInstructionCost(&I, VF);
6839 
6840       // Check if we should override the cost.
6841       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6842         C.first = ForceTargetInstructionCost;
6843 
6844       BlockCost.first += C.first;
6845       BlockCost.second |= C.second;
6846       DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "
6847                    << VF << " For instruction: " << I << '\n');
6848     }
6849 
6850     // If we are vectorizing a predicated block, it will have been
6851     // if-converted. This means that the block's instructions (aside from
6852     // stores and instructions that may divide by zero) will now be
6853     // unconditionally executed. For the scalar case, we may not always execute
6854     // the predicated block. Thus, scale the block's cost by the probability of
6855     // executing it.
6856     if (VF == 1 && Legal->blockNeedsPredication(BB))
6857       BlockCost.first /= getReciprocalPredBlockProb();
6858 
6859     Cost.first += BlockCost.first;
6860     Cost.second |= BlockCost.second;
6861   }
6862 
6863   return Cost;
6864 }
6865 
6866 /// \brief Gets Address Access SCEV after verifying that the access pattern
6867 /// is loop invariant except the induction variable dependence.
6868 ///
6869 /// This SCEV can be sent to the Target in order to estimate the address
6870 /// calculation cost.
6871 static const SCEV *getAddressAccessSCEV(
6872               Value *Ptr,
6873               LoopVectorizationLegality *Legal,
6874               ScalarEvolution *SE,
6875               const Loop *TheLoop) {
6876   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6877   if (!Gep)
6878     return nullptr;
6879 
6880   // We are looking for a gep with all loop invariant indices except for one
6881   // which should be an induction variable.
6882   unsigned NumOperands = Gep->getNumOperands();
6883   for (unsigned i = 1; i < NumOperands; ++i) {
6884     Value *Opd = Gep->getOperand(i);
6885     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6886         !Legal->isInductionVariable(Opd))
6887       return nullptr;
6888   }
6889 
6890   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6891   return SE->getSCEV(Ptr);
6892 }
6893 
6894 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6895   return Legal->hasStride(I->getOperand(0)) ||
6896          Legal->hasStride(I->getOperand(1));
6897 }
6898 
6899 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6900                                                                  unsigned VF) {
6901   Type *ValTy = getMemInstValueType(I);
6902   auto SE = PSE.getSE();
6903 
6904   unsigned Alignment = getMemInstAlignment(I);
6905   unsigned AS = getMemInstAddressSpace(I);
6906   Value *Ptr = getPointerOperand(I);
6907   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6908 
6909   // Figure out whether the access is strided and get the stride value
6910   // if it's known in compile time
6911   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, SE, TheLoop);
6912 
6913   // Get the cost of the scalar memory instruction and address computation.
6914   unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6915 
6916   Cost += VF *
6917           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6918                               AS);
6919 
6920   // Get the overhead of the extractelement and insertelement instructions
6921   // we might create due to scalarization.
6922   Cost += getScalarizationOverhead(I, VF, TTI);
6923 
6924   // If we have a predicated store, it may not be executed for each vector
6925   // lane. Scale the cost by the probability of executing the predicated
6926   // block.
6927   if (Legal->isScalarWithPredication(I))
6928     Cost /= getReciprocalPredBlockProb();
6929 
6930   return Cost;
6931 }
6932 
6933 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6934                                                              unsigned VF) {
6935   Type *ValTy = getMemInstValueType(I);
6936   Type *VectorTy = ToVectorTy(ValTy, VF);
6937   unsigned Alignment = getMemInstAlignment(I);
6938   Value *Ptr = getPointerOperand(I);
6939   unsigned AS = getMemInstAddressSpace(I);
6940   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6941 
6942   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6943          "Stride should be 1 or -1 for consecutive memory access");
6944   unsigned Cost = 0;
6945   if (Legal->isMaskRequired(I))
6946     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6947   else
6948     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6949 
6950   bool Reverse = ConsecutiveStride < 0;
6951   if (Reverse)
6952     Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6953   return Cost;
6954 }
6955 
6956 unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6957                                                          unsigned VF) {
6958   LoadInst *LI = cast<LoadInst>(I);
6959   Type *ValTy = LI->getType();
6960   Type *VectorTy = ToVectorTy(ValTy, VF);
6961   unsigned Alignment = LI->getAlignment();
6962   unsigned AS = LI->getPointerAddressSpace();
6963 
6964   return TTI.getAddressComputationCost(ValTy) +
6965          TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
6966          TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6967 }
6968 
6969 unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6970                                                           unsigned VF) {
6971   Type *ValTy = getMemInstValueType(I);
6972   Type *VectorTy = ToVectorTy(ValTy, VF);
6973   unsigned Alignment = getMemInstAlignment(I);
6974   Value *Ptr = getPointerOperand(I);
6975 
6976   return TTI.getAddressComputationCost(VectorTy) +
6977          TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
6978                                     Legal->isMaskRequired(I), Alignment);
6979 }
6980 
6981 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6982                                                             unsigned VF) {
6983   Type *ValTy = getMemInstValueType(I);
6984   Type *VectorTy = ToVectorTy(ValTy, VF);
6985   unsigned AS = getMemInstAddressSpace(I);
6986 
6987   auto Group = Legal->getInterleavedAccessGroup(I);
6988   assert(Group && "Fail to get an interleaved access group.");
6989 
6990   unsigned InterleaveFactor = Group->getFactor();
6991   Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6992 
6993   // Holds the indices of existing members in an interleaved load group.
6994   // An interleaved store group doesn't need this as it doesn't allow gaps.
6995   SmallVector<unsigned, 4> Indices;
6996   if (isa<LoadInst>(I)) {
6997     for (unsigned i = 0; i < InterleaveFactor; i++)
6998       if (Group->getMember(i))
6999         Indices.push_back(i);
7000   }
7001 
7002   // Calculate the cost of the whole interleaved group.
7003   unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy,
7004                                                  Group->getFactor(), Indices,
7005                                                  Group->getAlignment(), AS);
7006 
7007   if (Group->isReverse())
7008     Cost += Group->getNumMembers() *
7009             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
7010   return Cost;
7011 }
7012 
7013 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7014                                                               unsigned VF) {
7015 
7016   // Calculate scalar cost only. Vectorization cost should be ready at this
7017   // moment.
7018   if (VF == 1) {
7019     Type *ValTy = getMemInstValueType(I);
7020     unsigned Alignment = getMemInstAlignment(I);
7021     unsigned AS = getMemInstAlignment(I);
7022 
7023     return TTI.getAddressComputationCost(ValTy) +
7024            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS);
7025   }
7026   return getWideningCost(I, VF);
7027 }
7028 
7029 LoopVectorizationCostModel::VectorizationCostTy
7030 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
7031   // If we know that this instruction will remain uniform, check the cost of
7032   // the scalar version.
7033   if (isUniformAfterVectorization(I, VF))
7034     VF = 1;
7035 
7036   if (VF > 1 && isProfitableToScalarize(I, VF))
7037     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7038 
7039   Type *VectorTy;
7040   unsigned C = getInstructionCost(I, VF, VectorTy);
7041 
7042   bool TypeNotScalarized =
7043       VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF;
7044   return VectorizationCostTy(C, TypeNotScalarized);
7045 }
7046 
7047 void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
7048   if (VF == 1)
7049     return;
7050   for (BasicBlock *BB : TheLoop->blocks()) {
7051     // For each instruction in the old loop.
7052     for (Instruction &I : *BB) {
7053       Value *Ptr = getPointerOperand(&I);
7054       if (!Ptr)
7055         continue;
7056 
7057       if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
7058         // Scalar load + broadcast
7059         unsigned Cost = getUniformMemOpCost(&I, VF);
7060         setWideningDecision(&I, VF, CM_Scalarize, Cost);
7061         continue;
7062       }
7063 
7064       // We assume that widening is the best solution when possible.
7065       if (Legal->memoryInstructionCanBeWidened(&I, VF)) {
7066         unsigned Cost = getConsecutiveMemOpCost(&I, VF);
7067         setWideningDecision(&I, VF, CM_Widen, Cost);
7068         continue;
7069       }
7070 
7071       // Choose between Interleaving, Gather/Scatter or Scalarization.
7072       unsigned InterleaveCost = UINT_MAX;
7073       unsigned NumAccesses = 1;
7074       if (Legal->isAccessInterleaved(&I)) {
7075         auto Group = Legal->getInterleavedAccessGroup(&I);
7076         assert(Group && "Fail to get an interleaved access group.");
7077 
7078         // Make one decision for the whole group.
7079         if (getWideningDecision(&I, VF) != CM_Unknown)
7080           continue;
7081 
7082         NumAccesses = Group->getNumMembers();
7083         InterleaveCost = getInterleaveGroupCost(&I, VF);
7084       }
7085 
7086       unsigned GatherScatterCost =
7087           Legal->isLegalGatherOrScatter(&I)
7088               ? getGatherScatterCost(&I, VF) * NumAccesses
7089               : UINT_MAX;
7090 
7091       unsigned ScalarizationCost =
7092           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7093 
7094       // Choose better solution for the current VF,
7095       // write down this decision and use it during vectorization.
7096       unsigned Cost;
7097       InstWidening Decision;
7098       if (InterleaveCost <= GatherScatterCost &&
7099           InterleaveCost < ScalarizationCost) {
7100         Decision = CM_Interleave;
7101         Cost = InterleaveCost;
7102       } else if (GatherScatterCost < ScalarizationCost) {
7103         Decision = CM_GatherScatter;
7104         Cost = GatherScatterCost;
7105       } else {
7106         Decision = CM_Scalarize;
7107         Cost = ScalarizationCost;
7108       }
7109       // If the instructions belongs to an interleave group, the whole group
7110       // receives the same decision. The whole group receives the cost, but
7111       // the cost will actually be assigned to one instruction.
7112       if (auto Group = Legal->getInterleavedAccessGroup(&I))
7113         setWideningDecision(Group, VF, Decision, Cost);
7114       else
7115         setWideningDecision(&I, VF, Decision, Cost);
7116     }
7117   }
7118 }
7119 
7120 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7121                                                         unsigned VF,
7122                                                         Type *&VectorTy) {
7123   Type *RetTy = I->getType();
7124   if (canTruncateToMinimalBitwidth(I, VF))
7125     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7126   VectorTy = ToVectorTy(RetTy, VF);
7127   auto SE = PSE.getSE();
7128 
7129   // TODO: We need to estimate the cost of intrinsic calls.
7130   switch (I->getOpcode()) {
7131   case Instruction::GetElementPtr:
7132     // We mark this instruction as zero-cost because the cost of GEPs in
7133     // vectorized code depends on whether the corresponding memory instruction
7134     // is scalarized or not. Therefore, we handle GEPs with the memory
7135     // instruction cost.
7136     return 0;
7137   case Instruction::Br: {
7138     return TTI.getCFInstrCost(I->getOpcode());
7139   }
7140   case Instruction::PHI: {
7141     auto *Phi = cast<PHINode>(I);
7142 
7143     // First-order recurrences are replaced by vector shuffles inside the loop.
7144     if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
7145       return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
7146                                 VectorTy, VF - 1, VectorTy);
7147 
7148     // TODO: IF-converted IFs become selects.
7149     return 0;
7150   }
7151   case Instruction::UDiv:
7152   case Instruction::SDiv:
7153   case Instruction::URem:
7154   case Instruction::SRem:
7155     // If we have a predicated instruction, it may not be executed for each
7156     // vector lane. Get the scalarization cost and scale this amount by the
7157     // probability of executing the predicated block. If the instruction is not
7158     // predicated, we fall through to the next case.
7159     if (VF > 1 && Legal->isScalarWithPredication(I)) {
7160       unsigned Cost = 0;
7161 
7162       // These instructions have a non-void type, so account for the phi nodes
7163       // that we will create. This cost is likely to be zero. The phi node
7164       // cost, if any, should be scaled by the block probability because it
7165       // models a copy at the end of each predicated block.
7166       Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
7167 
7168       // The cost of the non-predicated instruction.
7169       Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
7170 
7171       // The cost of insertelement and extractelement instructions needed for
7172       // scalarization.
7173       Cost += getScalarizationOverhead(I, VF, TTI);
7174 
7175       // Scale the cost by the probability of executing the predicated blocks.
7176       // This assumes the predicated block for each vector lane is equally
7177       // likely.
7178       return Cost / getReciprocalPredBlockProb();
7179     }
7180   case Instruction::Add:
7181   case Instruction::FAdd:
7182   case Instruction::Sub:
7183   case Instruction::FSub:
7184   case Instruction::Mul:
7185   case Instruction::FMul:
7186   case Instruction::FDiv:
7187   case Instruction::FRem:
7188   case Instruction::Shl:
7189   case Instruction::LShr:
7190   case Instruction::AShr:
7191   case Instruction::And:
7192   case Instruction::Or:
7193   case Instruction::Xor: {
7194     // Since we will replace the stride by 1 the multiplication should go away.
7195     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7196       return 0;
7197     // Certain instructions can be cheaper to vectorize if they have a constant
7198     // second vector operand. One example of this are shifts on x86.
7199     TargetTransformInfo::OperandValueKind Op1VK =
7200         TargetTransformInfo::OK_AnyValue;
7201     TargetTransformInfo::OperandValueKind Op2VK =
7202         TargetTransformInfo::OK_AnyValue;
7203     TargetTransformInfo::OperandValueProperties Op1VP =
7204         TargetTransformInfo::OP_None;
7205     TargetTransformInfo::OperandValueProperties Op2VP =
7206         TargetTransformInfo::OP_None;
7207     Value *Op2 = I->getOperand(1);
7208 
7209     // Check for a splat or for a non uniform vector of constants.
7210     if (isa<ConstantInt>(Op2)) {
7211       ConstantInt *CInt = cast<ConstantInt>(Op2);
7212       if (CInt && CInt->getValue().isPowerOf2())
7213         Op2VP = TargetTransformInfo::OP_PowerOf2;
7214       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7215     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
7216       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
7217       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
7218       if (SplatValue) {
7219         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
7220         if (CInt && CInt->getValue().isPowerOf2())
7221           Op2VP = TargetTransformInfo::OP_PowerOf2;
7222         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7223       }
7224     } else if (Legal->isUniform(Op2)) {
7225       Op2VK = TargetTransformInfo::OK_UniformValue;
7226     }
7227     SmallVector<const Value *, 4> Operands(I->operand_values());
7228     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK,
7229                                       Op2VK, Op1VP, Op2VP, Operands);
7230   }
7231   case Instruction::Select: {
7232     SelectInst *SI = cast<SelectInst>(I);
7233     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7234     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7235     Type *CondTy = SI->getCondition()->getType();
7236     if (!ScalarCond)
7237       CondTy = VectorType::get(CondTy, VF);
7238 
7239     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
7240   }
7241   case Instruction::ICmp:
7242   case Instruction::FCmp: {
7243     Type *ValTy = I->getOperand(0)->getType();
7244     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7245     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7246       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7247     VectorTy = ToVectorTy(ValTy, VF);
7248     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
7249   }
7250   case Instruction::Store:
7251   case Instruction::Load: {
7252     VectorTy = ToVectorTy(getMemInstValueType(I), VF);
7253     return getMemoryInstructionCost(I, VF);
7254   }
7255   case Instruction::ZExt:
7256   case Instruction::SExt:
7257   case Instruction::FPToUI:
7258   case Instruction::FPToSI:
7259   case Instruction::FPExt:
7260   case Instruction::PtrToInt:
7261   case Instruction::IntToPtr:
7262   case Instruction::SIToFP:
7263   case Instruction::UIToFP:
7264   case Instruction::Trunc:
7265   case Instruction::FPTrunc:
7266   case Instruction::BitCast: {
7267     // We optimize the truncation of induction variables having constant
7268     // integer steps. The cost of these truncations is the same as the scalar
7269     // operation.
7270     if (isOptimizableIVTruncate(I, VF)) {
7271       auto *Trunc = cast<TruncInst>(I);
7272       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7273                                   Trunc->getSrcTy());
7274     }
7275 
7276     Type *SrcScalarTy = I->getOperand(0)->getType();
7277     Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
7278     if (canTruncateToMinimalBitwidth(I, VF)) {
7279       // This cast is going to be shrunk. This may remove the cast or it might
7280       // turn it into slightly different cast. For example, if MinBW == 16,
7281       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7282       //
7283       // Calculate the modified src and dest types.
7284       Type *MinVecTy = VectorTy;
7285       if (I->getOpcode() == Instruction::Trunc) {
7286         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7287         VectorTy =
7288             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7289       } else if (I->getOpcode() == Instruction::ZExt ||
7290                  I->getOpcode() == Instruction::SExt) {
7291         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7292         VectorTy =
7293             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7294       }
7295     }
7296 
7297     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
7298   }
7299   case Instruction::Call: {
7300     bool NeedToScalarize;
7301     CallInst *CI = cast<CallInst>(I);
7302     unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
7303     if (getVectorIntrinsicIDForCall(CI, TLI))
7304       return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
7305     return CallCost;
7306   }
7307   default:
7308     // The cost of executing VF copies of the scalar instruction. This opcode
7309     // is unknown. Assume that it is the same as 'mul'.
7310     return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
7311            getScalarizationOverhead(I, VF, TTI);
7312   } // end of switch.
7313 }
7314 
7315 char LoopVectorize::ID = 0;
7316 static const char lv_name[] = "Loop Vectorization";
7317 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7318 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7319 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7320 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7321 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7322 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7323 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7324 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7325 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7326 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7327 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7328 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7329 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7330 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7331 
7332 namespace llvm {
7333 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
7334   return new LoopVectorize(NoUnrolling, AlwaysVectorize);
7335 }
7336 }
7337 
7338 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7339 
7340   // Check if the pointer operand of a load or store instruction is
7341   // consecutive.
7342   if (auto *Ptr = getPointerOperand(Inst))
7343     return Legal->isConsecutivePtr(Ptr);
7344   return false;
7345 }
7346 
7347 void LoopVectorizationCostModel::collectValuesToIgnore() {
7348   // Ignore ephemeral values.
7349   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7350 
7351   // Ignore type-promoting instructions we identified during reduction
7352   // detection.
7353   for (auto &Reduction : *Legal->getReductionVars()) {
7354     RecurrenceDescriptor &RedDes = Reduction.second;
7355     SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7356     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7357   }
7358 }
7359 
7360 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
7361                                              bool IfPredicateInstr) {
7362   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
7363   // Holds vector parameters or scalars, in case of uniform vals.
7364   SmallVector<VectorParts, 4> Params;
7365 
7366   setDebugLocFromInst(Builder, Instr);
7367 
7368   // Does this instruction return a value ?
7369   bool IsVoidRetTy = Instr->getType()->isVoidTy();
7370 
7371   // Initialize a new scalar map entry.
7372   ScalarParts Entry(UF);
7373 
7374   VectorParts Cond;
7375   if (IfPredicateInstr)
7376     Cond = createBlockInMask(Instr->getParent());
7377 
7378   // For each vector unroll 'part':
7379   for (unsigned Part = 0; Part < UF; ++Part) {
7380     Entry[Part].resize(1);
7381     // For each scalar that we create:
7382 
7383     // Start an "if (pred) a[i] = ..." block.
7384     Value *Cmp = nullptr;
7385     if (IfPredicateInstr) {
7386       if (Cond[Part]->getType()->isVectorTy())
7387         Cond[Part] =
7388             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
7389       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
7390                                ConstantInt::get(Cond[Part]->getType(), 1));
7391     }
7392 
7393     Instruction *Cloned = Instr->clone();
7394     if (!IsVoidRetTy)
7395       Cloned->setName(Instr->getName() + ".cloned");
7396 
7397     // Replace the operands of the cloned instructions with their scalar
7398     // equivalents in the new loop.
7399     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
7400       auto *NewOp = getScalarValue(Instr->getOperand(op), Part, 0);
7401       Cloned->setOperand(op, NewOp);
7402     }
7403 
7404     // Place the cloned scalar in the new loop.
7405     Builder.Insert(Cloned);
7406 
7407     // Add the cloned scalar to the scalar map entry.
7408     Entry[Part][0] = Cloned;
7409 
7410     // If we just cloned a new assumption, add it the assumption cache.
7411     if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
7412       if (II->getIntrinsicID() == Intrinsic::assume)
7413         AC->registerAssumption(II);
7414 
7415     // End if-block.
7416     if (IfPredicateInstr)
7417       PredicatedInstructions.push_back(std::make_pair(Cloned, Cmp));
7418   }
7419   VectorLoopValueMap.initScalar(Instr, Entry);
7420 }
7421 
7422 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
7423   auto *SI = dyn_cast<StoreInst>(Instr);
7424   bool IfPredicateInstr = (SI && Legal->blockNeedsPredication(SI->getParent()));
7425 
7426   return scalarizeInstruction(Instr, IfPredicateInstr);
7427 }
7428 
7429 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
7430 
7431 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7432 
7433 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
7434                                         Instruction::BinaryOps BinOp) {
7435   // When unrolling and the VF is 1, we only need to add a simple scalar.
7436   Type *Ty = Val->getType();
7437   assert(!Ty->isVectorTy() && "Val must be a scalar");
7438 
7439   if (Ty->isFloatingPointTy()) {
7440     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
7441 
7442     // Floating point operations had to be 'fast' to enable the unrolling.
7443     Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
7444     return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
7445   }
7446   Constant *C = ConstantInt::get(Ty, StartIdx);
7447   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
7448 }
7449 
7450 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7451   SmallVector<Metadata *, 4> MDs;
7452   // Reserve first location for self reference to the LoopID metadata node.
7453   MDs.push_back(nullptr);
7454   bool IsUnrollMetadata = false;
7455   MDNode *LoopID = L->getLoopID();
7456   if (LoopID) {
7457     // First find existing loop unrolling disable metadata.
7458     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7459       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7460       if (MD) {
7461         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7462         IsUnrollMetadata =
7463             S && S->getString().startswith("llvm.loop.unroll.disable");
7464       }
7465       MDs.push_back(LoopID->getOperand(i));
7466     }
7467   }
7468 
7469   if (!IsUnrollMetadata) {
7470     // Add runtime unroll disable metadata.
7471     LLVMContext &Context = L->getHeader()->getContext();
7472     SmallVector<Metadata *, 1> DisableOperands;
7473     DisableOperands.push_back(
7474         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7475     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7476     MDs.push_back(DisableNode);
7477     MDNode *NewLoopID = MDNode::get(Context, MDs);
7478     // Set operand 0 to refer to the loop id itself.
7479     NewLoopID->replaceOperandWith(0, NewLoopID);
7480     L->setLoopID(NewLoopID);
7481   }
7482 }
7483 
7484 bool LoopVectorizePass::processLoop(Loop *L) {
7485   assert(L->empty() && "Only process inner loops.");
7486 
7487 #ifndef NDEBUG
7488   const std::string DebugLocStr = getDebugLocString(L);
7489 #endif /* NDEBUG */
7490 
7491   DEBUG(dbgs() << "\nLV: Checking a loop in \""
7492                << L->getHeader()->getParent()->getName() << "\" from "
7493                << DebugLocStr << "\n");
7494 
7495   LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
7496 
7497   DEBUG(dbgs() << "LV: Loop hints:"
7498                << " force="
7499                << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
7500                        ? "disabled"
7501                        : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
7502                               ? "enabled"
7503                               : "?"))
7504                << " width=" << Hints.getWidth()
7505                << " unroll=" << Hints.getInterleave() << "\n");
7506 
7507   // Function containing loop
7508   Function *F = L->getHeader()->getParent();
7509 
7510   // Looking at the diagnostic output is the only way to determine if a loop
7511   // was vectorized (other than looking at the IR or machine code), so it
7512   // is important to generate an optimization remark for each loop. Most of
7513   // these messages are generated as OptimizationRemarkAnalysis. Remarks
7514   // generated as OptimizationRemark and OptimizationRemarkMissed are
7515   // less verbose reporting vectorized loops and unvectorized loops that may
7516   // benefit from vectorization, respectively.
7517 
7518   if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
7519     DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
7520     return false;
7521   }
7522 
7523   // Check the loop for a trip count threshold:
7524   // do not vectorize loops with a tiny trip count.
7525   const unsigned MaxTC = SE->getSmallConstantMaxTripCount(L);
7526   if (MaxTC > 0u && MaxTC < TinyTripCountVectorThreshold) {
7527     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
7528                  << "This loop is not worth vectorizing.");
7529     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
7530       DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
7531     else {
7532       DEBUG(dbgs() << "\n");
7533       ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
7534                                      "NotBeneficial", L)
7535                 << "vectorization is not beneficial "
7536                    "and is not explicitly forced");
7537       return false;
7538     }
7539   }
7540 
7541   PredicatedScalarEvolution PSE(*SE, *L);
7542 
7543   // Check if it is legal to vectorize the loop.
7544   LoopVectorizationRequirements Requirements(*ORE);
7545   LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE,
7546                                 &Requirements, &Hints);
7547   if (!LVL.canVectorize()) {
7548     DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
7549     emitMissedWarning(F, L, Hints, ORE);
7550     return false;
7551   }
7552 
7553   // Use the cost model.
7554   LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
7555                                 &Hints);
7556   CM.collectValuesToIgnore();
7557 
7558   // Check the function attributes to find out if this function should be
7559   // optimized for size.
7560   bool OptForSize =
7561       Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
7562 
7563   // Compute the weighted frequency of this loop being executed and see if it
7564   // is less than 20% of the function entry baseline frequency. Note that we
7565   // always have a canonical loop here because we think we *can* vectorize.
7566   // FIXME: This is hidden behind a flag due to pervasive problems with
7567   // exactly what block frequency models.
7568   if (LoopVectorizeWithBlockFrequency) {
7569     BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
7570     if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
7571         LoopEntryFreq < ColdEntryFreq)
7572       OptForSize = true;
7573   }
7574 
7575   // Check the function attributes to see if implicit floats are allowed.
7576   // FIXME: This check doesn't seem possibly correct -- what if the loop is
7577   // an integer loop and the vector instructions selected are purely integer
7578   // vector instructions?
7579   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7580     DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
7581                     "attribute is used.\n");
7582     ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
7583                                    "NoImplicitFloat", L)
7584               << "loop not vectorized due to NoImplicitFloat attribute");
7585     emitMissedWarning(F, L, Hints, ORE);
7586     return false;
7587   }
7588 
7589   // Check if the target supports potentially unsafe FP vectorization.
7590   // FIXME: Add a check for the type of safety issue (denormal, signaling)
7591   // for the target we're vectorizing for, to make sure none of the
7592   // additional fp-math flags can help.
7593   if (Hints.isPotentiallyUnsafe() &&
7594       TTI->isFPVectorizationPotentiallyUnsafe()) {
7595     DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
7596     ORE->emit(
7597         createMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
7598         << "loop not vectorized due to unsafe FP support.");
7599     emitMissedWarning(F, L, Hints, ORE);
7600     return false;
7601   }
7602 
7603   // Select the optimal vectorization factor.
7604   const LoopVectorizationCostModel::VectorizationFactor VF =
7605       CM.selectVectorizationFactor(OptForSize);
7606 
7607   // Select the interleave count.
7608   unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
7609 
7610   // Get user interleave count.
7611   unsigned UserIC = Hints.getInterleave();
7612 
7613   // Identify the diagnostic messages that should be produced.
7614   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7615   bool VectorizeLoop = true, InterleaveLoop = true;
7616   if (Requirements.doesNotMeet(F, L, Hints)) {
7617     DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
7618                     "requirements.\n");
7619     emitMissedWarning(F, L, Hints, ORE);
7620     return false;
7621   }
7622 
7623   if (VF.Width == 1) {
7624     DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
7625     VecDiagMsg = std::make_pair(
7626         "VectorizationNotBeneficial",
7627         "the cost-model indicates that vectorization is not beneficial");
7628     VectorizeLoop = false;
7629   }
7630 
7631   if (IC == 1 && UserIC <= 1) {
7632     // Tell the user interleaving is not beneficial.
7633     DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
7634     IntDiagMsg = std::make_pair(
7635         "InterleavingNotBeneficial",
7636         "the cost-model indicates that interleaving is not beneficial");
7637     InterleaveLoop = false;
7638     if (UserIC == 1) {
7639       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
7640       IntDiagMsg.second +=
7641           " and is explicitly disabled or interleave count is set to 1";
7642     }
7643   } else if (IC > 1 && UserIC == 1) {
7644     // Tell the user interleaving is beneficial, but it explicitly disabled.
7645     DEBUG(dbgs()
7646           << "LV: Interleaving is beneficial but is explicitly disabled.");
7647     IntDiagMsg = std::make_pair(
7648         "InterleavingBeneficialButDisabled",
7649         "the cost-model indicates that interleaving is beneficial "
7650         "but is explicitly disabled or interleave count is set to 1");
7651     InterleaveLoop = false;
7652   }
7653 
7654   // Override IC if user provided an interleave count.
7655   IC = UserIC > 0 ? UserIC : IC;
7656 
7657   // Emit diagnostic messages, if any.
7658   const char *VAPassName = Hints.vectorizeAnalysisPassName();
7659   if (!VectorizeLoop && !InterleaveLoop) {
7660     // Do not vectorize or interleaving the loop.
7661     ORE->emit(OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
7662                                          L->getStartLoc(), L->getHeader())
7663               << VecDiagMsg.second);
7664     ORE->emit(OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
7665                                          L->getStartLoc(), L->getHeader())
7666               << IntDiagMsg.second);
7667     return false;
7668   } else if (!VectorizeLoop && InterleaveLoop) {
7669     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7670     ORE->emit(OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
7671                                          L->getStartLoc(), L->getHeader())
7672               << VecDiagMsg.second);
7673   } else if (VectorizeLoop && !InterleaveLoop) {
7674     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
7675                  << DebugLocStr << '\n');
7676     ORE->emit(OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
7677                                          L->getStartLoc(), L->getHeader())
7678               << IntDiagMsg.second);
7679   } else if (VectorizeLoop && InterleaveLoop) {
7680     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
7681                  << DebugLocStr << '\n');
7682     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7683   }
7684 
7685   using namespace ore;
7686   if (!VectorizeLoop) {
7687     assert(IC > 1 && "interleave count should not be 1 or 0");
7688     // If we decided that it is not legal to vectorize the loop, then
7689     // interleave it.
7690     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
7691                                &CM);
7692     Unroller.vectorize();
7693 
7694     ORE->emit(OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
7695                                  L->getHeader())
7696               << "interleaved loop (interleaved count: "
7697               << NV("InterleaveCount", IC) << ")");
7698   } else {
7699     // If we decided that it is *legal* to vectorize the loop, then do it.
7700     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
7701                            &LVL, &CM);
7702     LB.vectorize();
7703     ++LoopsVectorized;
7704 
7705     // Add metadata to disable runtime unrolling a scalar loop when there are
7706     // no runtime checks about strides and memory. A scalar loop that is
7707     // rarely used is not worth unrolling.
7708     if (!LB.areSafetyChecksAdded())
7709       AddRuntimeUnrollDisableMetaData(L);
7710 
7711     // Report the vectorization decision.
7712     ORE->emit(OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
7713                                  L->getHeader())
7714               << "vectorized loop (vectorization width: "
7715               << NV("VectorizationFactor", VF.Width)
7716               << ", interleaved count: " << NV("InterleaveCount", IC) << ")");
7717   }
7718 
7719   // Mark the loop as already vectorized to avoid vectorizing again.
7720   Hints.setAlreadyVectorized();
7721 
7722   DEBUG(verifyFunction(*L->getHeader()->getParent()));
7723   return true;
7724 }
7725 
7726 bool LoopVectorizePass::runImpl(
7727     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
7728     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
7729     DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
7730     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
7731     OptimizationRemarkEmitter &ORE_) {
7732 
7733   SE = &SE_;
7734   LI = &LI_;
7735   TTI = &TTI_;
7736   DT = &DT_;
7737   BFI = &BFI_;
7738   TLI = TLI_;
7739   AA = &AA_;
7740   AC = &AC_;
7741   GetLAA = &GetLAA_;
7742   DB = &DB_;
7743   ORE = &ORE_;
7744 
7745   // Compute some weights outside of the loop over the loops. Compute this
7746   // using a BranchProbability to re-use its scaling math.
7747   const BranchProbability ColdProb(1, 5); // 20%
7748   ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
7749 
7750   // Don't attempt if
7751   // 1. the target claims to have no vector registers, and
7752   // 2. interleaving won't help ILP.
7753   //
7754   // The second condition is necessary because, even if the target has no
7755   // vector registers, loop vectorization may still enable scalar
7756   // interleaving.
7757   if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
7758     return false;
7759 
7760   bool Changed = false;
7761 
7762   // The vectorizer requires loops to be in simplified form.
7763   // Since simplification may add new inner loops, it has to run before the
7764   // legality and profitability checks. This means running the loop vectorizer
7765   // will simplify all loops, regardless of whether anything end up being
7766   // vectorized.
7767   for (auto &L : *LI)
7768     Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
7769 
7770   // Build up a worklist of inner-loops to vectorize. This is necessary as
7771   // the act of vectorizing or partially unrolling a loop creates new loops
7772   // and can invalidate iterators across the loops.
7773   SmallVector<Loop *, 8> Worklist;
7774 
7775   for (Loop *L : *LI)
7776     addAcyclicInnerLoop(*L, Worklist);
7777 
7778   LoopsAnalyzed += Worklist.size();
7779 
7780   // Now walk the identified inner loops.
7781   while (!Worklist.empty()) {
7782     Loop *L = Worklist.pop_back_val();
7783 
7784     // For the inner loops we actually process, form LCSSA to simplify the
7785     // transform.
7786     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
7787 
7788     Changed |= processLoop(L);
7789   }
7790 
7791   // Process each loop nest in the function.
7792   return Changed;
7793 
7794 }
7795 
7796 
7797 PreservedAnalyses LoopVectorizePass::run(Function &F,
7798                                          FunctionAnalysisManager &AM) {
7799     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
7800     auto &LI = AM.getResult<LoopAnalysis>(F);
7801     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
7802     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
7803     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
7804     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
7805     auto &AA = AM.getResult<AAManager>(F);
7806     auto &AC = AM.getResult<AssumptionAnalysis>(F);
7807     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
7808     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
7809 
7810     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
7811     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
7812         [&](Loop &L) -> const LoopAccessInfo & {
7813       LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI};
7814       return LAM.getResult<LoopAccessAnalysis>(L, AR);
7815     };
7816     bool Changed =
7817         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
7818     if (!Changed)
7819       return PreservedAnalyses::all();
7820     PreservedAnalyses PA;
7821     PA.preserve<LoopAnalysis>();
7822     PA.preserve<DominatorTreeAnalysis>();
7823     PA.preserve<BasicAA>();
7824     PA.preserve<GlobalsAA>();
7825     return PA;
7826 }
7827