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