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