LLVM  6.0.0svn
LoopVectorize.cpp
Go to the documentation of this file.
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 
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"
64 #include "llvm/Analysis/LoopInfo.h"
66 #include "llvm/Analysis/LoopPass.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"
92 #include "llvm/Support/Debug.h"
94 #include "llvm/Transforms/Scalar.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.
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 
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 
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.
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 
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 
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 
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 
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 
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 
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 
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.
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.
192  "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
193  cl::desc("Max number of stores to be predicated behind an if."));
194 
196  "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
197  cl::desc("Count the induction variable only once when interleaving"));
198 
200  "enable-cond-stores-vec", cl::init(true), cl::Hidden,
201  cl::desc("Enable if predication of stores during vectorization."));
202 
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 
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 
214  "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
215  cl::desc("The maximum number of SCEV checks allowed."));
216 
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.
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 :
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)) {
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.
389 public:
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.
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.
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.
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.
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.
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.
630  /// Loop Info.
632  /// Dominator Tree.
634  /// Alias Analysis.
636  /// Target Library Info.
638  /// Target Transform Info.
640  /// Assumption Cache.
642  /// Interface to emit optimization remarks.
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
662 
663  // --- Vectorization state ---
664 
665  /// The vector-loop preheader.
667  /// The scalar-loop preheader.
669  /// Middle Block between the vector and the scalar.
671  /// The ExitBlock of the scalar loop.
673  /// The vector loop body.
675  /// The scalar loop body.
677  /// A list of all bypass blocks. The first block is the entry of the loop.
679 
680  /// The new Induction variable which was added to the new block.
682  /// The induction variable of the old basic block.
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.
690 
691  /// Store instructions that were predicated.
694  BlockMaskCacheTy BlockMaskCache;
695  /// Trip count of the original loop.
697  /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
699 
700  /// The legality analysis.
701  LoopVectorizationLegality *Legal;
702 
703  /// The profitablity analysis.
704  LoopVectorizationCostModel *Cost;
705 
706  // Record whether runtime checks are added.
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.
712 
714 };
715 
717 public:
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.
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 
756  if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
757  const DILocation *DIL = Inst->getDebugLoc();
758  if (DIL && Inst->getFunction()->isDebugInfoForProfiling())
760  else
762  } else
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 
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 
792  Instruction *From) {
793  propagateMetadata(To, From);
794  addNewMetadata(To, From);
795 }
796 
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;
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() {
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).
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.
1000 
1001  /// Holds dependences among the memory accesses in the loop. It maps a source
1002  /// access to a set of dependent sink accesses.
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(
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,
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.
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([&]() {
1235  return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
1236  "AllDisabled", L->getStartLoc(),
1237  L->getHeader())
1238  << "loop not vectorized: vectorization and interleaving are "
1239  "explicitly disabled, or the loop has already been "
1240  "vectorized";
1241  });
1242  return false;
1243  }
1244 
1245  return true;
1246  }
1247 
1248  /// Dumps all the hint information.
1249  void emitRemarkWithHints() const {
1250  using namespace ore;
1251  if (Force.Value == LoopVectorizeHints::FK_Disabled)
1252  ORE.emit(OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
1253  TheLoop->getStartLoc(),
1254  TheLoop->getHeader())
1255  << "loop not vectorized: vectorization is explicitly disabled");
1256  else {
1257  OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
1258  TheLoop->getStartLoc(), TheLoop->getHeader());
1259  R << "loop not vectorized";
1260  if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1261  R << " (Force=" << NV("Force", true);
1262  if (Width.Value != 0)
1263  R << ", Vector Width=" << NV("VectorWidth", Width.Value);
1264  if (Interleave.Value != 0)
1265  R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
1266  R << ")";
1267  }
1268  ORE.emit(R);
1269  }
1270  }
1271 
1272  unsigned getWidth() const { return Width.Value; }
1273  unsigned getInterleave() const { return Interleave.Value; }
1274  unsigned getIsVectorized() const { return IsVectorized.Value; }
1275  enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1276 
1277  /// \brief If hints are provided that force vectorization, use the AlwaysPrint
1278  /// pass name to force the frontend to print the diagnostic.
1279  const char *vectorizeAnalysisPassName() const {
1280  if (getWidth() == 1)
1281  return LV_NAME;
1282  if (getForce() == LoopVectorizeHints::FK_Disabled)
1283  return LV_NAME;
1284  if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1285  return LV_NAME;
1287  }
1288 
1289  bool allowReordering() const {
1290  // When enabling loop hints are provided we allow the vectorizer to change
1291  // the order of operations that is given by the scalar loop. This is not
1292  // enabled by default because can be unsafe or inefficient. For example,
1293  // reordering floating-point operations will change the way round-off
1294  // error accumulates in the loop.
1295  return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1296  }
1297 
1298  bool isPotentiallyUnsafe() const {
1299  // Avoid FP vectorization if the target is unsure about proper support.
1300  // This may be related to the SIMD unit in the target not handling
1301  // IEEE 754 FP ops properly, or bad single-to-double promotions.
1302  // Otherwise, a sequence of vectorized loops, even without reduction,
1303  // could lead to different end results on the destination vectors.
1304  return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1305  }
1306 
1307  void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
1308 
1309 private:
1310  /// Find hints specified in the loop metadata and update local values.
1311  void getHintsFromMetadata() {
1312  MDNode *LoopID = TheLoop->getLoopID();
1313  if (!LoopID)
1314  return;
1315 
1316  // First operand should refer to the loop id itself.
1317  assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1318  assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1319 
1320  for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1321  const MDString *S = nullptr;
1323 
1324  // The expected hint is either a MDString or a MDNode with the first
1325  // operand a MDString.
1326  if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1327  if (!MD || MD->getNumOperands() == 0)
1328  continue;
1329  S = dyn_cast<MDString>(MD->getOperand(0));
1330  for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1331  Args.push_back(MD->getOperand(i));
1332  } else {
1333  S = dyn_cast<MDString>(LoopID->getOperand(i));
1334  assert(Args.size() == 0 && "too many arguments for MDString");
1335  }
1336 
1337  if (!S)
1338  continue;
1339 
1340  // Check if the hint starts with the loop metadata prefix.
1341  StringRef Name = S->getString();
1342  if (Args.size() == 1)
1343  setHint(Name, Args[0]);
1344  }
1345  }
1346 
1347  /// Checks string hint with one operand and set value if valid.
1348  void setHint(StringRef Name, Metadata *Arg) {
1349  if (!Name.startswith(Prefix()))
1350  return;
1351  Name = Name.substr(Prefix().size(), StringRef::npos);
1352 
1353  const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1354  if (!C)
1355  return;
1356  unsigned Val = C->getZExtValue();
1357 
1358  Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
1359  for (auto H : Hints) {
1360  if (Name == H->Name) {
1361  if (H->validate(Val))
1362  H->Value = Val;
1363  else
1364  DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1365  break;
1366  }
1367  }
1368  }
1369 
1370  /// Create a new hint from name / value pair.
1371  MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1372  LLVMContext &Context = TheLoop->getHeader()->getContext();
1373  Metadata *MDs[] = {MDString::get(Context, Name),
1375  ConstantInt::get(Type::getInt32Ty(Context), V))};
1376  return MDNode::get(Context, MDs);
1377  }
1378 
1379  /// Matches metadata with hint name.
1380  bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1381  MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
1382  if (!Name)
1383  return false;
1384 
1385  for (auto H : HintTypes)
1386  if (Name->getString().endswith(H.Name))
1387  return true;
1388  return false;
1389  }
1390 
1391  /// Sets current hints into loop metadata, keeping other values intact.
1392  void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1393  if (HintTypes.size() == 0)
1394  return;
1395 
1396  // Reserve the first element to LoopID (see below).
1398  // If the loop already has metadata, then ignore the existing operands.
1399  MDNode *LoopID = TheLoop->getLoopID();
1400  if (LoopID) {
1401  for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1402  MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1403  // If node in update list, ignore old value.
1404  if (!matchesHintMetadataName(Node, HintTypes))
1405  MDs.push_back(Node);
1406  }
1407  }
1408 
1409  // Now, add the missing hints.
1410  for (auto H : HintTypes)
1411  MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1412 
1413  // Replace current metadata node with new one.
1414  LLVMContext &Context = TheLoop->getHeader()->getContext();
1415  MDNode *NewLoopID = MDNode::get(Context, MDs);
1416  // Set operand 0 to refer to the loop id itself.
1417  NewLoopID->replaceOperandWith(0, NewLoopID);
1418 
1419  TheLoop->setLoopID(NewLoopID);
1420  }
1421 
1422  /// The loop these hints belong to.
1423  const Loop *TheLoop;
1424 
1425  /// Interface to emit optimization remarks.
1427 };
1428 
1429 static void emitMissedWarning(Function *F, Loop *L,
1430  const LoopVectorizeHints &LH,
1432  LH.emitRemarkWithHints();
1433 
1434  if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1435  if (LH.getWidth() != 1)
1437  DEBUG_TYPE, "FailedRequestedVectorization",
1438  L->getStartLoc(), L->getHeader())
1439  << "loop not vectorized: "
1440  << "failed explicitly specified loop vectorization");
1441  else if (LH.getInterleave() != 1)
1443  DEBUG_TYPE, "FailedRequestedInterleaving", L->getStartLoc(),
1444  L->getHeader())
1445  << "loop not interleaved: "
1446  << "failed explicitly specified loop interleaving");
1447  }
1448 }
1449 
1450 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1451 /// to what vectorization factor.
1452 /// This class does not look at the profitability of vectorization, only the
1453 /// legality. This class has two main kinds of checks:
1454 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1455 /// will change the order of memory accesses in a way that will change the
1456 /// correctness of the program.
1457 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1458 /// checks for a number of different conditions, such as the availability of a
1459 /// single induction variable, that all types are supported and vectorize-able,
1460 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1461 /// This class is also used by InnerLoopVectorizer for identifying
1462 /// induction variable and the different reduction variables.
1463 class LoopVectorizationLegality {
1464 public:
1465  LoopVectorizationLegality(
1468  const TargetTransformInfo *TTI,
1469  std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
1470  OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R,
1471  LoopVectorizeHints *H)
1472  : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT),
1473  GetLAA(GetLAA), LAI(nullptr), ORE(ORE), InterleaveInfo(PSE, L, DT, LI),
1474  PrimaryInduction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
1475  Requirements(R), Hints(H) {}
1476 
1477  /// ReductionList contains the reduction descriptors for all
1478  /// of the reductions that were found in the loop.
1479  typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1480 
1481  /// InductionList saves induction variables and maps them to the
1482  /// induction descriptor.
1483  typedef MapVector<PHINode *, InductionDescriptor> InductionList;
1484 
1485  /// RecurrenceSet contains the phi nodes that are recurrences other than
1486  /// inductions and reductions.
1487  typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet;
1488 
1489  /// Returns true if it is legal to vectorize this loop.
1490  /// This does not mean that it is profitable to vectorize this
1491  /// loop, only that it is legal to do so.
1492  bool canVectorize();
1493 
1494  /// Returns the primary induction variable.
1495  PHINode *getPrimaryInduction() { return PrimaryInduction; }
1496 
1497  /// Returns the reduction variables found in the loop.
1498  ReductionList *getReductionVars() { return &Reductions; }
1499 
1500  /// Returns the induction variables found in the loop.
1501  InductionList *getInductionVars() { return &Inductions; }
1502 
1503  /// Return the first-order recurrences found in the loop.
1504  RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
1505 
1506  /// Return the set of instructions to sink to handle first-order recurrences.
1507  DenseMap<Instruction *, Instruction *> &getSinkAfter() { return SinkAfter; }
1508 
1509  /// Returns the widest induction type.
1510  Type *getWidestInductionType() { return WidestIndTy; }
1511 
1512  /// Returns True if V is an induction variable in this loop.
1513  bool isInductionVariable(const Value *V);
1514 
1515  /// Returns True if PN is a reduction variable in this loop.
1516  bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
1517 
1518  /// Returns True if Phi is a first-order recurrence in this loop.
1519  bool isFirstOrderRecurrence(const PHINode *Phi);
1520 
1521  /// Return true if the block BB needs to be predicated in order for the loop
1522  /// to be vectorized.
1523  bool blockNeedsPredication(BasicBlock *BB);
1524 
1525  /// Check if this pointer is consecutive when vectorizing. This happens
1526  /// when the last index of the GEP is the induction variable, or that the
1527  /// pointer itself is an induction variable.
1528  /// This check allows us to vectorize A[idx] into a wide load/store.
1529  /// Returns:
1530  /// 0 - Stride is unknown or non-consecutive.
1531  /// 1 - Address is consecutive.
1532  /// -1 - Address is consecutive, and decreasing.
1533  int isConsecutivePtr(Value *Ptr);
1534 
1535  /// Returns true if the value V is uniform within the loop.
1536  bool isUniform(Value *V);
1537 
1538  /// Returns the information that we collected about runtime memory check.
1539  const RuntimePointerChecking *getRuntimePointerChecking() const {
1540  return LAI->getRuntimePointerChecking();
1541  }
1542 
1543  const LoopAccessInfo *getLAI() const { return LAI; }
1544 
1545  /// \brief Check if \p Instr belongs to any interleaved access group.
1546  bool isAccessInterleaved(Instruction *Instr) {
1547  return InterleaveInfo.isInterleaved(Instr);
1548  }
1549 
1550  /// \brief Get the interleaved access group that \p Instr belongs to.
1551  const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1552  return InterleaveInfo.getInterleaveGroup(Instr);
1553  }
1554 
1555  /// \brief Returns true if an interleaved group requires a scalar iteration
1556  /// to handle accesses with gaps.
1557  bool requiresScalarEpilogue() const {
1558  return InterleaveInfo.requiresScalarEpilogue();
1559  }
1560 
1561  unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1562 
1563  uint64_t getMaxSafeRegisterWidth() const {
1564  return LAI->getDepChecker().getMaxSafeRegisterWidth();
1565  }
1566 
1567  bool hasStride(Value *V) { return LAI->hasStride(V); }
1568 
1569  /// Returns true if the target machine supports masked store operation
1570  /// for the given \p DataType and kind of access to \p Ptr.
1571  bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1572  return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1573  }
1574  /// Returns true if the target machine supports masked load operation
1575  /// for the given \p DataType and kind of access to \p Ptr.
1576  bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1577  return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1578  }
1579  /// Returns true if the target machine supports masked scatter operation
1580  /// for the given \p DataType.
1581  bool isLegalMaskedScatter(Type *DataType) {
1582  return TTI->isLegalMaskedScatter(DataType);
1583  }
1584  /// Returns true if the target machine supports masked gather operation
1585  /// for the given \p DataType.
1586  bool isLegalMaskedGather(Type *DataType) {
1587  return TTI->isLegalMaskedGather(DataType);
1588  }
1589  /// Returns true if the target machine can represent \p V as a masked gather
1590  /// or scatter operation.
1591  bool isLegalGatherOrScatter(Value *V) {
1592  auto *LI = dyn_cast<LoadInst>(V);
1593  auto *SI = dyn_cast<StoreInst>(V);
1594  if (!LI && !SI)
1595  return false;
1596  auto *Ptr = getPointerOperand(V);
1597  auto *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1598  return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1599  }
1600 
1601  /// Returns true if vector representation of the instruction \p I
1602  /// requires mask.
1603  bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
1604  unsigned getNumStores() const { return LAI->getNumStores(); }
1605  unsigned getNumLoads() const { return LAI->getNumLoads(); }
1606  unsigned getNumPredStores() const { return NumPredStores; }
1607 
1608  /// Returns true if \p I is an instruction that will be scalarized with
1609  /// predication. Such instructions include conditional stores and
1610  /// instructions that may divide by zero.
1611  bool isScalarWithPredication(Instruction *I);
1612 
1613  /// Returns true if \p I is a memory instruction with consecutive memory
1614  /// access that can be widened.
1615  bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
1616 
1617  // Returns true if the NoNaN attribute is set on the function.
1618  bool hasFunNoNaNAttr() const { return HasFunNoNaNAttr; }
1619 
1620 private:
1621  /// Check if a single basic block loop is vectorizable.
1622  /// At this point we know that this is a loop with a constant trip count
1623  /// and we only need to check individual instructions.
1624  bool canVectorizeInstrs();
1625 
1626  /// When we vectorize loops we may change the order in which
1627  /// we read and write from memory. This method checks if it is
1628  /// legal to vectorize the code, considering only memory constrains.
1629  /// Returns true if the loop is vectorizable
1630  bool canVectorizeMemory();
1631 
1632  /// Return true if we can vectorize this loop using the IF-conversion
1633  /// transformation.
1634  bool canVectorizeWithIfConvert();
1635 
1636  /// Return true if all of the instructions in the block can be speculatively
1637  /// executed. \p SafePtrs is a list of addresses that are known to be legal
1638  /// and we know that we can read from them without segfault.
1639  bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1640 
1641  /// Updates the vectorization state by adding \p Phi to the inductions list.
1642  /// This can set \p Phi as the main induction of the loop if \p Phi is a
1643  /// better choice for the main induction than the existing one.
1644  void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
1645  SmallPtrSetImpl<Value *> &AllowedExit);
1646 
1647  /// Create an analysis remark that explains why vectorization failed
1648  ///
1649  /// \p RemarkName is the identifier for the remark. If \p I is passed it is
1650  /// an instruction that prevents vectorization. Otherwise the loop is used
1651  /// for the location of the remark. \return the remark object that can be
1652  /// streamed to.
1654  createMissedAnalysis(StringRef RemarkName, Instruction *I = nullptr) const {
1655  return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1656  RemarkName, TheLoop, I);
1657  }
1658 
1659  /// \brief If an access has a symbolic strides, this maps the pointer value to
1660  /// the stride symbol.
1661  const ValueToValueMap *getSymbolicStrides() {
1662  // FIXME: Currently, the set of symbolic strides is sometimes queried before
1663  // it's collected. This happens from canVectorizeWithIfConvert, when the
1664  // pointer is checked to reference consecutive elements suitable for a
1665  // masked access.
1666  return LAI ? &LAI->getSymbolicStrides() : nullptr;
1667  }
1668 
1669  unsigned NumPredStores;
1670 
1671  /// The loop that we evaluate.
1672  Loop *TheLoop;
1673  /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
1674  /// Applies dynamic knowledge to simplify SCEV expressions in the context
1675  /// of existing SCEV assumptions. The analysis will also add a minimal set
1676  /// of new predicates if this is required to enable vectorization and
1677  /// unrolling.
1679  /// Target Library Info.
1680  TargetLibraryInfo *TLI;
1681  /// Target Transform Info
1682  const TargetTransformInfo *TTI;
1683  /// Dominator Tree.
1684  DominatorTree *DT;
1685  // LoopAccess analysis.
1686  std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1687  // And the loop-accesses info corresponding to this loop. This pointer is
1688  // null until canVectorizeMemory sets it up.
1689  const LoopAccessInfo *LAI;
1690  /// Interface to emit optimization remarks.
1692 
1693  /// The interleave access information contains groups of interleaved accesses
1694  /// with the same stride and close to each other.
1695  InterleavedAccessInfo InterleaveInfo;
1696 
1697  // --- vectorization state --- //
1698 
1699  /// Holds the primary induction variable. This is the counter of the
1700  /// loop.
1701  PHINode *PrimaryInduction;
1702  /// Holds the reduction variables.
1703  ReductionList Reductions;
1704  /// Holds all of the induction variables that we found in the loop.
1705  /// Notice that inductions don't need to start at zero and that induction
1706  /// variables can be pointers.
1707  InductionList Inductions;
1708  /// Holds the phi nodes that are first-order recurrences.
1709  RecurrenceSet FirstOrderRecurrences;
1710  /// Holds instructions that need to sink past other instructions to handle
1711  /// first-order recurrences.
1713  /// Holds the widest induction type encountered.
1714  Type *WidestIndTy;
1715 
1716  /// Allowed outside users. This holds the induction and reduction
1717  /// vars which can be accessed from outside the loop.
1718  SmallPtrSet<Value *, 4> AllowedExit;
1719 
1720  /// Can we assume the absence of NaNs.
1721  bool HasFunNoNaNAttr;
1722 
1723  /// Vectorization requirements that will go through late-evaluation.
1724  LoopVectorizationRequirements *Requirements;
1725 
1726  /// Used to emit an analysis of any legality issues.
1727  LoopVectorizeHints *Hints;
1728 
1729  /// While vectorizing these instructions we have to generate a
1730  /// call to the appropriate masked intrinsic
1732 };
1733 
1734 /// LoopVectorizationCostModel - estimates the expected speedups due to
1735 /// vectorization.
1736 /// In many cases vectorization is not profitable. This can happen because of
1737 /// a number of reasons. In this class we mainly attempt to predict the
1738 /// expected speedup/slowdowns due to the supported instruction set. We use the
1739 /// TargetTransformInfo to query the different backends for the cost of
1740 /// different operations.
1741 class LoopVectorizationCostModel {
1742 public:
1743  LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1744  LoopInfo *LI, LoopVectorizationLegality *Legal,
1745  const TargetTransformInfo &TTI,
1746  const TargetLibraryInfo *TLI, DemandedBits *DB,
1747  AssumptionCache *AC,
1748  OptimizationRemarkEmitter *ORE, const Function *F,
1749  const LoopVectorizeHints *Hints)
1750  : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1751  AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {}
1752 
1753  /// \return An upper bound for the vectorization factor, or None if
1754  /// vectorization should be avoided up front.
1755  Optional<unsigned> computeMaxVF(bool OptForSize);
1756 
1757  /// Information about vectorization costs
1758  struct VectorizationFactor {
1759  unsigned Width; // Vector width with best cost
1760  unsigned Cost; // Cost of the loop with that width
1761  };
1762  /// \return The most profitable vectorization factor and the cost of that VF.
1763  /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1764  /// then this vectorization factor will be selected if vectorization is
1765  /// possible.
1766  VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
1767 
1768  /// Setup cost-based decisions for user vectorization factor.
1769  void selectUserVectorizationFactor(unsigned UserVF) {
1770  collectUniformsAndScalars(UserVF);
1771  collectInstsToScalarize(UserVF);
1772  }
1773 
1774  /// \return The size (in bits) of the smallest and widest types in the code
1775  /// that needs to be vectorized. We ignore values that remain scalar such as
1776  /// 64 bit loop indices.
1777  std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1778 
1779  /// \return The desired interleave count.
1780  /// If interleave count has been specified by metadata it will be returned.
1781  /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1782  /// are the selected vectorization factor and the cost of the selected VF.
1783  unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1784  unsigned LoopCost);
1785 
1786  /// Memory access instruction may be vectorized in more than one way.
1787  /// Form of instruction after vectorization depends on cost.
1788  /// This function takes cost-based decisions for Load/Store instructions
1789  /// and collects them in a map. This decisions map is used for building
1790  /// the lists of loop-uniform and loop-scalar instructions.
1791  /// The calculated cost is saved with widening decision in order to
1792  /// avoid redundant calculations.
1793  void setCostBasedWideningDecision(unsigned VF);
1794 
1795  /// \brief A struct that represents some properties of the register usage
1796  /// of a loop.
1797  struct RegisterUsage {
1798  /// Holds the number of loop invariant values that are used in the loop.
1799  unsigned LoopInvariantRegs;
1800  /// Holds the maximum number of concurrent live intervals in the loop.
1801  unsigned MaxLocalUsers;
1802  /// Holds the number of instructions in the loop.
1803  unsigned NumInstructions;
1804  };
1805 
1806  /// \return Returns information about the register usages of the loop for the
1807  /// given vectorization factors.
1808  SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1809 
1810  /// Collect values we want to ignore in the cost model.
1811  void collectValuesToIgnore();
1812 
1813  /// \returns The smallest bitwidth each instruction can be represented with.
1814  /// The vector equivalents of these instructions should be truncated to this
1815  /// type.
1816  const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1817  return MinBWs;
1818  }
1819 
1820  /// \returns True if it is more profitable to scalarize instruction \p I for
1821  /// vectorization factor \p VF.
1822  bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
1823  assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.");
1824  auto Scalars = InstsToScalarize.find(VF);
1825  assert(Scalars != InstsToScalarize.end() &&
1826  "VF not yet analyzed for scalarization profitability");
1827  return Scalars->second.count(I);
1828  }
1829 
1830  /// Returns true if \p I is known to be uniform after vectorization.
1831  bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
1832  if (VF == 1)
1833  return true;
1834  assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity");
1835  auto UniformsPerVF = Uniforms.find(VF);
1836  return UniformsPerVF->second.count(I);
1837  }
1838 
1839  /// Returns true if \p I is known to be scalar after vectorization.
1840  bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
1841  if (VF == 1)
1842  return true;
1843  assert(Scalars.count(VF) && "Scalar values are not calculated for VF");
1844  auto ScalarsPerVF = Scalars.find(VF);
1845  return ScalarsPerVF->second.count(I);
1846  }
1847 
1848  /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1849  /// for vectorization factor \p VF.
1850  bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
1851  return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1852  !isScalarAfterVectorization(I, VF);
1853  }
1854 
1855  /// Decision that was taken during cost calculation for memory instruction.
1856  enum InstWidening {
1857  CM_Unknown,
1858  CM_Widen,
1859  CM_Interleave,
1860  CM_GatherScatter,
1861  CM_Scalarize
1862  };
1863 
1864  /// Save vectorization decision \p W and \p Cost taken by the cost model for
1865  /// instruction \p I and vector width \p VF.
1866  void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
1867  unsigned Cost) {
1868  assert(VF >= 2 && "Expected VF >=2");
1869  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1870  }
1871 
1872  /// Save vectorization decision \p W and \p Cost taken by the cost model for
1873  /// interleaving group \p Grp and vector width \p VF.
1874  void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
1875  InstWidening W, unsigned Cost) {
1876  assert(VF >= 2 && "Expected VF >=2");
1877  /// Broadcast this decicion to all instructions inside the group.
1878  /// But the cost will be assigned to one instruction only.
1879  for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1880  if (auto *I = Grp->getMember(i)) {
1881  if (Grp->getInsertPos() == I)
1882  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1883  else
1884  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1885  }
1886  }
1887  }
1888 
1889  /// Return the cost model decision for the given instruction \p I and vector
1890  /// width \p VF. Return CM_Unknown if this instruction did not pass
1891  /// through the cost modeling.
1892  InstWidening getWideningDecision(Instruction *I, unsigned VF) {
1893  assert(VF >= 2 && "Expected VF >=2");
1894  std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1895  auto Itr = WideningDecisions.find(InstOnVF);
1896  if (Itr == WideningDecisions.end())
1897  return CM_Unknown;
1898  return Itr->second.first;
1899  }
1900 
1901  /// Return the vectorization cost for the given instruction \p I and vector
1902  /// width \p VF.
1903  unsigned getWideningCost(Instruction *I, unsigned VF) {
1904  assert(VF >= 2 && "Expected VF >=2");
1905  std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1906  assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated");
1907  return WideningDecisions[InstOnVF].second;
1908  }
1909 
1910  /// Return True if instruction \p I is an optimizable truncate whose operand
1911  /// is an induction variable. Such a truncate will be removed by adding a new
1912  /// induction variable with the destination type.
1913  bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
1914 
1915  // If the instruction is not a truncate, return false.
1916  auto *Trunc = dyn_cast<TruncInst>(I);
1917  if (!Trunc)
1918  return false;
1919 
1920  // Get the source and destination types of the truncate.
1921  Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1922  Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1923 
1924  // If the truncate is free for the given types, return false. Replacing a
1925  // free truncate with an induction variable would add an induction variable
1926  // update instruction to each iteration of the loop. We exclude from this
1927  // check the primary induction variable since it will need an update
1928  // instruction regardless.
1929  Value *Op = Trunc->getOperand(0);
1930  if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1931  return false;
1932 
1933  // If the truncated value is not an induction variable, return false.
1934  return Legal->isInductionVariable(Op);
1935  }
1936 
1937  /// Collects the instructions to scalarize for each predicated instruction in
1938  /// the loop.
1939  void collectInstsToScalarize(unsigned VF);
1940 
1941  /// Collect Uniform and Scalar values for the given \p VF.
1942  /// The sets depend on CM decision for Load/Store instructions
1943  /// that may be vectorized as interleave, gather-scatter or scalarized.
1944  void collectUniformsAndScalars(unsigned VF) {
1945  // Do the analysis once.
1946  if (VF == 1 || Uniforms.count(VF))
1947  return;
1948  setCostBasedWideningDecision(VF);
1949  collectLoopUniforms(VF);
1950  collectLoopScalars(VF);
1951  }
1952 
1953 private:
1954  /// \return An upper bound for the vectorization factor, larger than zero.
1955  /// One is returned if vectorization should best be avoided due to cost.
1956  unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
1957 
1958  /// The vectorization cost is a combination of the cost itself and a boolean
1959  /// indicating whether any of the contributing operations will actually
1960  /// operate on
1961  /// vector values after type legalization in the backend. If this latter value
1962  /// is
1963  /// false, then all operations will be scalarized (i.e. no vectorization has
1964  /// actually taken place).
1965  typedef std::pair<unsigned, bool> VectorizationCostTy;
1966 
1967  /// Returns the expected execution cost. The unit of the cost does
1968  /// not matter because we use the 'cost' units to compare different
1969  /// vector widths. The cost that is returned is *not* normalized by
1970  /// the factor width.
1971  VectorizationCostTy expectedCost(unsigned VF);
1972 
1973  /// Returns the execution time cost of an instruction for a given vector
1974  /// width. Vector width of one means scalar.
1975  VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
1976 
1977  /// The cost-computation logic from getInstructionCost which provides
1978  /// the vector type as an output parameter.
1979  unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
1980 
1981  /// Calculate vectorization cost of memory instruction \p I.
1982  unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
1983 
1984  /// The cost computation for scalarized memory instruction.
1985  unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
1986 
1987  /// The cost computation for interleaving group of memory instructions.
1988  unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
1989 
1990  /// The cost computation for Gather/Scatter instruction.
1991  unsigned getGatherScatterCost(Instruction *I, unsigned VF);
1992 
1993  /// The cost computation for widening instruction \p I with consecutive
1994  /// memory access.
1995  unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
1996 
1997  /// The cost calculation for Load instruction \p I with uniform pointer -
1998  /// scalar load + broadcast.
1999  unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
2000 
2001  /// Returns whether the instruction is a load or store and will be a emitted
2002  /// as a vector operation.
2003  bool isConsecutiveLoadOrStore(Instruction *I);
2004 
2005  /// Create an analysis remark that explains why vectorization failed
2006  ///
2007  /// \p RemarkName is the identifier for the remark. \return the remark object
2008  /// that can be streamed to.
2010  return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
2011  RemarkName, TheLoop);
2012  }
2013 
2014  /// Map of scalar integer values to the smallest bitwidth they can be legally
2015  /// represented as. The vector equivalents of these values should be truncated
2016  /// to this type.
2018 
2019  /// A type representing the costs for instructions if they were to be
2020  /// scalarized rather than vectorized. The entries are Instruction-Cost
2021  /// pairs.
2022  typedef DenseMap<Instruction *, unsigned> ScalarCostsTy;
2023 
2024  /// A set containing all BasicBlocks that are known to present after
2025  /// vectorization as a predicated block.
2026  SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
2027 
2028  /// A map holding scalar costs for different vectorization factors. The
2029  /// presence of a cost for an instruction in the mapping indicates that the
2030  /// instruction will be scalarized when vectorizing with the associated
2031  /// vectorization factor. The entries are VF-ScalarCostTy pairs.
2032  DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
2033 
2034  /// Holds the instructions known to be uniform after vectorization.
2035  /// The data is collected per VF.
2037 
2038  /// Holds the instructions known to be scalar after vectorization.
2039  /// The data is collected per VF.
2041 
2042  /// Holds the instructions (address computations) that are forced to be
2043  /// scalarized.
2045 
2046  /// Returns the expected difference in cost from scalarizing the expression
2047  /// feeding a predicated instruction \p PredInst. The instructions to
2048  /// scalarize and their scalar costs are collected in \p ScalarCosts. A
2049  /// non-negative return value implies the expression will be scalarized.
2050  /// Currently, only single-use chains are considered for scalarization.
2051  int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
2052  unsigned VF);
2053 
2054  /// Collect the instructions that are uniform after vectorization. An
2055  /// instruction is uniform if we represent it with a single scalar value in
2056  /// the vectorized loop corresponding to each vector iteration. Examples of
2057  /// uniform instructions include pointer operands of consecutive or
2058  /// interleaved memory accesses. Note that although uniformity implies an
2059  /// instruction will be scalar, the reverse is not true. In general, a
2060  /// scalarized instruction will be represented by VF scalar values in the
2061  /// vectorized loop, each corresponding to an iteration of the original
2062  /// scalar loop.
2063  void collectLoopUniforms(unsigned VF);
2064 
2065  /// Collect the instructions that are scalar after vectorization. An
2066  /// instruction is scalar if it is known to be uniform or will be scalarized
2067  /// during vectorization. Non-uniform scalarized instructions will be
2068  /// represented by VF values in the vectorized loop, each corresponding to an
2069  /// iteration of the original scalar loop.
2070  void collectLoopScalars(unsigned VF);
2071 
2072  /// Keeps cost model vectorization decision and cost for instructions.
2073  /// Right now it is used for memory instructions only.
2075  std::pair<InstWidening, unsigned>>
2076  DecisionList;
2077 
2078  DecisionList WideningDecisions;
2079 
2080 public:
2081  /// The loop that we evaluate.
2082  Loop *TheLoop;
2083  /// Predicated scalar evolution analysis.
2085  /// Loop Info analysis.
2086  LoopInfo *LI;
2087  /// Vectorization legality.
2088  LoopVectorizationLegality *Legal;
2089  /// Vector target information.
2090  const TargetTransformInfo &TTI;
2091  /// Target Library Info.
2092  const TargetLibraryInfo *TLI;
2093  /// Demanded bits analysis.
2094  DemandedBits *DB;
2095  /// Assumption cache.
2096  AssumptionCache *AC;
2097  /// Interface to emit optimization remarks.
2099 
2100  const Function *TheFunction;
2101  /// Loop Vectorize Hint.
2102  const LoopVectorizeHints *Hints;
2103  /// Values to ignore in the cost model.
2104  SmallPtrSet<const Value *, 16> ValuesToIgnore;
2105  /// Values to ignore in the cost model when VF > 1.
2106  SmallPtrSet<const Value *, 16> VecValuesToIgnore;
2107 };
2108 
2109 } // end anonymous namespace
2110 
2111 namespace llvm {
2112 /// InnerLoopVectorizer vectorizes loops which contain only one basic
2113 /// LoopVectorizationPlanner - drives the vectorization process after having
2114 /// passed Legality checks.
2115 /// The planner builds and optimizes the Vectorization Plans which record the
2116 /// decisions how to vectorize the given loop. In particular, represent the
2117 /// control-flow of the vectorized version, the replication of instructions that
2118 /// are to be scalarized, and interleave access groups.
2120  /// The loop that we evaluate.
2121  Loop *OrigLoop;
2122 
2123  /// Loop Info analysis.
2124  LoopInfo *LI;
2125 
2126  /// Target Library Info.
2127  const TargetLibraryInfo *TLI;
2128 
2129  /// Target Transform Info.
2130  const TargetTransformInfo *TTI;
2131 
2132  /// The legality analysis.
2133  LoopVectorizationLegality *Legal;
2134 
2135  /// The profitablity analysis.
2136  LoopVectorizationCostModel &CM;
2137 
2138  SmallVector<VPlan *, 4> VPlans;
2139 
2140  unsigned BestVF;
2141  unsigned BestUF;
2142 
2143 public:
2145  const TargetTransformInfo *TTI,
2146  LoopVectorizationLegality *Legal,
2147  LoopVectorizationCostModel &CM)
2148  : OrigLoop(L), LI(LI), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM),
2149  BestVF(0), BestUF(0) {}
2150 
2152  while (!VPlans.empty()) {
2153  VPlan *Plan = VPlans.back();
2154  VPlans.pop_back();
2155  delete Plan;
2156  }
2157  }
2158 
2159  /// Plan how to best vectorize, return the best VF and its cost.
2161  unsigned UserVF);
2162 
2163  /// Finalize the best decision and dispose of all other VPlans.
2164  void setBestPlan(unsigned VF, unsigned UF);
2165 
2166  /// Generate the IR code for the body of the vectorized loop according to the
2167  /// best selected VPlan.
2168  void executePlan(InnerLoopVectorizer &LB, DominatorTree *DT);
2169 
2171  for (VPlan *Plan : VPlans)
2172  O << *Plan;
2173  }
2174 
2175 protected:
2176  /// Collect the instructions from the original loop that would be trivially
2177  /// dead in the vectorized loop if generated.
2178  void collectTriviallyDeadInstructions(
2179  SmallPtrSetImpl<Instruction *> &DeadInstructions);
2180 
2181  /// A range of powers-of-2 vectorization factors with fixed start and
2182  /// adjustable end. The range includes start and excludes end, e.g.,:
2183  /// [1, 9) = {1, 2, 4, 8}
2184  struct VFRange {
2185  const unsigned Start; // A power of 2.
2186  unsigned End; // Need not be a power of 2. If End <= Start range is empty.
2187  };
2188 
2189  /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
2190  /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
2191  /// returned value holds for the entire \p Range.
2192  bool getDecisionAndClampRange(const std::function<bool(unsigned)> &Predicate,
2193  VFRange &Range);
2194 
2195  /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
2196  /// according to the information gathered by Legal when it checked if it is
2197  /// legal to vectorize the loop.
2198  void buildVPlans(unsigned MinVF, unsigned MaxVF);
2199 
2200 private:
2201  /// Check if \I belongs to an Interleave Group within the given VF \p Range,
2202  /// \return true in the first returned value if so and false otherwise.
2203  /// Build a new VPInterleaveGroup Recipe if \I is the primary member of an IG
2204  /// for \p Range.Start, and provide it as the second returned value.
2205  /// Note that if \I is an adjunct member of an IG for \p Range.Start, the
2206  /// \return value is <true, nullptr>, as it is handled by another recipe.
2207  /// \p Range.End may be decreased to ensure same decision from \p Range.Start
2208  /// to \p Range.End.
2209  VPInterleaveRecipe *tryToInterleaveMemory(Instruction *I, VFRange &Range);
2210 
2211  /// Check if an induction recipe should be constructed for \I within the given
2212  /// VF \p Range. If so build and return it. If not, return null. \p Range.End
2213  /// may be decreased to ensure same decision from \p Range.Start to
2214  /// \p Range.End.
2215  VPWidenIntOrFpInductionRecipe *tryToOptimizeInduction(Instruction *I,
2216  VFRange &Range);
2217 
2218  /// Check if \I can be widened within the given VF \p Range. If \I can be
2219  /// widened for Range.Start, extend \p LastWidenRecipe to include \p I if
2220  /// possible or else build a new VPWidenRecipe for it, and return the
2221  /// VPWidenRecipe that includes \p I. If \p I cannot be widened for
2222  /// Range.Start \return null. Range.End may be decreased to ensure same
2223  /// decision from \p Range.Start to \p Range.End.
2224  VPWidenRecipe *tryToWiden(Instruction *I, VPWidenRecipe *LastWidenRecipe,
2225  VFRange &Range);
2226 
2227  /// Build a VPReplicationRecipe for \p I and enclose it within a Region if it
2228  /// is predicated. \return \p VPBB augmented with this new recipe if \p I is
2229  /// not predicated, otherwise \return a new VPBasicBlock that succeeds the new
2230  /// Region. Update the packing decision of predicated instructions if they
2231  /// feed \p I. Range.End may be decreased to ensure same recipe behavior from
2232  /// \p Range.Start to \p Range.End.
2233  VPBasicBlock *handleReplication(
2234  Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
2236 
2237  /// Create a replicating region for instruction \p I that requires
2238  /// predication. \p PredRecipe is a VPReplicateRecipe holding \p I.
2239  VPRegionBlock *createReplicateRegion(Instruction *I,
2240  VPRecipeBase *PredRecipe);
2241 
2242  /// Build a VPlan according to the information gathered by Legal. \return a
2243  /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
2244  /// exclusive, possibly decreasing \p Range.End.
2245  VPlan *buildVPlan(VFRange &Range);
2246 };
2247 
2248 } // namespace llvm
2249 
2250 namespace {
2251 
2252 /// \brief This holds vectorization requirements that must be verified late in
2253 /// the process. The requirements are set by legalize and costmodel. Once
2254 /// vectorization has been determined to be possible and profitable the
2255 /// requirements can be verified by looking for metadata or compiler options.
2256 /// For example, some loops require FP commutativity which is only allowed if
2257 /// vectorization is explicitly specified or if the fast-math compiler option
2258 /// has been provided.
2259 /// Late evaluation of these requirements allows helpful diagnostics to be
2260 /// composed that tells the user what need to be done to vectorize the loop. For
2261 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
2262 /// evaluation should be used only when diagnostics can generated that can be
2263 /// followed by a non-expert user.
2264 class LoopVectorizationRequirements {
2265 public:
2266  LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE)
2267  : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr), ORE(ORE) {}
2268 
2269  void addUnsafeAlgebraInst(Instruction *I) {
2270  // First unsafe algebra instruction.
2271  if (!UnsafeAlgebraInst)
2272  UnsafeAlgebraInst = I;
2273  }
2274 
2275  void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
2276 
2277  bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
2278  const char *PassName = Hints.vectorizeAnalysisPassName();
2279  bool Failed = false;
2280  if (UnsafeAlgebraInst && !Hints.allowReordering()) {
2281  ORE.emit(
2282  OptimizationRemarkAnalysisFPCommute(PassName, "CantReorderFPOps",
2283  UnsafeAlgebraInst->getDebugLoc(),
2284  UnsafeAlgebraInst->getParent())
2285  << "loop not vectorized: cannot prove it is safe to reorder "
2286  "floating-point operations");
2287  Failed = true;
2288  }
2289 
2290  // Test if runtime memcheck thresholds are exceeded.
2291  bool PragmaThresholdReached =
2292  NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
2293  bool ThresholdReached =
2294  NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
2295  if ((ThresholdReached && !Hints.allowReordering()) ||
2296  PragmaThresholdReached) {
2297  ORE.emit(OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
2298  L->getStartLoc(),
2299  L->getHeader())
2300  << "loop not vectorized: cannot prove it is safe to reorder "
2301  "memory operations");
2302  DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
2303  Failed = true;
2304  }
2305 
2306  return Failed;
2307  }
2308 
2309 private:
2310  unsigned NumRuntimePointerChecks;
2311  Instruction *UnsafeAlgebraInst;
2312 
2313  /// Interface to emit optimization remarks.
2315 };
2316 
2317 static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
2318  if (L.empty()) {
2319  if (!hasCyclesInLoopBody(L))
2320  V.push_back(&L);
2321  return;
2322  }
2323  for (Loop *InnerL : L)
2324  addAcyclicInnerLoop(*InnerL, V);
2325 }
2326 
2327 /// The LoopVectorize Pass.
2328 struct LoopVectorize : public FunctionPass {
2329  /// Pass identification, replacement for typeid
2330  static char ID;
2331 
2332  explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
2333  : FunctionPass(ID) {
2334  Impl.DisableUnrolling = NoUnrolling;
2335  Impl.AlwaysVectorize = AlwaysVectorize;
2337  }
2338 
2339  LoopVectorizePass Impl;
2340 
2341  bool runOnFunction(Function &F) override {
2342  if (skipFunction(F))
2343  return false;
2344 
2345  auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2346  auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2347  auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2348  auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2349  auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2350  auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2351  auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2352  auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2353  auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2354  auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2355  auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2356  auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2357 
2358  std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2359  [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2360 
2361  return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2362  GetLAA, *ORE);
2363  }
2364 
2365  void getAnalysisUsage(AnalysisUsage &AU) const override {
2380  }
2381 };
2382 
2383 } // end anonymous namespace
2384 
2385 //===----------------------------------------------------------------------===//
2386 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2387 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2388 //===----------------------------------------------------------------------===//
2389 
2391  // We need to place the broadcast of invariant variables outside the loop.
2392  Instruction *Instr = dyn_cast<Instruction>(V);
2393  bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
2394  bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
2395 
2396  // Place the code for broadcasting invariant variables in the new preheader.
2397  IRBuilder<>::InsertPointGuard Guard(Builder);
2398  if (Invariant)
2399  Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2400 
2401  // Broadcast the scalar into all locations in the vector.
2402  Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2403 
2404  return Shuf;
2405 }
2406 
2408  const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
2409  Value *Start = II.getStartValue();
2410 
2411  // Construct the initial value of the vector IV in the vector loop preheader
2412  auto CurrIP = Builder.saveIP();
2413  Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2414  if (isa<TruncInst>(EntryVal)) {
2415  assert(Start->getType()->isIntegerTy() &&
2416  "Truncation requires an integer type");
2417  auto *TruncType = cast<IntegerType>(EntryVal->getType());
2418  Step = Builder.CreateTrunc(Step, TruncType);
2419  Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2420  }
2421  Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2422  Value *SteppedStart =
2423  getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2424 
2425  // We create vector phi nodes for both integer and floating-point induction
2426  // variables. Here, we determine the kind of arithmetic we will perform.
2427  Instruction::BinaryOps AddOp;
2428  Instruction::BinaryOps MulOp;
2429  if (Step->getType()->isIntegerTy()) {
2430  AddOp = Instruction::Add;
2431  MulOp = Instruction::Mul;
2432  } else {
2433  AddOp = II.getInductionOpcode();
2434  MulOp = Instruction::FMul;
2435  }
2436 
2437  // Multiply the vectorization factor by the step using integer or
2438  // floating-point arithmetic as appropriate.
2439  Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
2440  Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
2441 
2442  // Create a vector splat to use in the induction update.
2443  //
2444  // FIXME: If the step is non-constant, we create the vector splat with
2445  // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2446  // handle a constant vector splat.
2447  Value *SplatVF = isa<Constant>(Mul)
2448  ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2449  : Builder.CreateVectorSplat(VF, Mul);
2450  Builder.restoreIP(CurrIP);
2451 
2452  // We may need to add the step a number of times, depending on the unroll
2453  // factor. The last of those goes into the PHI.
2454  PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2455  &*LoopVectorBody->getFirstInsertionPt());
2456  Instruction *LastInduction = VecInd;
2457  for (unsigned Part = 0; Part < UF; ++Part) {
2458  VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
2459  if (isa<TruncInst>(EntryVal))
2460  addMetadata(LastInduction, EntryVal);
2461  LastInduction = cast<Instruction>(addFastMathFlag(
2462  Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
2463  }
2464 
2465  // Move the last step to the end of the latch block. This ensures consistent
2466  // placement of all induction updates.
2467  auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2468  auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2469  auto *ICmp = cast<Instruction>(Br->getCondition());
2470  LastInduction->moveBefore(ICmp);
2471  LastInduction->setName("vec.ind.next");
2472 
2473  VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2474  VecInd->addIncoming(LastInduction, LoopVectorLatch);
2475 }
2476 
2478  return Cost->isScalarAfterVectorization(I, VF) ||
2479  Cost->isProfitableToScalarize(I, VF);
2480 }
2481 
2483  if (shouldScalarizeInstruction(IV))
2484  return true;
2485  auto isScalarInst = [&](User *U) -> bool {
2486  auto *I = cast<Instruction>(U);
2487  return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2488  };
2489  return any_of(IV->users(), isScalarInst);
2490 }
2491 
2493 
2494  assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2495  "Primary induction variable must have an integer type");
2496 
2497  auto II = Legal->getInductionVars()->find(IV);
2498  assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
2499 
2500  auto ID = II->second;
2501  assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2502 
2503  // The scalar value to broadcast. This will be derived from the canonical
2504  // induction variable.
2505  Value *ScalarIV = nullptr;
2506 
2507  // The value from the original loop to which we are mapping the new induction
2508  // variable.
2509  Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2510 
2511  // True if we have vectorized the induction variable.
2512  auto VectorizedIV = false;
2513 
2514  // Determine if we want a scalar version of the induction variable. This is
2515  // true if the induction variable itself is not widened, or if it has at
2516  // least one user in the loop that is not widened.
2517  auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
2518 
2519  // Generate code for the induction step. Note that induction steps are
2520  // required to be loop-invariant
2521  assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
2522  "Induction step should be loop invariant");
2523  auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2524  Value *Step = nullptr;
2525  if (PSE.getSE()->isSCEVable(IV->getType())) {
2526  SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2527  Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2528  LoopVectorPreHeader->getTerminator());
2529  } else {
2530  Step = cast<SCEVUnknown>(ID.getStep())->getValue();
2531  }
2532 
2533  // Try to create a new independent vector induction variable. If we can't
2534  // create the phi node, we will splat the scalar induction variable in each
2535  // loop iteration.
2536  if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
2537  createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2538  VectorizedIV = true;
2539  }
2540 
2541  // If we haven't yet vectorized the induction variable, or if we will create
2542  // a scalar one, we need to define the scalar induction variable and step
2543  // values. If we were given a truncation type, truncate the canonical
2544  // induction variable and step. Otherwise, derive these values from the
2545  // induction descriptor.
2546  if (!VectorizedIV || NeedsScalarIV) {
2547  ScalarIV = Induction;
2548  if (IV != OldInduction) {
2549  ScalarIV = IV->getType()->isIntegerTy()
2550  ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2551  : Builder.CreateCast(Instruction::SIToFP, Induction,
2552  IV->getType());
2553  ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
2554  ScalarIV->setName("offset.idx");
2555  }
2556  if (Trunc) {
2557  auto *TruncType = cast<IntegerType>(Trunc->getType());
2558  assert(Step->getType()->isIntegerTy() &&
2559  "Truncation requires an integer step");
2560  ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2561  Step = Builder.CreateTrunc(Step, TruncType);
2562  }
2563  }
2564 
2565  // If we haven't yet vectorized the induction variable, splat the scalar
2566  // induction variable, and build the necessary step vectors.
2567  if (!VectorizedIV) {
2568  Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2569  for (unsigned Part = 0; Part < UF; ++Part) {
2570  Value *EntryPart =
2571  getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
2572  VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
2573  if (Trunc)
2574  addMetadata(EntryPart, Trunc);
2575  }
2576  }
2577 
2578  // If an induction variable is only used for counting loop iterations or
2579  // calculating addresses, it doesn't need to be widened. Create scalar steps
2580  // that can be used by instructions we will later scalarize. Note that the
2581  // addition of the scalar steps will not increase the number of instructions
2582  // in the loop in the common case prior to InstCombine. We will be trading
2583  // one vector extract for each scalar step.
2584  if (NeedsScalarIV)
2585  buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2586 }
2587 
2589  Instruction::BinaryOps BinOp) {
2590  // Create and check the types.
2591  assert(Val->getType()->isVectorTy() && "Must be a vector");
2592  int VLen = Val->getType()->getVectorNumElements();
2593 
2594  Type *STy = Val->getType()->getScalarType();
2595  assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2596  "Induction Step must be an integer or FP");
2597  assert(Step->getType() == STy && "Step has wrong type");
2598 
2600 
2601  if (STy->isIntegerTy()) {
2602  // Create a vector of consecutive numbers from zero to VF.
2603  for (int i = 0; i < VLen; ++i)
2604  Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2605 
2606  // Add the consecutive indices to the vector value.
2607  Constant *Cv = ConstantVector::get(Indices);
2608  assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2609  Step = Builder.CreateVectorSplat(VLen, Step);
2610  assert(Step->getType() == Val->getType() && "Invalid step vec");
2611  // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2612  // which can be found from the original scalar operations.
2613  Step = Builder.CreateMul(Cv, Step);
2614  return Builder.CreateAdd(Val, Step, "induction");
2615  }
2616 
2617  // Floating point induction.
2618  assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2619  "Binary Opcode should be specified for FP induction");
2620  // Create a vector of consecutive numbers from zero to VF.
2621  for (int i = 0; i < VLen; ++i)
2622  Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2623 
2624  // Add the consecutive indices to the vector value.
2625  Constant *Cv = ConstantVector::get(Indices);
2626 
2627  Step = Builder.CreateVectorSplat(VLen, Step);
2628 
2629  // Floating point operations had to be 'fast' to enable the induction.
2631  Flags.setUnsafeAlgebra();
2632 
2633  Value *MulOp = Builder.CreateFMul(Cv, Step);
2634  if (isa<Instruction>(MulOp))
2635  // Have to check, MulOp may be a constant
2636  cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2637 
2638  Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2639  if (isa<Instruction>(BOp))
2640  cast<Instruction>(BOp)->setFastMathFlags(Flags);
2641  return BOp;
2642 }
2643 
2645  Value *EntryVal,
2646  const InductionDescriptor &ID) {
2647 
2648  // We shouldn't have to build scalar steps if we aren't vectorizing.
2649  assert(VF > 1 && "VF should be greater than one");
2650 
2651  // Get the value type and ensure it and the step have the same integer type.
2652  Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2653  assert(ScalarIVTy == Step->getType() &&
2654  "Val and Step should have the same type");
2655 
2656  // We build scalar steps for both integer and floating-point induction
2657  // variables. Here, we determine the kind of arithmetic we will perform.
2658  Instruction::BinaryOps AddOp;
2659  Instruction::BinaryOps MulOp;
2660  if (ScalarIVTy->isIntegerTy()) {
2661  AddOp = Instruction::Add;
2662  MulOp = Instruction::Mul;
2663  } else {
2664  AddOp = ID.getInductionOpcode();
2665  MulOp = Instruction::FMul;
2666  }
2667 
2668  // Determine the number of scalars we need to generate for each unroll
2669  // iteration. If EntryVal is uniform, we only need to generate the first
2670  // lane. Otherwise, we generate all VF values.
2671  unsigned Lanes =
2672  Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
2673  : VF;
2674  // Compute the scalar steps and save the results in VectorLoopValueMap.
2675  for (unsigned Part = 0; Part < UF; ++Part) {
2676  for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2677  auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2678  auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2679  auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2680  VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
2681  }
2682  }
2683 }
2684 
2685 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2686 
2687  const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() :
2688  ValueToValueMap();
2689 
2690  int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
2691  if (Stride == 1 || Stride == -1)
2692  return Stride;
2693  return 0;
2694 }
2695 
2696 bool LoopVectorizationLegality::isUniform(Value *V) {
2697  return LAI->isUniform(V);
2698 }
2699 
2701  assert(V != Induction && "The new induction variable should not be used.");
2702  assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2703  assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2704 
2705  // If we have a stride that is replaced by one, do it here.
2706  if (Legal->hasStride(V))
2707  V = ConstantInt::get(V->getType(), 1);
2708 
2709  // If we have a vector mapped to this value, return it.
2710  if (VectorLoopValueMap.hasVectorValue(V, Part))
2711  return VectorLoopValueMap.getVectorValue(V, Part);
2712 
2713  // If the value has not been vectorized, check if it has been scalarized
2714  // instead. If it has been scalarized, and we actually need the value in
2715  // vector form, we will construct the vector values on demand.
2716  if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2717 
2718  Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
2719 
2720  // If we've scalarized a value, that value should be an instruction.
2721  auto *I = cast<Instruction>(V);
2722 
2723  // If we aren't vectorizing, we can just copy the scalar map values over to
2724  // the vector map.
2725  if (VF == 1) {
2726  VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2727  return ScalarValue;
2728  }
2729 
2730  // Get the last scalar instruction we generated for V and Part. If the value
2731  // is known to be uniform after vectorization, this corresponds to lane zero
2732  // of the Part unroll iteration. Otherwise, the last instruction is the one
2733  // we created for the last vector lane of the Part unroll iteration.
2734  unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2735  auto *LastInst = cast<Instruction>(
2736  VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
2737 
2738  // Set the insert point after the last scalarized instruction. This ensures
2739  // the insertelement sequence will directly follow the scalar definitions.
2740  auto OldIP = Builder.saveIP();
2741  auto NewIP = std::next(BasicBlock::iterator(LastInst));
2742  Builder.SetInsertPoint(&*NewIP);
2743 
2744  // However, if we are vectorizing, we need to construct the vector values.
2745  // If the value is known to be uniform after vectorization, we can just
2746  // broadcast the scalar value corresponding to lane zero for each unroll
2747  // iteration. Otherwise, we construct the vector values using insertelement
2748  // instructions. Since the resulting vectors are stored in
2749  // VectorLoopValueMap, we will only generate the insertelements once.
2750  Value *VectorValue = nullptr;
2751  if (Cost->isUniformAfterVectorization(I, VF)) {
2752  VectorValue = getBroadcastInstrs(ScalarValue);
2753  VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2754  } else {
2755  // Initialize packing with insertelements to start from undef.
2757  VectorLoopValueMap.setVectorValue(V, Part, Undef);
2758  for (unsigned Lane = 0; Lane < VF; ++Lane)
2759  packScalarIntoVectorValue(V, {Part, Lane});
2760  VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2761  }
2762  Builder.restoreIP(OldIP);
2763  return VectorValue;
2764  }
2765 
2766  // If this scalar is unknown, assume that it is a constant or that it is
2767  // loop invariant. Broadcast V and save the value for future uses.
2768  Value *B = getBroadcastInstrs(V);
2769  VectorLoopValueMap.setVectorValue(V, Part, B);
2770  return B;
2771 }
2772 
2773 Value *
2775  const VPIteration &Instance) {
2776  // If the value is not an instruction contained in the loop, it should
2777  // already be scalar.
2778  if (OrigLoop->isLoopInvariant(V))
2779  return V;
2780 
2781  assert(Instance.Lane > 0
2782  ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2783  : true && "Uniform values only have lane zero");
2784 
2785  // If the value from the original loop has not been vectorized, it is
2786  // represented by UF x VF scalar values in the new loop. Return the requested
2787  // scalar value.
2788  if (VectorLoopValueMap.hasScalarValue(V, Instance))
2789  return VectorLoopValueMap.getScalarValue(V, Instance);
2790 
2791  // If the value has not been scalarized, get its entry in VectorLoopValueMap
2792  // for the given unroll part. If this entry is not a vector type (i.e., the
2793  // vectorization factor is one), there is no need to generate an
2794  // extractelement instruction.
2795  auto *U = getOrCreateVectorValue(V, Instance.Part);
2796  if (!U->getType()->isVectorTy()) {
2797  assert(VF == 1 && "Value not scalarized has non-vector type");
2798  return U;
2799  }
2800 
2801  // Otherwise, the value from the original loop has been vectorized and is
2802  // represented by UF vector values. Extract and return the requested scalar
2803  // value from the appropriate vector lane.
2804  return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2805 }
2806 
2808  Value *V, const VPIteration &Instance) {
2809  assert(V != Induction && "The new induction variable should not be used.");
2810  assert(!V->getType()->isVectorTy() && "Can't pack a vector");
2811  assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2812 
2813  Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2814  Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2815  VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2816  Builder.getInt32(Instance.Lane));
2817  VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2818 }
2819 
2821  assert(Vec->getType()->isVectorTy() && "Invalid type");
2822  SmallVector<Constant *, 8> ShuffleMask;
2823  for (unsigned i = 0; i < VF; ++i)
2824  ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2825 
2826  return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2827  ConstantVector::get(ShuffleMask),
2828  "reverse");
2829 }
2830 
2831 // Try to vectorize the interleave group that \p Instr belongs to.
2832 //
2833 // E.g. Translate following interleaved load group (factor = 3):
2834 // for (i = 0; i < N; i+=3) {
2835 // R = Pic[i]; // Member of index 0
2836 // G = Pic[i+1]; // Member of index 1
2837 // B = Pic[i+2]; // Member of index 2
2838 // ... // do something to R, G, B
2839 // }
2840 // To:
2841 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2842 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2843 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2844 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2845 //
2846 // Or translate following interleaved store group (factor = 3):
2847 // for (i = 0; i < N; i+=3) {
2848 // ... do something to R, G, B
2849 // Pic[i] = R; // Member of index 0
2850 // Pic[i+1] = G; // Member of index 1
2851 // Pic[i+2] = B; // Member of index 2
2852 // }
2853 // To:
2854 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2855 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2856 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2857 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2858 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2860  const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2861  assert(Group && "Fail to get an interleaved access group.");
2862 
2863  // Skip if current instruction is not the insert position.
2864  if (Instr != Group->getInsertPos())
2865  return;
2866 
2867  const DataLayout &DL = Instr->getModule()->getDataLayout();
2868  Value *Ptr = getPointerOperand(Instr);
2869 
2870  // Prepare for the vector type of the interleaved load/store.
2871  Type *ScalarTy = getMemInstValueType(Instr);
2872  unsigned InterleaveFactor = Group->getFactor();
2873  Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2874  Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2875 
2876  // Prepare for the new pointers.
2877  setDebugLocFromInst(Builder, Ptr);
2878  SmallVector<Value *, 2> NewPtrs;
2879  unsigned Index = Group->getIndex(Instr);
2880 
2881  // If the group is reverse, adjust the index to refer to the last vector lane
2882  // instead of the first. We adjust the index from the first vector lane,
2883  // rather than directly getting the pointer for lane VF - 1, because the
2884  // pointer operand of the interleaved access is supposed to be uniform. For
2885  // uniform instructions, we're only required to generate a value for the
2886  // first vector lane in each unroll iteration.
2887  if (Group->isReverse())
2888  Index += (VF - 1) * Group->getFactor();
2889 
2890  for (unsigned Part = 0; Part < UF; Part++) {
2891  Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
2892 
2893  // Notice current instruction could be any index. Need to adjust the address
2894  // to the member of index 0.
2895  //
2896  // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2897  // b = A[i]; // Member of index 0
2898  // Current pointer is pointed to A[i+1], adjust it to A[i].
2899  //
2900  // E.g. A[i+1] = a; // Member of index 1
2901  // A[i] = b; // Member of index 0
2902  // A[i+2] = c; // Member of index 2 (Current instruction)
2903  // Current pointer is pointed to A[i+2], adjust it to A[i].
2904  NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2905 
2906  // Cast to the vector pointer type.
2907  NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2908  }
2909 
2910  setDebugLocFromInst(Builder, Instr);
2911  Value *UndefVec = UndefValue::get(VecTy);
2912 
2913  // Vectorize the interleaved load group.
2914  if (isa<LoadInst>(Instr)) {
2915 
2916  // For each unroll part, create a wide load for the group.
2917  SmallVector<Value *, 2> NewLoads;
2918  for (unsigned Part = 0; Part < UF; Part++) {
2919  auto *NewLoad = Builder.CreateAlignedLoad(
2920  NewPtrs[Part], Group->getAlignment(), "wide.vec");
2921  addMetadata(NewLoad, Instr);
2922  NewLoads.push_back(NewLoad);
2923  }
2924 
2925  // For each member in the group, shuffle out the appropriate data from the
2926  // wide loads.
2927  for (unsigned I = 0; I < InterleaveFactor; ++I) {
2928  Instruction *Member = Group->getMember(I);
2929 
2930  // Skip the gaps in the group.
2931  if (!Member)
2932  continue;
2933 
2934  Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2935  for (unsigned Part = 0; Part < UF; Part++) {
2936  Value *StridedVec = Builder.CreateShuffleVector(
2937  NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2938 
2939  // If this member has different type, cast the result type.
2940  if (Member->getType() != ScalarTy) {
2941  VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2942  StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2943  }
2944 
2945  if (Group->isReverse())
2946  StridedVec = reverseVector(StridedVec);
2947 
2948  VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2949  }
2950  }
2951  return;
2952  }
2953 
2954  // The sub vector type for current instruction.
2955  VectorType *SubVT = VectorType::get(ScalarTy, VF);
2956 
2957  // Vectorize the interleaved store group.
2958  for (unsigned Part = 0; Part < UF; Part++) {
2959  // Collect the stored vector from each member.
2960  SmallVector<Value *, 4> StoredVecs;
2961  for (unsigned i = 0; i < InterleaveFactor; i++) {
2962  // Interleaved store group doesn't allow a gap, so each index has a member
2963  Instruction *Member = Group->getMember(i);
2964  assert(Member && "Fail to get a member from an interleaved store group");
2965 
2966  Value *StoredVec = getOrCreateVectorValue(
2967  cast<StoreInst>(Member)->getValueOperand(), Part);
2968  if (Group->isReverse())
2969  StoredVec = reverseVector(StoredVec);
2970 
2971  // If this member has different type, cast it to a unified type.
2972 
2973  if (StoredVec->getType() != SubVT)
2974  StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2975 
2976  StoredVecs.push_back(StoredVec);
2977  }
2978 
2979  // Concatenate all vectors into a wide vector.
2980  Value *WideVec = concatenateVectors(Builder, StoredVecs);
2981 
2982  // Interleave the elements in the wide vector.
2983  Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2984  Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2985  "interleaved.vec");
2986 
2987  Instruction *NewStoreInstr =
2988  Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2989  addMetadata(NewStoreInstr, Instr);
2990  }
2991 }
2992 
2994  // Attempt to issue a wide load.
2995  LoadInst *LI = dyn_cast<LoadInst>(Instr);
2996  StoreInst *SI = dyn_cast<StoreInst>(Instr);
2997 
2998  assert((LI || SI) && "Invalid Load/Store instruction");
2999 
3000  LoopVectorizationCostModel::InstWidening Decision =
3001  Cost->getWideningDecision(Instr, VF);
3002  assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
3003  "CM decision should be taken at this point");
3004  if (Decision == LoopVectorizationCostModel::CM_Interleave)
3005  return vectorizeInterleaveGroup(Instr);
3006 
3007  Type *ScalarDataTy = getMemInstValueType(Instr);
3008  Type *DataTy = VectorType::get(ScalarDataTy, VF);
3009  Value *Ptr = getPointerOperand(Instr);
3010  unsigned Alignment = getMemInstAlignment(Instr);
3011  // An alignment of 0 means target abi alignment. We need to use the scalar's
3012  // target abi alignment in such a case.
3013  const DataLayout &DL = Instr->getModule()->getDataLayout();
3014  if (!Alignment)
3015  Alignment = DL.getABITypeAlignment(ScalarDataTy);
3016  unsigned AddressSpace = getMemInstAddressSpace(Instr);
3017 
3018  // Determine if the pointer operand of the access is either consecutive or
3019  // reverse consecutive.
3020  int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
3021  bool Reverse = ConsecutiveStride < 0;
3022  bool CreateGatherScatter =
3023  (Decision == LoopVectorizationCostModel::CM_GatherScatter);
3024 
3025  // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
3026  // gather/scatter. Otherwise Decision should have been to Scalarize.
3027  assert((ConsecutiveStride || CreateGatherScatter) &&
3028  "The instruction should be scalarized");
3029 
3030  // Handle consecutive loads/stores.
3031  if (ConsecutiveStride)
3032  Ptr = getOrCreateScalarValue(Ptr, {0, 0});
3033 
3034  VectorParts Mask = createBlockInMask(Instr->getParent());
3035  // Handle Stores:
3036  if (SI) {
3037  assert(!Legal->isUniform(SI->getPointerOperand()) &&
3038  "We do not allow storing to uniform addresses");
3039  setDebugLocFromInst(Builder, SI);
3040 
3041  for (unsigned Part = 0; Part < UF; ++Part) {
3042  Instruction *NewSI = nullptr;
3043  Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
3044  if (CreateGatherScatter) {
3045  Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr;
3046  Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3047  NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
3048  MaskPart);
3049  } else {
3050  // Calculate the pointer for the specific unroll-part.
3051  Value *PartPtr =
3052  Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3053 
3054  if (Reverse) {
3055  // If we store to reverse consecutive memory locations, then we need
3056  // to reverse the order of elements in the stored value.
3057  StoredVal = reverseVector(StoredVal);
3058  // We don't want to update the value in the map as it might be used in
3059  // another expression. So don't call resetVectorValue(StoredVal).
3060 
3061  // If the address is consecutive but reversed, then the
3062  // wide store needs to start at the last vector element.
3063  PartPtr =
3064  Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3065  PartPtr =
3066  Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3067  if (Mask[Part]) // The reverse of a null all-one mask is a null mask.
3068  Mask[Part] = reverseVector(Mask[Part]);
3069  }
3070 
3071  Value *VecPtr =
3072  Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3073 
3074  if (Legal->isMaskRequired(SI) && Mask[Part])
3075  NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
3076  Mask[Part]);
3077  else
3078  NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
3079  }
3080  addMetadata(NewSI, SI);
3081  }
3082  return;
3083  }
3084 
3085  // Handle loads.
3086  assert(LI && "Must have a load instruction");
3087  setDebugLocFromInst(Builder, LI);
3088  for (unsigned Part = 0; Part < UF; ++Part) {
3089  Value *NewLI;
3090  if (CreateGatherScatter) {
3091  Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr;
3092  Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3093  NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
3094  nullptr, "wide.masked.gather");
3095  addMetadata(NewLI, LI);
3096  } else {
3097  // Calculate the pointer for the specific unroll-part.
3098  Value *PartPtr =
3099  Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3100 
3101  if (Reverse) {
3102  // If the address is consecutive but reversed, then the
3103  // wide load needs to start at the last vector element.
3104  PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3105  PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3106  if (Mask[Part]) // The reverse of a null all-one mask is a null mask.
3107  Mask[Part] = reverseVector(Mask[Part]);
3108  }
3109 
3110  Value *VecPtr =
3111  Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3112  if (Legal->isMaskRequired(LI) && Mask[Part])
3113  NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
3114  UndefValue::get(DataTy),
3115  "wide.masked.load");
3116  else
3117  NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
3118 
3119  // Add metadata to the load, but setVectorValue to the reverse shuffle.
3120  addMetadata(NewLI, LI);
3121  if (Reverse)
3122  NewLI = reverseVector(NewLI);
3123  }
3124  VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
3125  }
3126 }
3127 
3129  const VPIteration &Instance,
3130  bool IfPredicateInstr) {
3131  assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3132 
3133  setDebugLocFromInst(Builder, Instr);
3134 
3135  // Does this instruction return a value ?
3136  bool IsVoidRetTy = Instr->getType()->isVoidTy();
3137 
3138  Instruction *Cloned = Instr->clone();
3139  if (!IsVoidRetTy)
3140  Cloned->setName(Instr->getName() + ".cloned");
3141 
3142  // Replace the operands of the cloned instructions with their scalar
3143  // equivalents in the new loop.
3144  for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
3145  auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
3146  Cloned->setOperand(op, NewOp);
3147  }
3148  addNewMetadata(Cloned, Instr);
3149 
3150  // Place the cloned scalar in the new loop.
3151  Builder.Insert(Cloned);
3152 
3153  // Add the cloned scalar to the scalar map entry.
3154  VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
3155 
3156  // If we just cloned a new assumption, add it the assumption cache.
3157  if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
3158  if (II->getIntrinsicID() == Intrinsic::assume)
3159  AC->registerAssumption(II);
3160 
3161  // End if-block.
3162  if (IfPredicateInstr)
3163  PredicatedInstructions.push_back(Cloned);
3164 }
3165 
3167  Value *End, Value *Step,
3168  Instruction *DL) {
3169  BasicBlock *Header = L->getHeader();
3170  BasicBlock *Latch = L->getLoopLatch();
3171  // As we're just creating this loop, it's possible no latch exists
3172  // yet. If so, use the header as this will be a single block loop.
3173  if (!Latch)
3174  Latch = Header;
3175 
3176  IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3177  Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3178  setDebugLocFromInst(Builder, OldInst);
3179  auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3180 
3181  Builder.SetInsertPoint(Latch->getTerminator());
3182  setDebugLocFromInst(Builder, OldInst);
3183 
3184  // Create i+1 and fill the PHINode.
3185  Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3186  Induction->addIncoming(Start, L->getLoopPreheader());
3187  Induction->addIncoming(Next, Latch);
3188  // Create the compare.
3189  Value *ICmp = Builder.CreateICmpEQ(Next, End);
3190  Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
3191 
3192  // Now we have two terminators. Remove the old one from the block.
3193  Latch->getTerminator()->eraseFromParent();
3194 
3195  return Induction;
3196 }
3197 
3199  if (TripCount)
3200  return TripCount;
3201 
3202  IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3203  // Find the loop boundaries.
3204  ScalarEvolution *SE = PSE.getSE();
3205  const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3206  assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
3207  "Invalid loop count");
3208 
3209  Type *IdxTy = Legal->getWidestInductionType();
3210 
3211  // The exit count might have the type of i64 while the phi is i32. This can
3212  // happen if we have an induction variable that is sign extended before the
3213  // compare. The only way that we get a backedge taken count is that the
3214  // induction variable was signed and as such will not overflow. In such a case
3215  // truncation is legal.
3216  if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
3217  IdxTy->getPrimitiveSizeInBits())
3218  BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3219  BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3220 
3221  // Get the total trip count from the count by adding 1.
3222  const SCEV *ExitCount = SE->getAddExpr(
3223  BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3224 
3225  const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3226 
3227  // Expand the trip count and place the new instructions in the preheader.
3228  // Notice that the pre-header does not change, only the loop body.
3229  SCEVExpander Exp(*SE, DL, "induction");
3230 
3231  // Count holds the overall loop count (N).
3232  TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3234 
3235  if (TripCount->getType()->isPointerTy())
3236  TripCount =
3237  CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3239 
3240  return TripCount;
3241 }
3242 
3244  if (VectorTripCount)
3245  return VectorTripCount;
3246 
3247  Value *TC = getOrCreateTripCount(L);
3248  IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3249 
3250  // Now we need to generate the expression for the part of the loop that the
3251  // vectorized body will execute. This is equal to N - (N % Step) if scalar
3252  // iterations are not required for correctness, or N - Step, otherwise. Step
3253  // is equal to the vectorization factor (number of SIMD elements) times the
3254  // unroll factor (number of SIMD instructions).
3255  Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
3256  Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3257 
3258  // If there is a non-reversed interleaved group that may speculatively access
3259  // memory out-of-bounds, we need to ensure that there will be at least one
3260  // iteration of the scalar epilogue loop. Thus, if the step evenly divides
3261  // the trip count, we set the remainder to be equal to the step. If the step
3262  // does not evenly divide the trip count, no adjustment is necessary since
3263  // there will already be scalar iterations. Note that the minimum iterations
3264  // check ensures that N >= Step.
3265  if (VF > 1 && Legal->requiresScalarEpilogue()) {
3266  auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3267  R = Builder.CreateSelect(IsZero, Step, R);
3268  }
3269 
3270  VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3271 
3272  return VectorTripCount;
3273 }
3274 
3276  const DataLayout &DL) {
3277  // Verify that V is a vector type with same number of elements as DstVTy.
3278  unsigned VF = DstVTy->getNumElements();
3279  VectorType *SrcVecTy = cast<VectorType>(V->getType());
3280  assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3281  Type *SrcElemTy = SrcVecTy->getElementType();
3282  Type *DstElemTy = DstVTy->getElementType();
3283  assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3284  "Vector elements must have same size");
3285 
3286  // Do a direct cast if element types are castable.
3287  if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3288  return Builder.CreateBitOrPointerCast(V, DstVTy);
3289  }
3290  // V cannot be directly casted to desired vector type.
3291  // May happen when V is a floating point vector but DstVTy is a vector of
3292  // pointers or vice-versa. Handle this using a two-step bitcast using an
3293  // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3294  assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3295  "Only one type should be a pointer type");
3296  assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3297  "Only one type should be a floating point type");
3298  Type *IntTy =
3300  VectorType *VecIntTy = VectorType::get(IntTy, VF);
3301  Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3302  return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3303 }
3304 
3306  BasicBlock *Bypass) {
3307  Value *Count = getOrCreateTripCount(L);
3308  BasicBlock *BB = L->getLoopPreheader();
3309  IRBuilder<> Builder(BB->getTerminator());
3310 
3311  // Generate code to check if the loop's trip count is less than VF * UF, or
3312  // equal to it in case a scalar epilogue is required; this implies that the
3313  // vector trip count is zero. This check also covers the case where adding one
3314  // to the backedge-taken count overflowed leading to an incorrect trip count
3315  // of zero. In this case we will also jump to the scalar loop.
3316  auto P = Legal->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
3318  Value *CheckMinIters = Builder.CreateICmp(
3319  P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
3320 
3321  BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3322  // Update dominator tree immediately if the generated block is a
3323  // LoopBypassBlock because SCEV expansions to generate loop bypass
3324  // checks may query it before the current function is finished.
3325  DT->addNewBlock(NewBB, BB);
3326  if (L->getParentLoop())
3327  L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3329  BranchInst::Create(Bypass, NewBB, CheckMinIters));
3330  LoopBypassBlocks.push_back(BB);
3331 }
3332 
3334  BasicBlock *BB = L->getLoopPreheader();
3335 
3336  // Generate the code to check that the SCEV assumptions that we made.
3337  // We want the new basic block to start at the first instruction in a
3338  // sequence of instructions that form a check.
3339  SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
3340  "scev.check");
3341  Value *SCEVCheck =
3342  Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
3343 
3344  if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3345  if (C->isZero())
3346  return;
3347 
3348  // Create a new block containing the stride check.
3349  BB->setName("vector.scevcheck");
3350  auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3351  // Update dominator tree immediately if the generated block is a
3352  // LoopBypassBlock because SCEV expansions to generate loop bypass
3353  // checks may query it before the current function is finished.
3354  DT->addNewBlock(NewBB, BB);
3355  if (L->getParentLoop())
3356  L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3358  BranchInst::Create(Bypass, NewBB, SCEVCheck));
3359  LoopBypassBlocks.push_back(BB);
3360  AddedSafetyChecks = true;
3361 }
3362 
3364  BasicBlock *BB = L->getLoopPreheader();
3365 
3366  // Generate the code that checks in runtime if arrays overlap. We put the
3367  // checks into a separate block to make the more common case of few elements
3368  // faster.
3369  Instruction *FirstCheckInst;
3370  Instruction *MemRuntimeCheck;
3371  std::tie(FirstCheckInst, MemRuntimeCheck) =
3372  Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
3373  if (!MemRuntimeCheck)
3374  return;
3375 
3376  // Create a new block containing the memory check.
3377  BB->setName("vector.memcheck");
3378  auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3379  // Update dominator tree immediately if the generated block is a
3380  // LoopBypassBlock because SCEV expansions to generate loop bypass
3381  // checks may query it before the current function is finished.
3382  DT->addNewBlock(NewBB, BB);
3383  if (L->getParentLoop())
3384  L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3386  BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
3387  LoopBypassBlocks.push_back(BB);
3388  AddedSafetyChecks = true;
3389 
3390  // We currently don't use LoopVersioning for the actual loop cloning but we
3391  // still use it to add the noalias metadata.
3392  LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3393  PSE.getSE());
3394  LVer->prepareNoAliasMetadata();
3395 }
3396 
3398  /*
3399  In this function we generate a new loop. The new loop will contain
3400  the vectorized instructions while the old loop will continue to run the
3401  scalar remainder.
3402 
3403  [ ] <-- loop iteration number check.
3404  / |
3405  / v
3406  | [ ] <-- vector loop bypass (may consist of multiple blocks).
3407  | / |
3408  | / v
3409  || [ ] <-- vector pre header.
3410  |/ |
3411  | v
3412  | [ ] \
3413  | [ ]_| <-- vector loop.
3414  | |
3415  | v
3416  | -[ ] <--- middle-block.
3417  | / |
3418  | / v
3419  -|- >[ ] <--- new preheader.
3420  | |
3421  | v
3422  | [ ] \
3423  | [ ]_| <-- old scalar loop to handle remainder.
3424  \ |
3425  \ v
3426  >[ ] <-- exit block.
3427  ...
3428  */
3429 
3430  BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3431  BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3432  BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3433  assert(VectorPH && "Invalid loop structure");
3434  assert(ExitBlock && "Must have an exit block");
3435 
3436  // Some loops have a single integer induction variable, while other loops
3437  // don't. One example is c++ iterators that often have multiple pointer
3438  // induction variables. In the code below we also support a case where we
3439  // don't have a single induction variable.
3440  //
3441  // We try to obtain an induction variable from the original loop as hard
3442  // as possible. However if we don't find one that:
3443  // - is an integer
3444  // - counts from zero, stepping by one
3445  // - is the size of the widest induction variable type
3446  // then we create a new one.
3447  OldInduction = Legal->getPrimaryInduction();
3448  Type *IdxTy = Legal->getWidestInductionType();
3449 
3450  // Split the single block loop into the two loop structure described above.
3451  BasicBlock *VecBody =
3452  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
3453  BasicBlock *MiddleBlock =
3454  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
3455  BasicBlock *ScalarPH =
3456  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
3457 
3458  // Create and register the new vector loop.
3459  Loop *Lp = new Loop();
3460  Loop *ParentLoop = OrigLoop->getParentLoop();
3461 
3462  // Insert the new loop into the loop nest and register the new basic blocks
3463  // before calling any utilities such as SCEV that require valid LoopInfo.
3464  if (ParentLoop) {
3465  ParentLoop->addChildLoop(Lp);
3466  ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
3467  ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
3468  } else {
3469  LI->addTopLevelLoop(Lp);
3470  }
3471  Lp->addBasicBlockToLoop(VecBody, *LI);
3472 
3473  // Find the loop boundaries.
3474  Value *Count = getOrCreateTripCount(Lp);
3475 
3476  Value *StartIdx = ConstantInt::get(IdxTy, 0);
3477 
3478  // Now, compare the new count to zero. If it is zero skip the vector loop and
3479  // jump to the scalar loop. This check also covers the case where the
3480  // backedge-taken count is uint##_max: adding one to it will overflow leading
3481  // to an incorrect trip count of zero. In this (rare) case we will also jump
3482  // to the scalar loop.
3483  emitMinimumIterationCountCheck(Lp, ScalarPH);
3484 
3485  // Generate the code to check any assumptions that we've made for SCEV
3486  // expressions.
3487  emitSCEVChecks(Lp, ScalarPH);
3488 
3489  // Generate the code that checks in runtime if arrays overlap. We put the
3490  // checks into a separate block to make the more common case of few elements
3491  // faster.
3492  emitMemRuntimeChecks(Lp, ScalarPH);
3493 
3494  // Generate the induction variable.
3495  // The loop step is equal to the vectorization factor (num of SIMD elements)
3496  // times the unroll factor (num of SIMD instructions).
3497  Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3498  Constant *Step = ConstantInt::get(IdxTy, VF * UF);
3499  Induction =
3500  createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3501  getDebugLocFromInstOrOperands(OldInduction));
3502 
3503  // We are going to resume the execution of the scalar loop.
3504  // Go over all of the induction variables that we found and fix the
3505  // PHIs that are left in the scalar version of the loop.
3506  // The starting values of PHI nodes depend on the counter of the last
3507  // iteration in the vectorized loop.
3508  // If we come from a bypass edge then we need to start from the original
3509  // start value.
3510 
3511  // This variable saves the new starting index for the scalar loop. It is used
3512  // to test if there are any tail iterations left once the vector loop has
3513  // completed.
3514  LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
3515  for (auto &InductionEntry : *List) {
3516  PHINode *OrigPhi = InductionEntry.first;
3517  InductionDescriptor II = InductionEntry.second;
3518 
3519  // Create phi nodes to merge from the backedge-taken check block.
3520  PHINode *BCResumeVal = PHINode::Create(
3521  OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
3522  Value *&EndValue = IVEndValues[OrigPhi];
3523  if (OrigPhi == OldInduction) {
3524  // We know what the end value is.
3525  EndValue = CountRoundDown;
3526  } else {
3528  Type *StepType = II.getStep()->getType();
3529  Instruction::CastOps CastOp =
3530  CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
3531  Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
3532  const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3533  EndValue = II.transform(B, CRD, PSE.getSE(), DL);
3534  EndValue->setName("ind.end");
3535  }
3536 
3537  // The new PHI merges the original incoming value, in case of a bypass,
3538  // or the value at the end of the vectorized loop.
3539  BCResumeVal->addIncoming(EndValue, MiddleBlock);
3540 
3541  // Fix the scalar body counter (PHI node).
3542  unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
3543 
3544  // The old induction's phi node in the scalar body needs the truncated
3545  // value.
3546  for (BasicBlock *BB : LoopBypassBlocks)
3547  BCResumeVal->addIncoming(II.getStartValue(), BB);
3548  OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
3549  }
3550 
3551  // Add a check in the middle block to see if we have completed
3552  // all of the iterations in the first vector loop.
3553  // If (N - N%VF) == N, then we *don't* need to run the remainder.
3554  Value *CmpN =
3555  CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3556  CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
3557  ReplaceInstWithInst(MiddleBlock->getTerminator(),
3558  BranchInst::Create(ExitBlock, ScalarPH, CmpN));
3559 
3560  // Get ready to start creating new instructions into the vectorized body.
3561  Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
3562 
3563  // Save the state.
3564  LoopVectorPreHeader = Lp->getLoopPreheader();
3565  LoopScalarPreHeader = ScalarPH;
3566  LoopMiddleBlock = MiddleBlock;
3567  LoopExitBlock = ExitBlock;
3568  LoopVectorBody = VecBody;
3569  LoopScalarBody = OldBasicBlock;
3570 
3571  // Keep all loop hints from the original loop on the vector loop (we'll
3572  // replace the vectorizer-specific hints below).
3573  if (MDNode *LID = OrigLoop->getLoopID())
3574  Lp->setLoopID(LID);
3575 
3576  LoopVectorizeHints Hints(Lp, true, *ORE);
3577  Hints.setAlreadyVectorized();
3578 
3579  return LoopVectorPreHeader;
3580 }
3581 
3582 // Fix up external users of the induction variable. At this point, we are
3583 // in LCSSA form, with all external PHIs that use the IV having one input value,
3584 // coming from the remainder loop. We need those PHIs to also have a correct
3585 // value for the IV when arriving directly from the middle block.
3587  const InductionDescriptor &II,
3588  Value *CountRoundDown, Value *EndValue,
3589  BasicBlock *MiddleBlock) {
3590  // There are two kinds of external IV usages - those that use the value
3591  // computed in the last iteration (the PHI) and those that use the penultimate
3592  // value (the value that feeds into the phi from the loop latch).
3593  // We allow both, but they, obviously, have different values.
3594 
3595  assert(OrigLoop->getExitBlock() && "Expected a single exit block");
3596 
3597  DenseMap<Value *, Value *> MissingVals;
3598 
3599  // An external user of the last iteration's value should see the value that
3600  // the remainder loop uses to initialize its own IV.
3601  Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3602  for (User *U : PostInc->users()) {
3603  Instruction *UI = cast<Instruction>(U);
3604  if (!OrigLoop->contains(UI)) {
3605  assert(isa<PHINode>(UI) && "Expected LCSSA form");
3606  MissingVals[UI] = EndValue;
3607  }
3608  }
3609 
3610  // An external user of the penultimate value need to see EndValue - Step.
3611  // The simplest way to get this is to recompute it from the constituent SCEVs,
3612  // that is Start + (Step * (CRD - 1)).
3613  for (User *U : OrigPhi->users()) {
3614  auto *UI = cast<Instruction>(U);
3615  if (!OrigLoop->contains(UI)) {
3616  const DataLayout &DL =
3617  OrigLoop->getHeader()->getModule()->getDataLayout();
3618  assert(isa<PHINode>(UI) && "Expected LCSSA form");
3619 
3620  IRBuilder<> B(MiddleBlock->getTerminator());
3621  Value *CountMinusOne = B.CreateSub(
3622  CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3623  Value *CMO =
3624  !II.getStep()->getType()->isIntegerTy()
3625  ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3626  II.getStep()->getType())
3627  : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3628  CMO->setName("cast.cmo");
3629  Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3630  Escape->setName("ind.escape");
3631  MissingVals[UI] = Escape;
3632  }
3633  }
3634 
3635  for (auto &I : MissingVals) {
3636  PHINode *PHI = cast<PHINode>(I.first);
3637  // One corner case we have to handle is two IVs "chasing" each-other,
3638  // that is %IV2 = phi [...], [ %IV1, %latch ]
3639  // In this case, if IV1 has an external use, we need to avoid adding both
3640  // "last value of IV1" and "penultimate value of IV2". So, verify that we
3641  // don't already have an incoming value for the middle block.
3642  if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3643  PHI->addIncoming(I.second, MiddleBlock);
3644  }
3645 }
3646 
3647 namespace {
3648 struct CSEDenseMapInfo {
3649  static bool canHandle(const Instruction *I) {
3650  return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3651  isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3652  }
3653  static inline Instruction *getEmptyKey() {
3655  }
3656  static inline Instruction *getTombstoneKey() {
3658  }
3659  static unsigned getHashValue(const Instruction *I) {
3660  assert(canHandle(I) && "Unknown instruction!");
3662  I->value_op_end()));
3663  }
3664  static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3665  if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3666  LHS == getTombstoneKey() || RHS == getTombstoneKey())
3667  return LHS == RHS;
3668  return LHS->isIdenticalTo(RHS);
3669  }
3670 };
3671 }
3672 
3673 ///\brief Perform cse of induction variable instructions.
3674 static void cse(BasicBlock *BB) {
3675  // Perform simple cse.
3677  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3678  Instruction *In = &*I++;
3679 
3680  if (!CSEDenseMapInfo::canHandle(In))
3681  continue;
3682 
3683  // Check if we can replace this instruction with any of the
3684  // visited instructions.
3685  if (Instruction *V = CSEMap.lookup(In)) {
3686  In->replaceAllUsesWith(V);
3687  In->eraseFromParent();
3688  continue;
3689  }
3690 
3691  CSEMap[In] = In;
3692  }
3693 }
3694 
3695 /// \brief Estimate the overhead of scalarizing an instruction. This is a
3696 /// convenience wrapper for the type-based getScalarizationOverhead API.
3697 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3698  const TargetTransformInfo &TTI) {
3699  if (VF == 1)
3700  return 0;
3701 
3702  unsigned Cost = 0;
3703  Type *RetTy = ToVectorTy(I->getType(), VF);
3704  if (!RetTy->isVoidTy() &&
3705  (!isa<LoadInst>(I) ||
3707  Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3708 
3709  if (CallInst *CI = dyn_cast<CallInst>(I)) {
3710  SmallVector<const Value *, 4> Operands(CI->arg_operands());
3711  Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3712  }
3713  else if (!isa<StoreInst>(I) ||
3716  Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3717  }
3718 
3719  return Cost;
3720 }
3721 
3722 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3723 // Return the cost of the instruction, including scalarization overhead if it's
3724 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3725 // i.e. either vector version isn't available, or is too expensive.
3726 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3727  const TargetTransformInfo &TTI,
3728  const TargetLibraryInfo *TLI,
3729  bool &NeedToScalarize) {
3730  Function *F = CI->getCalledFunction();
3731  StringRef FnName = CI->getCalledFunction()->getName();
3732  Type *ScalarRetTy = CI->getType();
3733  SmallVector<Type *, 4> Tys, ScalarTys;
3734  for (auto &ArgOp : CI->arg_operands())
3735  ScalarTys.push_back(ArgOp->getType());
3736 
3737  // Estimate cost of scalarized vector call. The source operands are assumed
3738  // to be vectors, so we need to extract individual elements from there,
3739  // execute VF scalar calls, and then gather the result into the vector return
3740  // value.
3741  unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3742  if (VF == 1)
3743  return ScalarCallCost;
3744 
3745  // Compute corresponding vector type for return value and arguments.
3746  Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3747  for (Type *ScalarTy : ScalarTys)
3748  Tys.push_back(ToVectorTy(ScalarTy, VF));
3749 
3750  // Compute costs of unpacking argument values for the scalar calls and
3751  // packing the return values to a vector.
3752  unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3753 
3754  unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3755 
3756  // If we can't emit a vector call for this function, then the currently found
3757  // cost is the cost we need to return.
3758  NeedToScalarize = true;
3759  if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3760  return Cost;
3761 
3762  // If the corresponding vector cost is cheaper, return its cost.
3763  unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3764  if (VectorCallCost < Cost) {
3765  NeedToScalarize = false;
3766  return VectorCallCost;
3767  }
3768  return Cost;
3769 }
3770 
3771 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3772 // factor VF. Return the cost of the instruction, including scalarization
3773 // overhead if it's needed.
3774 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3775  const TargetTransformInfo &TTI,
3776  const TargetLibraryInfo *TLI) {
3778  assert(ID && "Expected intrinsic call!");
3779 
3780  FastMathFlags FMF;
3781  if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3782  FMF = FPMO->getFastMathFlags();
3783 
3784  SmallVector<Value *, 4> Operands(CI->arg_operands());
3785  return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3786 }
3787 
3789  auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3790  auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3791  return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3792 }
3794  auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3795  auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3796  return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3797 }
3798 
3800  // For every instruction `I` in MinBWs, truncate the operands, create a
3801  // truncated version of `I` and reextend its result. InstCombine runs
3802  // later and will remove any ext/trunc pairs.
3803  //
3804  SmallPtrSet<Value *, 4> Erased;
3805  for (const auto &KV : Cost->getMinimalBitwidths()) {
3806  // If the value wasn't vectorized, we must maintain the original scalar
3807  // type. The absence of the value from VectorLoopValueMap indicates that it
3808  // wasn't vectorized.
3809  if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3810  continue;
3811  for (unsigned Part = 0; Part < UF; ++Part) {
3812  Value *I = getOrCreateVectorValue(KV.first, Part);
3813  if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3814  continue;
3815  Type *OriginalTy = I->getType();
3816  Type *ScalarTruncatedTy =
3817  IntegerType::get(OriginalTy->getContext(), KV.second);
3818  Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3819  OriginalTy->getVectorNumElements());
3820  if (TruncatedTy == OriginalTy)
3821  continue;
3822 
3823  IRBuilder<> B(cast<Instruction>(I));
3824  auto ShrinkOperand = [&](Value *V) -> Value * {
3825  if (auto *ZI = dyn_cast<ZExtInst>(V))
3826  if (ZI->getSrcTy() == TruncatedTy)
3827  return ZI->getOperand(0);
3828  return B.CreateZExtOrTrunc(V, TruncatedTy);
3829  };
3830 
3831  // The actual instruction modification depends on the instruction type,
3832  // unfortunately.
3833  Value *NewI = nullptr;
3834  if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3835  NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3836  ShrinkOperand(BO->getOperand(1)));
3837 
3838  // Any wrapping introduced by shrinking this operation shouldn't be
3839  // considered undefined behavior. So, we can't unconditionally copy
3840  // arithmetic wrapping flags to NewI.
3841  cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3842  } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3843  NewI =
3844  B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3845  ShrinkOperand(CI->getOperand(1)));
3846  } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3847  NewI = B.CreateSelect(SI->getCondition(),
3848  ShrinkOperand(SI->getTrueValue()),
3849  ShrinkOperand(SI->getFalseValue()));
3850  } else if (auto *CI = dyn_cast<CastInst>(I)) {
3851  switch (CI->getOpcode()) {
3852  default:
3853  llvm_unreachable("Unhandled cast!");
3854  case Instruction::Trunc:
3855  NewI = ShrinkOperand(CI->getOperand(0));
3856  break;
3857  case Instruction::SExt:
3858  NewI = B.CreateSExtOrTrunc(
3859  CI->getOperand(0),
3860  smallestIntegerVectorType(OriginalTy, TruncatedTy));
3861  break;
3862  case Instruction::ZExt:
3863  NewI = B.CreateZExtOrTrunc(
3864  CI->getOperand(0),
3865  smallestIntegerVectorType(OriginalTy, TruncatedTy));
3866  break;
3867  }
3868  } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3869  auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3870  auto *O0 = B.CreateZExtOrTrunc(
3871  SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3872  auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3873  auto *O1 = B.CreateZExtOrTrunc(
3874  SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3875 
3876  NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3877  } else if (isa<LoadInst>(I)) {
3878  // Don't do anything with the operands, just extend the result.
3879  continue;
3880  } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3881  auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3882  auto *O0 = B.CreateZExtOrTrunc(
3883  IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3884  auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3885  NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3886  } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3887  auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3888  auto *O0 = B.CreateZExtOrTrunc(
3889  EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3890  NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3891  } else {
3892  llvm_unreachable("Unhandled instruction type!");
3893  }
3894 
3895  // Lastly, extend the result.
3896  NewI->takeName(cast<Instruction>(I));
3897  Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3898  I->replaceAllUsesWith(Res);
3899  cast<Instruction>(I)->eraseFromParent();
3900  Erased.insert(I);
3901  VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3902  }
3903  }
3904 
3905  // We'll have created a bunch of ZExts that are now parentless. Clean up.
3906  for (const auto &KV : Cost->getMinimalBitwidths()) {
3907  // If the value wasn't vectorized, we must maintain the original scalar
3908  // type. The absence of the value from VectorLoopValueMap indicates that it
3909  // wasn't vectorized.
3910  if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3911  continue;
3912  for (unsigned Part = 0; Part < UF; ++Part) {
3913  Value *I = getOrCreateVectorValue(KV.first, Part);
3914  ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3915  if (Inst && Inst->use_empty()) {
3916  Value *NewI = Inst->getOperand(0);
3917  Inst->eraseFromParent();
3918  VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3919  }
3920  }
3921  }
3922 }
3923 
3925  // Insert truncates and extends for any truncated instructions as hints to
3926  // InstCombine.
3927  if (VF > 1)
3928  truncateToMinimalBitwidths();
3929 
3930  // At this point every instruction in the original loop is widened to a
3931  // vector form. Now we need to fix the recurrences in the loop. These PHI
3932  // nodes are currently empty because we did not want to introduce cycles.
3933  // This is the second stage of vectorizing recurrences.
3934  fixCrossIterationPHIs();
3935 
3936  // Update the dominator tree.
3937  //
3938  // FIXME: After creating the structure of the new loop, the dominator tree is
3939  // no longer up-to-date, and it remains that way until we update it
3940  // here. An out-of-date dominator tree is problematic for SCEV,
3941  // because SCEVExpander uses it to guide code generation. The
3942  // vectorizer use SCEVExpanders in several places. Instead, we should
3943  // keep the dominator tree up-to-date as we go.
3944  updateAnalysis();
3945 
3946  // Fix-up external users of the induction variables.
3947  for (auto &Entry : *Legal->getInductionVars())
3948  fixupIVUsers(Entry.first, Entry.second,
3949  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3950  IVEndValues[Entry.first], LoopMiddleBlock);
3951 
3952  fixLCSSAPHIs();
3953  for (Instruction *PI : PredicatedInstructions)
3954  sinkScalarOperands(&*PI);
3955 
3956  // Remove redundant induction instructions.
3957  cse(LoopVectorBody);
3958 }
3959 
3961  // In order to support recurrences we need to be able to vectorize Phi nodes.
3962  // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3963  // stage #2: We now need to fix the recurrences by adding incoming edges to
3964  // the currently empty PHI nodes. At this point every instruction in the
3965  // original loop is widened to a vector form so we can use them to construct
3966  // the incoming edges.
3967  for (Instruction &I : *OrigLoop->getHeader()) {
3968  PHINode *Phi = dyn_cast<PHINode>(&I);
3969  if (!Phi)
3970  break;
3971  // Handle first-order recurrences and reductions that need to be fixed.
3972  if (Legal->isFirstOrderRecurrence(Phi))
3973  fixFirstOrderRecurrence(Phi);
3974  else if (Legal->isReductionVariable(Phi))
3975  fixReduction(Phi);
3976  }
3977 }
3978 
3980 
3981  // This is the second phase of vectorizing first-order recurrences. An
3982  // overview of the transformation is described below. Suppose we have the
3983  // following loop.
3984  //
3985  // for (int i = 0; i < n; ++i)
3986  // b[i] = a[i] - a[i - 1];
3987  //
3988  // There is a first-order recurrence on "a". For this loop, the shorthand
3989  // scalar IR looks like:
3990  //
3991  // scalar.ph:
3992  // s_init = a[-1]
3993  // br scalar.body
3994  //
3995  // scalar.body:
3996  // i = phi [0, scalar.ph], [i+1, scalar.body]
3997  // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3998  // s2 = a[i]
3999  // b[i] = s2 - s1
4000  // br cond, scalar.body, ...
4001  //
4002  // In this example, s1 is a recurrence because it's value depends on the
4003  // previous iteration. In the first phase of vectorization, we created a
4004  // temporary value for s1. We now complete the vectorization and produce the
4005  // shorthand vector IR shown below (for VF = 4, UF = 1).
4006  //
4007  // vector.ph:
4008  // v_init = vector(..., ..., ..., a[-1])
4009  // br vector.body
4010  //
4011  // vector.body
4012  // i = phi [0, vector.ph], [i+4, vector.body]
4013  // v1 = phi [v_init, vector.ph], [v2, vector.body]
4014  // v2 = a[i, i+1, i+2, i+3];
4015  // v3 = vector(v1(3), v2(0, 1, 2))
4016  // b[i, i+1, i+2, i+3] = v2 - v3
4017  // br cond, vector.body, middle.block
4018  //
4019  // middle.block:
4020  // x = v2(3)
4021  // br scalar.ph
4022  //
4023  // scalar.ph:
4024  // s_init = phi [x, middle.block], [a[-1], otherwise]
4025  // br scalar.body
4026  //
4027  // After execution completes the vector loop, we extract the next value of
4028  // the recurrence (x) to use as the initial value in the scalar loop.
4029 
4030  // Get the original loop preheader and single loop latch.
4031  auto *Preheader = OrigLoop->getLoopPreheader();
4032  auto *Latch = OrigLoop->getLoopLatch();
4033 
4034  // Get the initial and previous values of the scalar recurrence.
4035  auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4036  auto *Previous = Phi->getIncomingValueForBlock(Latch);
4037 
4038  // Create a vector from the initial value.
4039  auto *VectorInit = ScalarInit;
4040  if (VF > 1) {
4041  Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4042  VectorInit = Builder.CreateInsertElement(
4043  UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4044  Builder.getInt32(VF - 1), "vector.recur.init");
4045  }
4046 
4047  // We constructed a temporary phi node in the first phase of vectorization.
4048  // This phi node will eventually be deleted.
4049  Builder.SetInsertPoint(
4050  cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
4051 
4052  // Create a phi node for the new recurrence. The current value will either be
4053  // the initial value inserted into a vector or loop-varying vector value.
4054  auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4055  VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4056 
4057  // Get the vectorized previous value of the last part UF - 1. It appears last
4058  // among all unrolled iterations, due to the order of their construction.
4059  Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
4060 
4061  // Set the insertion point after the previous value if it is an instruction.
4062  // Note that the previous value may have been constant-folded so it is not
4063  // guaranteed to be an instruction in the vector loop. Also, if the previous
4064  // value is a phi node, we should insert after all the phi nodes to avoid
4065  // breaking basic block verification.
4066  if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
4067  isa<PHINode>(PreviousLastPart))
4068  Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4069  else
4070  Builder.SetInsertPoint(
4071  &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
4072 
4073  // We will construct a vector for the recurrence by combining the values for
4074  // the current and previous iterations. This is the required shuffle mask.
4075  SmallVector<Constant *, 8> ShuffleMask(VF);
4076  ShuffleMask[0] = Builder.getInt32(VF - 1);
4077  for (unsigned I = 1; I < VF; ++I)
4078  ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4079 
4080  // The vector from which to take the initial value for the current iteration
4081  // (actual or unrolled). Initially, this is the vector phi node.
4082  Value *Incoming = VecPhi;
4083 
4084  // Shuffle the current and previous vector and update the vector parts.
4085  for (unsigned Part = 0; Part < UF; ++Part) {
4086  Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
4087  Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
4088  auto *Shuffle =
4089  VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
4090  ConstantVector::get(ShuffleMask))
4091  : Incoming;
4092  PhiPart->replaceAllUsesWith(Shuffle);
4093  cast<Instruction>(PhiPart)->eraseFromParent();
4094  VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
4095  Incoming = PreviousPart;
4096  }
4097 
4098  // Fix the latch value of the new recurrence in the vector loop.
4099  VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4100 
4101  // Extract the last vector element in the middle block. This will be the
4102  // initial value for the recurrence when jumping to the scalar loop.
4103  auto *ExtractForScalar = Incoming;
4104  if (VF > 1) {
4105  Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4106  ExtractForScalar = Builder.CreateExtractElement(
4107  ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
4108  }
4109  // Extract the second last element in the middle block if the
4110  // Phi is used outside the loop. We need to extract the phi itself
4111  // and not the last element (the phi update in the current iteration). This
4112  // will be the value when jumping to the exit block from the LoopMiddleBlock,
4113  // when the scalar loop is not run at all.
4114  Value *ExtractForPhiUsedOutsideLoop = nullptr;
4115  if (VF > 1)
4116  ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4117  Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
4118  // When loop is unrolled without vectorizing, initialize
4119  // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4120  // `Incoming`. This is analogous to the vectorized case above: extracting the
4121  // second last element when VF > 1.
4122  else if (UF > 1)
4123  ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
4124 
4125  // Fix the initial value of the original recurrence in the scalar loop.
4126  Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4127  auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4128  for (auto *BB : predecessors(LoopScalarPreHeader)) {
4129  auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4130  Start->addIncoming(Incoming, BB);
4131  }
4132 
4133  Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4134  Phi->setName("scalar.recur");
4135 
4136  // Finally, fix users of the recurrence outside the loop. The users will need
4137  // either the last value of the scalar recurrence or the last value of the
4138  // vector recurrence we extracted in the middle block. Since the loop is in
4139  // LCSSA form, we just need to find the phi node for the original scalar
4140  // recurrence in the exit block, and then add an edge for the middle block.
4141  for (auto &I : *LoopExitBlock) {
4142  auto *LCSSAPhi = dyn_cast<PHINode>(&I);
4143  if (!LCSSAPhi)
4144  break;
4145  if (LCSSAPhi->getIncomingValue(0) == Phi) {
4146  LCSSAPhi->addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4147  break;
4148  }
4149  }
4150 }
4151 
4153  Constant *Zero = Builder.getInt32(0);
4154 
4155  // Get it's reduction variable descriptor.
4156  assert(Legal->isReductionVariable(Phi) &&
4157  "Unable to find the reduction variable");
4158  RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
4159 
4161  TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4162  Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4164  RdxDesc.getMinMaxRecurrenceKind();
4165  setDebugLocFromInst(Builder, ReductionStartValue);
4166 
4167  // We need to generate a reduction vector from the incoming scalar.
4168  // To do so, we need to generate the 'identity' vector and override
4169  // one of the elements with the incoming scalar reduction. We need
4170  // to do it in the vector-loop preheader.
4171  Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4172 
4173  // This is the vector-clone of the value that leaves the loop.
4174  Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
4175 
4176  // Find the reduction identity variable. Zero for addition, or, xor,
4177  // one for multiplication, -1 for And.
4178  Value *Identity;
4179  Value *VectorStart;
4182  // MinMax reduction have the start value as their identify.
4183  if (VF == 1) {
4184  VectorStart = Identity = ReductionStartValue;
4185  } else {
4186  VectorStart = Identity =
4187  Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
4188  }
4189  } else {
4190  // Handle other reduction kinds:
4192  RK, VecTy->getScalarType());
4193  if (VF == 1) {
4194  Identity = Iden;
4195  // This vector is the Identity vector where the first element is the
4196  // incoming scalar reduction.
4197  VectorStart = ReductionStartValue;
4198  } else {
4199  Identity = ConstantVector::getSplat(VF, Iden);
4200 
4201  // This vector is the Identity vector where the first element is the
4202  // incoming scalar reduction.
4203  VectorStart =
4204  Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
4205  }
4206  }
4207 
4208  // Fix the vector-loop phi.
4209 
4210  // Reductions do not have to start at zero. They can start with
4211  // any loop invariant values.
4212  BasicBlock *Latch = OrigLoop->getLoopLatch();
4213  Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
4214  for (unsigned Part = 0; Part < UF; ++Part) {
4215  Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
4216  Value *Val = getOrCreateVectorValue(LoopVal, Part);
4217  // Make sure to add the reduction stat value only to the
4218  // first unroll part.
4219  Value *StartVal = (Part == 0) ? VectorStart : Identity;
4220  cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
4221  cast<PHINode>(VecRdxPhi)
4222  ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4223  }
4224 
4225  // Before each round, move the insertion point right between
4226  // the PHIs and the values we are going to write.
4227  // This allows us to write both PHINodes and the extractelement
4228  // instructions.
4229  Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4230 
4231  setDebugLocFromInst(Builder, LoopExitInst);
4232 
4233  // If the vector reduction can be performed in a smaller type, we truncate
4234  // then extend the loop exit value to enable InstCombine to evaluate the
4235  // entire expression in the smaller type.
4236  if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
4237  Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4238  Builder.SetInsertPoint(LoopVectorBody->getTerminator());
4239  VectorParts RdxParts(UF);
4240  for (unsigned Part = 0; Part < UF; ++Part) {
4241  RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4242  Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4243  Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4244  : Builder.CreateZExt(Trunc, VecTy);
4245  for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4246  UI != RdxParts[Part]->user_end();)
4247  if (*UI != Trunc) {
4248  (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4249  RdxParts[Part] = Extnd;
4250  } else {
4251  ++UI;
4252  }
4253  }
4254  Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4255  for (unsigned Part = 0; Part < UF; ++Part) {
4256  RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4257  VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
4258  }
4259  }
4260 
4261  // Reduce all of the unrolled parts into a single vector.
4262  Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
4264  setDebugLocFromInst(Builder, ReducedPartRdx);
4265  for (unsigned Part = 1; Part < UF; ++Part) {
4266  Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4267  if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4268  // Floating point operations had to be 'fast' to enable the reduction.
4269  ReducedPartRdx = addFastMathFlag(
4270  Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
4271  ReducedPartRdx, "bin.rdx"));
4272  else
4273  ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
4274  Builder, MinMaxKind, ReducedPartRdx, RdxPart);
4275  }
4276 
4277  if (VF > 1) {
4278  bool NoNaN = Legal->hasFunNoNaNAttr();
4279  ReducedPartRdx =
4280  createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
4281  // If the reduction can be performed in a smaller type, we need to extend
4282  // the reduction to the wider type before we branch to the original loop.
4283  if (Phi->getType() != RdxDesc.getRecurrenceType())
4284  ReducedPartRdx =
4285  RdxDesc.isSigned()
4286  ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4287  : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4288  }
4289 
4290  // Create a phi node that merges control-flow from the backedge-taken check
4291  // block and the middle block.
4292  PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4293  LoopScalarPreHeader->getTerminator());
4294  for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4295  BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4296  BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4297 
4298  // Now, we need to fix the users of the reduction variable
4299  // inside and outside of the scalar remainder loop.
4300  // We know that the loop is in LCSSA form. We need to update the
4301  // PHI nodes in the exit blocks.
4302  for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
4303  LEE = LoopExitBlock->end();
4304  LEI != LEE; ++LEI) {
4305  PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
4306  if (!LCSSAPhi)
4307  break;
4308 
4309  // All PHINodes need to have a single entry edge, or two if
4310  // we already fixed them.
4311  assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
4312 
4313  // We found a reduction value exit-PHI. Update it with the
4314  // incoming bypass edge.
4315  if (LCSSAPhi->getIncomingValue(0) == LoopExitInst)
4316  LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4317  } // end of the LCSSA phi scan.
4318 
4319  // Fix the scalar loop reduction variable with the incoming reduction sum
4320  // from the vector body and from the backedge value.
4321  int IncomingEdgeBlockIdx =
4322  Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4323  assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4324  // Pick the other block.
4325  int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4326  Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4327  Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4328 }
4329 
4331  for (Instruction &LEI : *LoopExitBlock) {
4332  auto *LCSSAPhi = dyn_cast<PHINode>(&LEI);
4333  if (!LCSSAPhi)
4334  break;
4335  if (LCSSAPhi->getNumIncomingValues() == 1) {
4336  assert(OrigLoop->isLoopInvariant(LCSSAPhi->getIncomingValue(0)) &&
4337  "Incoming value isn't loop invariant");
4338  LCSSAPhi->addIncoming(LCSSAPhi->getIncomingValue(0), LoopMiddleBlock);
4339  }
4340  }
4341 }
4342 
4344 
4345  // The basic block and loop containing the predicated instruction.
4346  auto *PredBB = PredInst->getParent();
4347  auto *VectorLoop = LI->getLoopFor(PredBB);
4348 
4349  // Initialize a worklist with the operands of the predicated instruction.
4350  SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4351 
4352  // Holds instructions that we need to analyze again. An instruction may be
4353  // reanalyzed if we don't yet know if we can sink it or not.
4354  SmallVector<Instruction *, 8> InstsToReanalyze;
4355 
4356  // Returns true if a given use occurs in the predicated block. Phi nodes use
4357  // their operands in their corresponding predecessor blocks.
4358  auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4359  auto *I = cast<Instruction>(U.getUser());
4360  BasicBlock *BB = I->getParent();
4361  if (auto *Phi = dyn_cast<PHINode>(I))
4362  BB = Phi->getIncomingBlock(
4363  PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4364  return BB == PredBB;
4365  };
4366 
4367  // Iteratively sink the scalarized operands of the predicated instruction
4368  // into the block we created for it. When an instruction is sunk, it's
4369  // operands are then added to the worklist. The algorithm ends after one pass
4370  // through the worklist doesn't sink a single instruction.
4371  bool Changed;
4372  do {
4373 
4374  // Add the instructions that need to be reanalyzed to the worklist, and
4375  // reset the changed indicator.
4376  Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4377  InstsToReanalyze.clear();
4378  Changed = false;
4379 
4380  while (!Worklist.empty()) {
4381  auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4382 
4383  // We can't sink an instruction if it is a phi node, is already in the
4384  // predicated block, is not in the loop, or may have side effects.
4385  if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4386  !VectorLoop->contains(I) || I->mayHaveSideEffects())
4387  continue;
4388 
4389  // It's legal to sink the instruction if all its uses occur in the
4390  // predicated block. Otherwise, there's nothing to do yet, and we may
4391  // need to reanalyze the instruction.
4392  if (!all_of(I->uses(), isBlockOfUsePredicated)) {
4393  InstsToReanalyze.push_back(I);
4394  continue;
4395  }
4396 
4397  // Move the instruction to the beginning of the predicated block, and add
4398  // it's operands to the worklist.
4399  I->moveBefore(&*PredBB->getFirstInsertionPt());
4400  Worklist.insert(I->op_begin(), I->op_end());
4401 
4402  // The sinking may have enabled other instructions to be sunk, so we will
4403  // need to iterate.
4404  Changed = true;
4405  }
4406  } while (Changed);
4407 }
4408 
4411  assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
4412 
4413  // Look for cached value.
4414  std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
4415  EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
4416  if (ECEntryIt != EdgeMaskCache.end())
4417  return ECEntryIt->second;
4418 
4419  VectorParts SrcMask = createBlockInMask(Src);
4420 
4421  // The terminator has to be a branch inst!
4423  assert(BI && "Unexpected terminator found");
4424 
4425  if (!BI->isConditional())
4426  return EdgeMaskCache[Edge] = SrcMask;
4427 
4428  VectorParts EdgeMask(UF);
4429  for (unsigned Part = 0; Part < UF; ++Part) {
4430  auto *EdgeMaskPart = getOrCreateVectorValue(BI->getCondition(), Part);
4431  if (BI->getSuccessor(0) != Dst)
4432  EdgeMaskPart = Builder.CreateNot(EdgeMaskPart);
4433 
4434  if (SrcMask[Part]) // Otherwise block in-mask is all-one, no need to AND.
4435  EdgeMaskPart = Builder.CreateAnd(EdgeMaskPart, SrcMask[Part]);
4436 
4437  EdgeMask[Part] = EdgeMaskPart;
4438  }
4439 
4440  return EdgeMaskCache[Edge] = EdgeMask;
4441 }
4442 
4445  assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
4446 
4447  // Look for cached value.
4448  BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
4449  if (BCEntryIt != BlockMaskCache.end())
4450  return BCEntryIt->second;
4451 
4452  // All-one mask is modelled as no-mask following the convention for masked
4453  // load/store/gather/scatter. Initialize BlockMask to no-mask.
4454  VectorParts BlockMask(UF);
4455  for (unsigned Part = 0; Part < UF; ++Part)
4456  BlockMask[Part] = nullptr;
4457 
4458  // Loop incoming mask is all-one.
4459  if (OrigLoop->getHeader() == BB)
4460  return BlockMaskCache[BB] = BlockMask;
4461 
4462  // This is the block mask. We OR all incoming edges.
4463  for (auto *Predecessor : predecessors(BB)) {
4464  VectorParts EdgeMask = createEdgeMask(Predecessor, BB);
4465  if (!EdgeMask[0]) // Mask of predecessor is all-one so mask of block is too.
4466  return BlockMaskCache[BB] = EdgeMask;
4467 
4468  if (!BlockMask[0]) { // BlockMask has its initialized nullptr value.
4469  BlockMask = EdgeMask;
4470  continue;
4471  }
4472 
4473  for (unsigned Part = 0; Part < UF; ++Part)
4474  BlockMask[Part] = Builder.CreateOr(BlockMask[Part], EdgeMask[Part]);
4475  }
4476 
4477  return BlockMaskCache[BB] = BlockMask;
4478 }
4479 
4481  unsigned VF) {
4482  PHINode *P = cast<PHINode>(PN);
4483  // In order to support recurrences we need to be able to vectorize Phi nodes.
4484  // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4485  // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4486  // this value when we vectorize all of the instructions that use the PHI.
4487  if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4488  for (unsigned Part = 0; Part < UF; ++Part) {
4489  // This is phase one of vectorizing PHIs.
4490  Type *VecTy =
4491  (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4492  Value *EntryPart = PHINode::Create(
4493  VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4494  VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
4495  }
4496  return;
4497  }
4498 
4499  setDebugLocFromInst(Builder, P);
4500  // Check for PHI nodes that are lowered to vector selects.
4501  if (P->getParent() != OrigLoop->getHeader()) {
4502  // We know that all PHIs in non-header blocks are converted into
4503  // selects, so we don't have to worry about the insertion order and we
4504  // can just use the builder.
4505  // At this point we generate the predication tree. There may be
4506  // duplications since this is a simple recursive scan, but future
4507  // optimizations will clean it up.
4508 
4509  unsigned NumIncoming = P->getNumIncomingValues();
4510 
4511  // Generate a sequence of selects of the form:
4512  // SELECT(Mask3, In3,
4513  // SELECT(Mask2, In2,
4514  // ( ...)))
4515  VectorParts Entry(UF);
4516  for (unsigned In = 0; In < NumIncoming; In++) {
4517  VectorParts Cond =
4518  createEdgeMask(P->getIncomingBlock(In), P->getParent());
4519 
4520  for (unsigned Part = 0; Part < UF; ++Part) {
4521  Value *In0 = getOrCreateVectorValue(P->getIncomingValue(In), Part);
4522  assert((Cond[Part] || NumIncoming == 1) &&
4523  "Multiple predecessors with one predecessor having a full mask");
4524  if (In == 0)
4525  Entry[Part] = In0; // Initialize with the first incoming value.
4526  else
4527  // Select between the current value and the previous incoming edge
4528  // based on the incoming mask.
4529  Entry[Part] = Builder.CreateSelect(Cond[Part], In0, Entry[Part],
4530  "predphi");
4531  }
4532  }
4533  for (unsigned Part = 0; Part < UF; ++Part)
4534  VectorLoopValueMap.setVectorValue(P, Part, Entry[Part]);
4535  return;
4536  }
4537 
4538  // This PHINode must be an induction variable.
4539  // Make sure that we know about it.
4540  assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
4541 
4542  InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4543  const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4544 
4545  // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4546  // which can be found from the original scalar operations.
4547  switch (II.getKind()) {
4549  llvm_unreachable("Unknown induction");
4552  llvm_unreachable("Integer/fp induction is handled elsewhere.");
4554  // Handle the pointer induction variable case.
4555  assert(P->getType()->isPointerTy() && "Unexpected type.");
4556  // This is the normalized GEP that starts counting at zero.
4557  Value *PtrInd = Induction;
4558  PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4559  // Determine the number of scalars we need to generate for each unroll
4560  // iteration. If the instruction is uniform, we only need to generate the
4561  // first lane. Otherwise, we generate all VF values.
4562  unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4563  // These are the scalar results. Notice that we don't generate vector GEPs
4564  // because scalar GEPs result in better code.
4565  for (unsigned Part = 0; Part < UF; ++Part) {
4566  for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4567  Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
4568  Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4569  Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4570  SclrGep->setName("next.gep");
4571  VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
4572  }
4573  }
4574  return;
4575  }
4576  }
4577 }
4578 
4579 /// A helper function for checking whether an integer division-related
4580 /// instruction may divide by zero (in which case it must be predicated if
4581 /// executed conditionally in the scalar code).
4582 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4583 /// Non-zero divisors that are non compile-time constants will not be
4584 /// converted into multiplication, so we will still end up scalarizing
4585 /// the division, but can do so w/o predication.
4586 static bool mayDivideByZero(Instruction &I) {
4587  assert((I.getOpcode() == Instruction::UDiv ||
4588  I.getOpcode() == Instruction::SDiv ||
4589  I.getOpcode() == Instruction::URem ||
4590  I.getOpcode() == Instruction::SRem) &&
4591  "Unexpected instruction");
4592  Value *Divisor = I.getOperand(1);
4593  auto *CInt = dyn_cast<ConstantInt>(Divisor);
4594  return !CInt || CInt->isZero();
4595 }
4596 
4598  switch (I.getOpcode()) {
4599  case Instruction::Br:
4600  case Instruction::PHI:
4601  llvm_unreachable("This instruction is handled by a different recipe.");
4602  case Instruction::GetElementPtr: {
4603  // Construct a vector GEP by widening the operands of the scalar GEP as
4604  // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4605  // results in a vector of pointers when at least one operand of the GEP
4606  // is vector-typed. Thus, to keep the representation compact, we only use
4607  // vector-typed operands for loop-varying values.
4608  auto *GEP = cast<GetElementPtrInst>(&I);
4609 
4610  if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
4611  // If we are vectorizing, but the GEP has only loop-invariant operands,
4612  // the GEP we build (by only using vector-typed operands for
4613  // loop-varying values) would be a scalar pointer. Thus, to ensure we
4614  // produce a vector of pointers, we need to either arbitrarily pick an
4615  // operand to broadcast, or broadcast a clone of the original GEP.
4616  // Here, we broadcast a clone of the original.
4617  //
4618  // TODO: If at some point we decide to scalarize instructions having
4619  // loop-invariant operands, this special case will no longer be
4620  // required. We would add the scalarization decision to
4621  // collectLoopScalars() and teach getVectorValue() to broadcast
4622  // the lane-zero scalar value.
4623  auto *Clone = Builder.Insert(GEP->clone());
4624  for (unsigned Part = 0; Part < UF; ++Part) {
4625  Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4626  VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
4627  addMetadata(EntryPart, GEP);
4628  }
4629  } else {
4630  // If the GEP has at least one loop-varying operand, we are sure to
4631  // produce a vector of pointers. But if we are only unrolling, we want
4632  // to produce a scalar GEP for each unroll part. Thus, the GEP we
4633  // produce with the code below will be scalar (if VF == 1) or vector
4634  // (otherwise). Note that for the unroll-only case, we still maintain
4635  // values in the vector mapping with initVector, as we do for other
4636  // instructions.
4637  for (unsigned Part = 0; Part < UF; ++Part) {
4638 
4639  // The pointer operand of the new GEP. If it's loop-invariant, we
4640  // won't broadcast it.
4641  auto *Ptr =
4642  OrigLoop->isLoopInvariant(GEP->getPointerOperand())
4643  ? GEP->getPointerOperand()
4644  : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
4645 
4646  // Collect all the indices for the new GEP. If any index is
4647  // loop-invariant, we won't broadcast it.
4648  SmallVector<Value *, 4> Indices;
4649  for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
4650  if (OrigLoop->isLoopInvariant(U.get()))
4651  Indices.push_back(U.get());
4652  else
4653  Indices.push_back(getOrCreateVectorValue(U.get(), Part));
4654  }
4655 
4656  // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4657  // but it should be a vector, otherwise.
4658  auto *NewGEP = GEP->isInBounds()
4659  ? Builder.CreateInBoundsGEP(Ptr, Indices)
4660  : Builder.CreateGEP(Ptr, Indices);
4661  assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
4662  "NewGEP is not a pointer vector");
4663  VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
4664  addMetadata(NewGEP, GEP);
4665  }
4666  }
4667 
4668  break;
4669  }
4670  case Instruction::UDiv:
4671  case Instruction::SDiv:
4672  case Instruction::SRem:
4673  case Instruction::URem:
4674  case Instruction::Add:
4675  case Instruction::FAdd:
4676  case Instruction::Sub:
4677  case Instruction::FSub:
4678  case Instruction::Mul:
4679  case Instruction::FMul:
4680  case Instruction::FDiv:
4681  case Instruction::FRem:
4682  case Instruction::Shl:
4683  case Instruction::LShr:
4684  case Instruction::AShr:
4685  case Instruction::And:
4686  case Instruction::Or:
4687  case Instruction::Xor: {
4688  // Just widen binops.
4689  auto *BinOp = cast<BinaryOperator>(&I);
4690  setDebugLocFromInst(Builder, BinOp);
4691 
4692  for (unsigned Part = 0; Part < UF; ++Part) {
4693  Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
4694  Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
4695  Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
4696 
4697  if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4698  VecOp->copyIRFlags(BinOp);
4699 
4700  // Use this vector value for all users of the original instruction.
4701  VectorLoopValueMap.setVectorValue(&I, Part, V);
4702  addMetadata(V, BinOp);
4703  }
4704 
4705  break;
4706  }
4707  case Instruction::Select: {
4708  // Widen selects.
4709  // If the selector is loop invariant we can create a select
4710  // instruction with a scalar condition. Otherwise, use vector-select.
4711  auto *SE = PSE.getSE();
4712  bool InvariantCond =
4713  SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4714  setDebugLocFromInst(Builder, &I);
4715 
4716  // The condition can be loop invariant but still defined inside the
4717  // loop. This means that we can't just use the original 'cond' value.
4718  // We have to take the 'vectorized' value and pick the first lane.
4719  // Instcombine will make this a no-op.
4720 
4721  auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
4722 
4723  for (unsigned Part = 0; Part < UF; ++Part) {
4724  Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
4725  Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
4726  Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
4727  Value *Sel =
4728  Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
4729  VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4730  addMetadata(Sel, &I);
4731  }
4732 
4733  break;
4734  }
4735 
4736  case Instruction::ICmp:
4737  case Instruction::FCmp: {
4738  // Widen compares. Generate vector compares.
4739  bool FCmp = (I.getOpcode() == Instruction::FCmp);
4740  auto *Cmp = dyn_cast<CmpInst>(&I);
4741  setDebugLocFromInst(Builder, Cmp);
4742  for (unsigned Part = 0; Part < UF; ++Part) {
4743  Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
4744  Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
4745  Value *C = nullptr;
4746  if (FCmp) {
4747  // Propagate fast math flags.
4748  IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4749  Builder.setFastMathFlags(Cmp->getFastMathFlags());
4750  C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4751  } else {
4752  C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4753  }
4754  VectorLoopValueMap.setVectorValue(&I, Part, C);
4755  addMetadata(C, &I);
4756  }
4757 
4758  break;
4759  }
4760 
4761  case Instruction::Store:
4762  case Instruction::Load:
4763  vectorizeMemoryInstruction(&I);
4764  break;
4765  case Instruction::ZExt:
4766  case Instruction::SExt:
4767  case Instruction::FPToUI:
4768  case Instruction::FPToSI:
4769  case Instruction::FPExt:
4770  case Instruction::PtrToInt:
4771  case Instruction::IntToPtr:
4772  case Instruction::SIToFP:
4773  case Instruction::UIToFP:
4774  case Instruction::Trunc:
4775  case Instruction::FPTrunc:
4776  case Instruction::BitCast: {
4777  auto *CI = dyn_cast<CastInst>(&I);
4778  setDebugLocFromInst(Builder, CI);
4779 
4780  /// Vectorize casts.
4781  Type *DestTy =
4782  (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4783 
4784  for (unsigned Part = 0; Part < UF; ++Part) {
4785  Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4786  Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4787  VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4788  addMetadata(Cast, &I);
4789  }
4790  break;
4791  }
4792 
4793  case Instruction::Call: {
4794  // Ignore dbg intrinsics.
4795  if (isa<DbgInfoIntrinsic>(I))
4796  break;
4797  setDebugLocFromInst(Builder, &I);
4798 
4799  Module *M = I.getParent()->getParent()->getParent();
4800  auto *CI = cast<CallInst>(&I);
4801 
4802  StringRef FnName = CI->getCalledFunction()->getName();
4803  Function *F = CI->getCalledFunction();
4804  Type *RetTy = ToVectorTy(CI->getType(), VF);
4806  for (Value *ArgOperand : CI->arg_operands())
4807  Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4808 
4810 
4811  // The flag shows whether we use Intrinsic or a usual Call for vectorized
4812  // version of the instruction.
4813  // Is it beneficial to perform intrinsic call compared to lib call?
4814  bool NeedToScalarize;
4815  unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4816  bool UseVectorIntrinsic =
4817  ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4818  assert((UseVectorIntrinsic || !NeedToScalarize) &&
4819  "Instruction should be scalarized elsewhere.");
4820 
4821  for (unsigned Part = 0; Part < UF; ++Part) {
4823  for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4824  Value *Arg = CI->getArgOperand(i);
4825  // Some intrinsics have a scalar argument - don't replace it with a
4826  // vector.
4827  if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
4828  Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4829  Args.push_back(Arg);
4830  }
4831 
4832  Function *VectorF;
4833  if (UseVectorIntrinsic) {
4834  // Use vector version of the intrinsic.
4835  Type *TysForDecl[] = {CI->getType()};
4836  if (VF > 1)
4837  TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4838  VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4839  } else {
4840  // Use vector version of the library call.
4841  StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4842  assert(!VFnName.empty() && "Vector function name is empty.");
4843  VectorF = M->getFunction(VFnName);
4844  if (!VectorF) {
4845  // Generate a declaration
4846  FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4847  VectorF =
4848  Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4849  VectorF->copyAttributesFrom(F);
4850  }
4851  }
4852  assert(VectorF && "Can't create vector function.");
4853 
4855  CI->getOperandBundlesAsDefs(OpBundles);
4856  CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4857 
4858  if (isa<FPMathOperator>(V))
4859  V->copyFastMathFlags(CI);
4860 
4861  VectorLoopValueMap.setVectorValue(&I, Part, V);
4862  addMetadata(V, &I);
4863  }
4864 
4865  break;
4866  }
4867 
4868  default:
4869  // All other instructions are scalarized.
4870  DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4871  llvm_unreachable("Unhandled instruction!");
4872  } // end of switch.
4873 }
4874 
4876  // Forget the original basic block.
4877  PSE.getSE()->forgetLoop(OrigLoop);
4878 
4879  // Update the dominator tree information.
4880  assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
4881  "Entry does not dominate exit.");
4882 
4883  DT->addNewBlock(LoopMiddleBlock,
4884  LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4885  DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4886  DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4887  DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4888  DEBUG(DT->verifyDomTree());
4889 }
4890 
4891 /// \brief Check whether it is safe to if-convert this phi node.
4892 ///
4893 /// Phi nodes with constant expressions that can trap are not safe to if
4894 /// convert.
4896  for (Instruction &I : *BB) {
4897  auto *Phi = dyn_cast<PHINode>(&I);
4898  if (!Phi)
4899  return true;
4900  for (Value *V : Phi->incoming_values())
4901  if (auto *C = dyn_cast<Constant>(V))
4902  if (C->canTrap())
4903  return false;
4904  }
4905  return true;
4906 }
4907 
4908 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4909  if (!EnableIfConversion) {
4910  ORE->emit(createMissedAnalysis("IfConversionDisabled")
4911  << "if-conversion is disabled");
4912  return false;
4913  }
4914 
4915  assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
4916 
4917  // A list of pointers that we can safely read and write to.
4918  SmallPtrSet<Value *, 8> SafePointes;
4919 
4920  // Collect safe addresses.
4921  for (BasicBlock *BB : TheLoop->blocks()) {
4922  if (blockNeedsPredication(BB))
4923  continue;
4924 
4925  for (Instruction &I : *BB)
4926  if (auto *Ptr = getPointerOperand(&I))
4927  SafePointes.insert(Ptr);
4928  }
4929 
4930  // Collect the blocks that need predication.
4931  BasicBlock *Header = TheLoop->getHeader();
4932  for (BasicBlock *BB : TheLoop->blocks()) {
4933  // We don't support switch statements inside loops.
4934  if (!isa<BranchInst>(BB->getTerminator())) {
4935  ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
4936  << "loop contains a switch statement");
4937  return false;
4938  }
4939 
4940  // We must be able to predicate all blocks that need to be predicated.
4941  if (blockNeedsPredication(BB)) {
4942  if (!blockCanBePredicated(BB, SafePointes)) {
4943  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4944  << "control flow cannot be substituted for a select");
4945  return false;
4946  }
4947  } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4948  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4949  << "control flow cannot be substituted for a select");
4950  return false;
4951  }
4952  }
4953 
4954  // We can if-convert this loop.
4955  return true;
4956 }
4957 
4958 bool LoopVectorizationLegality::canVectorize() {
4959  // Store the result and return it at the end instead of exiting early, in case
4960  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
4961  bool Result = true;
4962 
4963  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
4964  if (DoExtraAnalysis)
4965  // We must have a loop in canonical form. Loops with indirectbr in them cannot
4966  // be canonicalized.
4967  if (!TheLoop->getLoopPreheader()) {
4968  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4969  << "loop control flow is not understood by vectorizer");
4970  if (DoExtraAnalysis)
4971  Result = false;
4972  else
4973  return false;
4974  }
4975 
4976  // FIXME: The code is currently dead, since the loop gets sent to
4977  // LoopVectorizationLegality is already an innermost loop.
4978  //
4979  // We can only vectorize innermost loops.
4980  if (!TheLoop->empty()) {
4981  ORE->emit(createMissedAnalysis("NotInnermostLoop")
4982  << "loop is not the innermost loop");
4983  if (DoExtraAnalysis)
4984  Result = false;
4985  else
4986  return false;
4987  }
4988 
4989  // We must have a single backedge.
4990  if (TheLoop->getNumBackEdges() != 1) {
4991  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4992  << "loop control flow is not understood by vectorizer");
4993  if (DoExtraAnalysis)
4994  Result = false;
4995  else
4996  return false;
4997  }
4998 
4999  // We must have a single exiting block.
5000  if (!TheLoop->getExitingBlock()) {
5001  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5002  << "loop control flow is not understood by vectorizer");
5003  if (DoExtraAnalysis)
5004  Result = false;
5005  else
5006  return false;
5007  }
5008 
5009  // We only handle bottom-tested loops, i.e. loop in which the condition is
5010  // checked at the end of each iteration. With that we can assume that all
5011  // instructions in the loop are executed the same number of times.
5012  if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5013  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5014  << "loop control flow is not understood by vectorizer");
5015  if (DoExtraAnalysis)
5016  Result = false;
5017  else
5018  return false;
5019  }
5020 
5021  // We need to have a loop header.
5022  DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
5023  << '\n');
5024 
5025  // Check if we can if-convert non-single-bb loops.
5026  unsigned NumBlocks = TheLoop->getNumBlocks();
5027  if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
5028  DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
5029  if (DoExtraAnalysis)
5030  Result = false;
5031  else
5032  return false;
5033  }
5034 
5035  // Check if we can vectorize the instructions and CFG in this loop.
5036  if (!canVectorizeInstrs()) {
5037  DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
5038  if (DoExtraAnalysis)
5039  Result = false;
5040  else
5041  return false;
5042  }
5043 
5044  // Go over each instruction and look at memory deps.
5045  if (!canVectorizeMemory()) {
5046  DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
5047  if (DoExtraAnalysis)
5048  Result = false;
5049  else
5050  return false;
5051  }
5052 
5053  DEBUG(dbgs() << "LV: We can vectorize this loop"
5054  << (LAI->getRuntimePointerChecking()->Need
5055  ? " (with a runtime bound check)"
5056  : "")
5057  << "!\n");
5058 
5059  bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
5060 
5061  // If an override option has been passed in for interleaved accesses, use it.
5062  if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
5063  UseInterleaved = EnableInterleavedMemAccesses;
5064 
5065  // Analyze interleaved memory accesses.
5066  if (UseInterleaved)
5067  InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
5068 
5069  unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
5070  if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
5071  SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
5072 
5073  if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
5074  ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
5075  << "Too many SCEV assumptions need to be made and checked "
5076  << "at runtime");
5077  DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
5078  if (DoExtraAnalysis)
5079  Result = false;
5080  else
5081  return false;
5082  }
5083 
5084  // Okay! We've done all the tests. If any have failed, return false. Otherwise
5085  // we can vectorize, and at this point we don't have any other mem analysis
5086  // which may limit our maximum vectorization factor, so just return true with
5087  // no restrictions.
5088  return Result;
5089 }
5090 
5092  if (Ty->isPointerTy())
5093  return DL.getIntPtrType(Ty);
5094 
5095  // It is possible that char's or short's overflow when we ask for the loop's
5096  // trip count, work around this by changing the type size.
5097  if (Ty->getScalarSizeInBits() < 32)
5098  return Type::getInt32Ty(Ty->getContext());
5099 
5100  return Ty;
5101 }
5102 
5103 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
5104  Ty0 = convertPointerToIntegerType(DL, Ty0);
5105  Ty1 = convertPointerToIntegerType(DL, Ty1);
5106  if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
5107  return Ty0;
5108  return Ty1;
5109 }
5110 
5111 /// \brief Check that the instruction has outside loop users and is not an
5112 /// identified reduction variable.
5113 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
5114  SmallPtrSetImpl<Value *> &AllowedExit) {
5115  // Reduction and Induction instructions are allowed to have exit users. All
5116  // other instructions must not have external users.
5117  if (!AllowedExit.count(Inst))
5118  // Check that all of the users of the loop are inside the BB.
5119  for (User *U : Inst->users()) {
5120  Instruction *UI = cast<Instruction>(U);
5121  // This user may be a reduction exit value.
5122  if (!TheLoop->contains(UI)) {
5123  DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
5124  return true;
5125  }
5126  }
5127  return false;
5128 }
5129 
5130 void LoopVectorizationLegality::addInductionPhi(
5131  PHINode *Phi, const InductionDescriptor &ID,
5132  SmallPtrSetImpl<Value *> &AllowedExit) {
5133  Inductions[Phi] = ID;
5134  Type *PhiTy = Phi->getType();
5135  const DataLayout &DL = Phi->getModule()->getDataLayout();
5136 
5137  // Get the widest type.
5138  if (!PhiTy->isFloatingPointTy()) {
5139  if (!WidestIndTy)
5140  WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
5141  else
5142  WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
5143  }
5144 
5145  // Int inductions are special because we only allow one IV.
5147  ID.getConstIntStepValue() &&
5148  ID.getConstIntStepValue()->isOne() &&
5149  isa<Constant>(ID.getStartValue()) &&
5150  cast<Constant>(ID.getStartValue())->isNullValue()) {
5151 
5152  // Use the phi node with the widest type as induction. Use the last
5153  // one if there are multiple (no good reason for doing this other
5154  // than it is expedient). We've checked that it begins at zero and
5155  // steps by one, so this is a canonical induction variable.
5156  if (!PrimaryInduction || PhiTy == WidestIndTy)
5157  PrimaryInduction = Phi;
5158  }
5159 
5160  // Both the PHI node itself, and the "post-increment" value feeding
5161  // back into the PHI node may have external users.
5162  // We can allow those uses, except if the SCEVs we have for them rely
5163  // on predicates that only hold within the loop, since allowing the exit
5164  // currently means re-using this SCEV outside the loop.
5165  if (PSE.getUnionPredicate().isAlwaysTrue()) {
5166  AllowedExit.insert(Phi);
5167  AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
5168  }
5169 
5170  DEBUG(dbgs() << "LV: Found an induction variable.\n");
5171  return;
5172 }
5173 
5174 bool LoopVectorizationLegality::canVectorizeInstrs() {
5175  BasicBlock *Header = TheLoop->getHeader();
5176 
5177  // Look for the attribute signaling the absence of NaNs.
5178  Function &F = *Header->getParent();
5179  HasFunNoNaNAttr =
5180  F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
5181 
5182  // For each block in the loop.
5183  for (BasicBlock *BB : TheLoop->blocks()) {
5184  // Scan the instructions in the block and look for hazards.
5185  for (Instruction &I : *BB) {
5186  if (auto *Phi = dyn_cast<PHINode>(&I)) {
5187  Type *PhiTy = Phi->getType();
5188  // Check that this PHI type is allowed.
5189  if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
5190  !PhiTy->isPointerTy()) {
5191  ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5192  << "loop control flow is not understood by vectorizer");
5193  DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
5194  return false;
5195  }
5196 
5197  // If this PHINode is not in the header block, then we know that we
5198  // can convert it to select during if-conversion. No need to check if
5199  // the PHIs in this block are induction or reduction variables.
5200  if (BB != Header) {
5201  // Check that this instruction has no outside users or is an
5202  // identified reduction value with an outside user.
5203  if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
5204  continue;
5205  ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi)
5206  << "value could not be identified as "
5207  "an induction or reduction variable");
5208  return false;
5209  }
5210 
5211  // We only allow if-converted PHIs with exactly two incoming values.
5212  if (Phi->getNumIncomingValues() != 2) {
5213  ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5214  << "control flow not understood by vectorizer");
5215  DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
5216  return false;
5217  }
5218 
5219  RecurrenceDescriptor RedDes;
5220  if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
5221  if (RedDes.hasUnsafeAlgebra())
5222  Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
5223  AllowedExit.insert(RedDes.getLoopExitInstr());
5224  Reductions[Phi] = RedDes;
5225  continue;
5226  }
5227 
5229  if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
5230  addInductionPhi(Phi, ID, AllowedExit);
5231  if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
5232  Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
5233  continue;
5234  }
5235 
5237  SinkAfter, DT)) {
5238  FirstOrderRecurrences.insert(Phi);
5239  continue;
5240  }
5241 
5242  // As a last resort, coerce the PHI to a AddRec expression
5243  // and re-try classifying it a an induction PHI.
5244  if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
5245  addInductionPhi(Phi, ID, AllowedExit);
5246  continue;
5247  }
5248 
5249  ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
5250  << "value that could not be identified as "
5251  "reduction is used outside the loop");
5252  DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
5253  return false;
5254  } // end of PHI handling
5255 
5256  // We handle calls that:
5257  // * Are debug info intrinsics.
5258  // * Have a mapping to an IR intrinsic.
5259  // * Have a vector version available.
5260  auto *CI = dyn_cast<CallInst>(&I);
5261  if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
5262  !isa<DbgInfoIntrinsic>(CI) &&
5263  !(CI->getCalledFunction() && TLI &&
5264  TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5265  ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
5266  << "call instruction cannot be vectorized");
5267  DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
5268  return false;
5269  }
5270 
5271  // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
5272  // second argument is the same (i.e. loop invariant)
5273  if (CI && hasVectorInstrinsicScalarOpd(
5274  getVectorIntrinsicIDForCall(CI, TLI), 1)) {
5275  auto *SE = PSE.getSE();
5276  if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
5277  ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
5278  << "intrinsic instruction cannot be vectorized");
5279  DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
5280  return false;
5281  }
5282  }
5283 
5284  // Check that the instruction return type is vectorizable.
5285  // Also, we can't vectorize extractelement instructions.
5287  !I.getType()->isVoidTy()) ||
5288  isa<ExtractElementInst>(I)) {
5289  ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
5290  << "instruction return type cannot be vectorized");
5291  DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
5292  return false;
5293  }
5294 
5295  // Check that the stored type is vectorizable.
5296  if (auto *ST = dyn_cast<StoreInst>(&I)) {
5297  Type *T = ST->getValueOperand()->getType();
5299  ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
5300  << "store instruction cannot be vectorized");
5301  return false;
5302  }
5303 
5304  // FP instructions can allow unsafe algebra, thus vectorizable by
5305  // non-IEEE-754 compliant SIMD units.
5306  // This applies to floating-point math operations and calls, not memory
5307  // operations, shuffles, or casts, as they don't change precision or
5308  // semantics.
5309  } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
5310  !I.hasUnsafeAlgebra()) {
5311  DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
5312  Hints->setPotentiallyUnsafe();
5313  }
5314 
5315  // Reduction instructions are allowed to have exit users.
5316  // All other instructions must not have external users.
5317  if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
5318  ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
5319  << "value cannot be used outside the loop");
5320  return false;
5321  }
5322 
5323  } // next instr.
5324  }
5325 
5326  if (!PrimaryInduction) {
5327  DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
5328  if (Inductions.empty()) {
5329  ORE->emit(createMissedAnalysis("NoInductionVariable")
5330  << "loop induction variable could not be identified");
5331  return false;
5332  }
5333  }
5334 
5335  // Now we know the widest induction type, check if our found induction
5336  // is the same size. If it's not, unset it here and InnerLoopVectorizer
5337  // will create another.
5338  if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5339  PrimaryInduction = nullptr;
5340 
5341  return true;
5342 }
5343 
5344 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
5345 
5346  // We should not collect Scalars more than once per VF. Right now, this
5347  // function is called from collectUniformsAndScalars(), which already does
5348  // this check. Collecting Scalars for VF=1 does not make any sense.
5349  assert(VF >= 2 && !Scalars.count(VF) &&
5350  "This function should not be visited twice for the same VF");
5351 
5353 
5354  // These sets are used to seed the analysis with pointers used by memory
5355  // accesses that will remain scalar.
5357  SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5358 
5359  // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5360  // The pointer operands of loads and stores will be scalar as long as the
5361  // memory access is not a gather or scatter operation. The value operand of a
5362  // store will remain scalar if the store is scalarized.
5363  auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5364  InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5365  assert(WideningDecision != CM_Unknown &&
5366  "Widening decision should be ready at this moment");
5367  if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5368  if (Ptr == Store->getValueOperand())
5369  return WideningDecision == CM_Scalarize;
5370  assert(Ptr == getPointerOperand(MemAccess) &&
5371  "Ptr is neither a value or pointer operand");
5372  return WideningDecision != CM_GatherScatter;
5373  };
5374 
5375  // A helper that returns true if the given value is a bitcast or
5376  // getelementptr instruction contained in the loop.
5377  auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5378  return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5379  isa<GetElementPtrInst>(V)) &&
5380  !TheLoop->isLoopInvariant(V);
5381  };
5382 
5383  // A helper that evaluates a memory access's use of a pointer. If the use
5384  // will be a scalar use, and the pointer is only used by memory accesses, we
5385  // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
5386  // PossibleNonScalarPtrs.
5387  auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5388 
5389  // We only care about bitcast and getelementptr instructions contained in
5390  // the loop.
5391  if (!isLoopVaryingBitCastOrGEP(Ptr))
5392  return;
5393 
5394  // If the pointer has already been identified as scalar (e.g., if it was
5395  // also identified as uniform), there's nothing to do.
5396  auto *I = cast<Instruction>(Ptr);
5397  if (Worklist.count(I))
5398  return;
5399 
5400  // If the use of the pointer will be a scalar use, and all users of the
5401  // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5402  // place the pointer in PossibleNonScalarPtrs.
5403  if (isScalarUse(MemAccess, Ptr) && all_of(I->users(), [&](User *U) {
5404  return isa<LoadInst>(U) || isa<StoreInst>(U);
5405  }))
5406  ScalarPtrs.insert(I);
5407  else
5408  PossibleNonScalarPtrs.insert(I);
5409  };
5410 
5411  // We seed the scalars analysis with three classes of instructions: (1)
5412  // instructions marked uniform-after-vectorization, (2) bitcast and
5413  // getelementptr instructions used by memory accesses requiring a scalar use,
5414  // and (3) pointer induction variables and their update instructions (we
5415  // currently only scalarize these).
5416  //
5417  // (1) Add to the worklist all instructions that have been identified as
5418  // uniform-after-vectorization.
5419  Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5420 
5421  // (2) Add to the worklist all bitcast and getelementptr instructions used by
5422  // memory accesses requiring a scalar use. The pointer operands of loads and
5423  // stores will be scalar as long as the memory accesses is not a gather or
5424  // scatter operation. The value operand of a store will remain scalar if the
5425  // store is scalarized.
5426  for (auto *BB : TheLoop->blocks())
5427  for (auto &I : *BB) {
5428  if (auto *Load = dyn_cast<LoadInst>(&I)) {
5429  evaluatePtrUse(Load, Load->getPointerOperand());
5430  } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5431  evaluatePtrUse(Store, Store->getPointerOperand());
5432  evaluatePtrUse(Store, Store->getValueOperand());
5433  }
5434  }
5435  for (auto *I : ScalarPtrs)
5436  if (!PossibleNonScalarPtrs.count(I)) {
5437  DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5438  Worklist.insert(I);
5439  }
5440 
5441  // (3) Add to the worklist all pointer induction variables and their update
5442  // instructions.
5443  //
5444  // TODO: Once we are able to vectorize pointer induction variables we should
5445  // no longer insert them into the worklist here.
5446  auto *Latch = TheLoop->getLoopLatch();
5447  for (auto &Induction : *Legal->getInductionVars()) {
5448  auto *Ind = Induction.first;
5449  auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5450  if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
5451  continue;
5452  Worklist.insert(Ind);
5453  Worklist.insert(IndUpdate);
5454  DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5455  DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5456  }
5457 
5458  // Insert the forced scalars.
5459  // FIXME: Currently widenPHIInstruction() often creates a dead vector
5460  // induction variable when the PHI user is scalarized.
5461  if (ForcedScalars.count(VF))
5462  for (auto *I : ForcedScalars.find(VF)->second)
5463  Worklist.insert(I);
5464 
5465  // Expand the worklist by looking through any bitcasts and getelementptr
5466  // instructions we've already identified as scalar. This is similar to the
5467  // expansion step in collectLoopUniforms(); however, here we're only
5468  // expanding to include additional bitcasts and getelementptr instructions.
5469  unsigned Idx = 0;
5470  while (Idx != Worklist.size()) {
5471  Instruction *Dst = Worklist[Idx++];
5472  if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5473  continue;
5474  auto *Src = cast<Instruction>(Dst->getOperand(0));
5475  if (all_of(Src->users(), [&](User *U) -> bool {
5476  auto *J = cast<Instruction>(U);
5477  return !TheLoop->contains(J) || Worklist.count(J) ||
5478  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5479  isScalarUse(J, Src));
5480  })) {
5481  Worklist.insert(Src);
5482  DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5483  }
5484  }
5485 
5486  // An induction variable will remain scalar if all users of the induction
5487  // variable and induction variable update remain scalar.
5488  for (auto &Induction : *Legal->getInductionVars()) {
5489  auto *Ind = Induction.first;
5490  auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5491 
5492  // We already considered pointer induction variables, so there's no reason
5493  // to look at their users again.
5494  //
5495  // TODO: Once we are able to vectorize pointer induction variables we
5496  // should no longer skip over them here.
5497  if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
5498  continue;
5499 
5500  // Determine if all users of the induction variable are scalar after
5501  // vectorization.
5502  auto ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
5503  auto *I = cast<Instruction>(U);
5504  return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5505  });
5506  if (!ScalarInd)
5507  continue;
5508 
5509  // Determine if all users of the induction variable update instruction are
5510  // scalar after vectorization.
5511  auto ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5512  auto *I = cast<Instruction>(U);
5513  return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5514  });
5515  if (!ScalarIndUpdate)
5516  continue;
5517 
5518  // The induction variable and its update instruction will remain scalar.
5519  Worklist.insert(Ind);
5520  Worklist.insert(IndUpdate);
5521  DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5522  DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5523  }
5524 
5525  Scalars[VF].insert(Worklist.begin(), Worklist.end());
5526 }
5527 
5528 bool LoopVectorizationLegality::isScalarWithPredication(Instruction *I) {
5529  if (!blockNeedsPredication(I->getParent()))
5530  return false;
5531  switch(I->getOpcode()) {
5532  default:
5533  break;
5534  case Instruction::Store:
5535  return !isMaskRequired(I);
5536  case Instruction::UDiv:
5537  case Instruction::SDiv:
5538  case Instruction::SRem:
5539  case Instruction::URem:
5540  return mayDivideByZero(*I);
5541  }
5542  return false;
5543 }
5544 
5545 bool LoopVectorizationLegality::memoryInstructionCanBeWidened(Instruction *I,
5546  unsigned VF) {
5547  // Get and ensure we have a valid memory instruction.
5548  LoadInst *LI = dyn_cast<LoadInst>(I);
5550  assert((LI || SI) && "Invalid memory instruction");
5551 
5552  auto *Ptr = getPointerOperand(I);
5553 
5554  // In order to be widened, the pointer should be consecutive, first of all.
5555  if (!isConsecutivePtr(Ptr))
5556  return false;
5557 
5558  // If the instruction is a store located in a predicated block, it will be
5559  // scalarized.
5560  if (isScalarWithPredication(I))
5561  return false;
5562 
5563  // If the instruction's allocated size doesn't equal it's type size, it
5564  // requires padding and will be scalarized.
5565  auto &DL = I->getModule()->getDataLayout();
5566  auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5567  if (hasIrregularType(ScalarTy, DL, VF))
5568  return false;
5569 
5570  return true;
5571 }
5572 
5573 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
5574 
5575  // We should not collect Uniforms more than once per VF. Right now,
5576  // this function is called from collectUniformsAndScalars(), which
5577  // already does this check. Collecting Uniforms for VF=1 does not make any
5578  // sense.
5579 
5580  assert(VF >= 2 && !Uniforms.count(VF) &&
5581  "This function should not be visited twice for the same VF");
5582 
5583  // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5584  // not analyze again. Uniforms.count(VF) will return 1.
5585  Uniforms[VF].clear();
5586 
5587  // We now know that the loop is vectorizable!
5588  // Collect instructions inside the loop that will remain uniform after
5589  // vectorization.
5590 
5591  // Global values, params and instructions outside of current loop are out of
5592  // scope.
5593  auto isOutOfScope = [&](Value *V) -> bool {
5594  Instruction *I = dyn_cast<Instruction>(V);
5595  return (!I || !TheLoop->contains(I));
5596  };
5597 
5598  SetVector<Instruction *> Worklist;
5599  BasicBlock *Latch = TheLoop->getLoopLatch();
5600 
5601  // Start with the conditional branch. If the branch condition is an
5602  // instruction contained in the loop that is only used by the branch, it is
5603  // uniform.
5604  auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5605  if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
5606  Worklist.insert(Cmp);
5607  DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
5608  }
5609 
5610  // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5611  // are pointers that are treated like consecutive pointers during
5612  // vectorization. The pointer operands of interleaved accesses are an
5613  // example.
5614  SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5615 
5616  // Holds pointer operands of instructions that are possibly non-uniform.
5617  SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5618 
5619  auto isUniformDecision = [&](Instruction *I, unsigned VF) {
5620  InstWidening WideningDecision = getWideningDecision(I, VF);
5621  assert(WideningDecision != CM_Unknown &&
5622  "Widening decision should be ready at this moment");
5623 
5624  return (WideningDecision == CM_Widen ||
5625  WideningDecision == CM_Interleave);
5626  };
5627  // Iterate over the instructions in the loop, and collect all
5628  // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5629  // that a consecutive-like pointer operand will be scalarized, we collect it
5630  // in PossibleNonUniformPtrs instead. We use two sets here because a single
5631  // getelementptr instruction can be used by both vectorized and scalarized
5632  // memory instructions. For example, if a loop loads and stores from the same
5633  // location, but the store is conditional, the store will be scalarized, and
5634  // the getelementptr won't remain uniform.
5635  for (auto *BB : TheLoop->blocks())
5636  for (auto &I : *BB) {
5637 
5638  // If there's no pointer operand, there's nothing to do.
5639  auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I));
5640  if (!Ptr)
5641  continue;
5642 
5643  // True if all users of Ptr are memory accesses that have Ptr as their
5644  // pointer operand.
5645  auto UsersAreMemAccesses = all_of(Ptr->users(), [&](User *U) -> bool {
5646  return getPointerOperand(U) == Ptr;
5647  });
5648 
5649  // Ensure the memory instruction will not be scalarized or used by
5650  // gather/scatter, making its pointer operand non-uniform. If the pointer
5651  // operand is used by any instruction other than a memory access, we
5652  // conservatively assume the pointer operand may be non-uniform.
5653  if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5654  PossibleNonUniformPtrs.insert(Ptr);
5655 
5656  // If the memory instruction will be vectorized and its pointer operand
5657  // is consecutive-like, or interleaving - the pointer operand should
5658  // remain uniform.
5659  else
5660  ConsecutiveLikePtrs.insert(Ptr);
5661  }
5662 
5663  // Add to the Worklist all consecutive and consecutive-like pointers that
5664  // aren't also identified as possibly non-uniform.
5665  for (auto *V : ConsecutiveLikePtrs)
5666  if (!PossibleNonUniformPtrs.count(V)) {
5667  DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
5668  Worklist.insert(V);
5669  }
5670 
5671  // Expand Worklist in topological order: whenever a new instruction
5672  // is added , its users should be either already inside Worklist, or
5673  // out of scope. It ensures a uniform instruction will only be used
5674  // by uniform instructions or out of scope instructions.
5675  unsigned idx = 0;
5676  while (idx != Worklist.size()) {
5677  Instruction *I = Worklist[idx++];
5678 
5679  for (auto OV : I->operand_values()) {
5680  if (isOutOfScope(OV))
5681  continue;
5682  auto *OI = cast<Instruction>(OV);
5683  if (all_of(OI->users(), [&](User *U) -> bool {
5684  auto *J = cast<Instruction>(U);
5685  return !TheLoop->contains(J) || Worklist.count(J) ||
5686  (OI == getPointerOperand(J) && isUniformDecision(J, VF));
5687  })) {
5688  Worklist.insert(OI);
5689  DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
5690  }
5691  }
5692  }
5693 
5694  // Returns true if Ptr is the pointer operand of a memory access instruction
5695  // I, and I is known to not require scalarization.
5696  auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5697  return getPointerOperand(I) == Ptr && isUniformDecision(I, VF);
5698  };
5699 
5700  // For an instruction to be added into Worklist above, all its users inside
5701  // the loop should also be in Worklist. However, this condition cannot be
5702  // true for phi nodes that form a cyclic dependence. We must process phi
5703  // nodes separately. An induction variable will remain uniform if all users
5704  // of the induction variable and induction variable update remain uniform.
5705  // The code below handles both pointer and non-pointer induction variables.
5706  for (auto &Induction : *Legal->getInductionVars()) {
5707  auto *Ind = Induction.first;
5708  auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5709 
5710  // Determine if all users of the induction variable are uniform after
5711  // vectorization.
5712  auto UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
5713  auto *I = cast<Instruction>(U);
5714  return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5715  isVectorizedMemAccessUse(I, Ind);
5716  });
5717  if (!UniformInd)
5718  continue;
5719 
5720  // Determine if all users of the induction variable update instruction are
5721  // uniform after vectorization.
5722  auto UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5723  auto *I = cast<Instruction>(U);
5724  return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5725  isVectorizedMemAccessUse(I, IndUpdate);
5726  });
5727  if (!UniformIndUpdate)
5728  continue;
5729 
5730  // The induction variable and its update instruction will remain uniform.
5731  Worklist.insert(Ind);
5732  Worklist.insert(IndUpdate);
5733  DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
5734  DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n");
5735  }
5736 
5737  Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5738 }
5739 
5740 bool LoopVectorizationLegality::canVectorizeMemory() {
5741  LAI = &(*GetLAA)(*TheLoop);
5742  InterleaveInfo.setLAI(LAI);
5743  const OptimizationRemarkAnalysis *LAR = LAI->getReport();
5744  if (LAR) {
5745  OptimizationRemarkAnalysis VR(Hints->vectorizeAnalysisPassName(),
5746  "loop not vectorized: ", *LAR);