LLVM  9.0.0svn
LoopVectorizationLegality.cpp
Go to the documentation of this file.
1 //===- LoopVectorizationLegality.cpp --------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides loop vectorization legality analysis. Original code
10 // resided in LoopVectorize.cpp for a long time.
11 //
12 // At this point, it is implemented as a utility class, not as an analysis
13 // pass. It should be easy to create an analysis pass around it if there
14 // is a need (but D45420 needs to happen first).
15 //
18 #include "llvm/IR/IntrinsicInst.h"
19 
20 using namespace llvm;
21 
22 #define LV_NAME "loop-vectorize"
23 #define DEBUG_TYPE LV_NAME
24 
26 
27 static cl::opt<bool>
28  EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
29  cl::desc("Enable if-conversion during vectorization."));
30 
32  "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
33  cl::desc("The maximum allowed number of runtime memory checks with a "
34  "vectorize(enable) pragma."));
35 
37  "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
38  cl::desc("The maximum number of SCEV checks allowed."));
39 
41  "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
42  cl::desc("The maximum number of SCEV checks allowed with a "
43  "vectorize(enable) pragma"));
44 
45 /// Maximum vectorization interleave count.
46 static const unsigned MaxInterleaveFactor = 16;
47 
48 namespace llvm {
49 
51  StringRef RemarkName,
52  Loop *TheLoop,
53  Instruction *I) {
54  Value *CodeRegion = TheLoop->getHeader();
55  DebugLoc DL = TheLoop->getStartLoc();
56 
57  if (I) {
58  CodeRegion = I->getParent();
59  // If there is no debug location attached to the instruction, revert back to
60  // using the loop's.
61  if (I->getDebugLoc())
62  DL = I->getDebugLoc();
63  }
64 
65  OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
66  R << "loop not vectorized: ";
67  return R;
68 }
69 
70 bool LoopVectorizeHints::Hint::validate(unsigned Val) {
71  switch (Kind) {
72  case HK_WIDTH:
73  return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
74  case HK_UNROLL:
75  return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
76  case HK_FORCE:
77  return (Val <= 1);
78  case HK_ISVECTORIZED:
79  return (Val == 0 || Val == 1);
80  }
81  return false;
82 }
83 
85  bool InterleaveOnlyWhenForced,
87  : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
88  Interleave("interleave.count", InterleaveOnlyWhenForced, HK_UNROLL),
89  Force("vectorize.enable", FK_Undefined, HK_FORCE),
90  IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) {
91  // Populate values with existing loop metadata.
92  getHintsFromMetadata();
93 
94  // force-vector-interleave overrides DisableInterleaving.
97 
98  if (IsVectorized.Value != 1)
99  // If the vectorization width and interleaving count are both 1 then
100  // consider the loop to have been already vectorized because there's
101  // nothing more that we can do.
102  IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
103  LLVM_DEBUG(if (InterleaveOnlyWhenForced && Interleave.Value == 1) dbgs()
104  << "LV: Interleaving disabled by the pass manager\n");
105 }
106 
108  LLVMContext &Context = TheLoop->getHeader()->getContext();
109 
110  MDNode *IsVectorizedMD = MDNode::get(
111  Context,
112  {MDString::get(Context, "llvm.loop.isvectorized"),
113  ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
114  MDNode *LoopID = TheLoop->getLoopID();
115  MDNode *NewLoopID =
116  makePostTransformationMetadata(Context, LoopID,
117  {Twine(Prefix(), "vectorize.").str(),
118  Twine(Prefix(), "interleave.").str()},
119  {IsVectorizedMD});
120  TheLoop->setLoopID(NewLoopID);
121 
122  // Update internal cache.
123  IsVectorized.Value = 1;
124 }
125 
127  Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
129  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
131  return false;
132  }
133 
134  if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
135  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
137  return false;
138  }
139 
140  if (getIsVectorized() == 1) {
141  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
142  // FIXME: Add interleave.disable metadata. This will allow
143  // vectorize.disable to be used without disabling the pass and errors
144  // to differentiate between disabled vectorization and a width of 1.
145  ORE.emit([&]() {
147  "AllDisabled", L->getStartLoc(),
148  L->getHeader())
149  << "loop not vectorized: vectorization and interleaving are "
150  "explicitly disabled, or the loop has already been "
151  "vectorized";
152  });
153  return false;
154  }
155 
156  return true;
157 }
158 
160  using namespace ore;
161 
162  ORE.emit([&]() {
163  if (Force.Value == LoopVectorizeHints::FK_Disabled)
164  return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
165  TheLoop->getStartLoc(),
166  TheLoop->getHeader())
167  << "loop not vectorized: vectorization is explicitly disabled";
168  else {
169  OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
170  TheLoop->getStartLoc(), TheLoop->getHeader());
171  R << "loop not vectorized";
172  if (Force.Value == LoopVectorizeHints::FK_Enabled) {
173  R << " (Force=" << NV("Force", true);
174  if (Width.Value != 0)
175  R << ", Vector Width=" << NV("VectorWidth", Width.Value);
176  if (Interleave.Value != 0)
177  R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
178  R << ")";
179  }
180  return R;
181  }
182  });
183 }
184 
186  if (getWidth() == 1)
187  return LV_NAME;
189  return LV_NAME;
191  return LV_NAME;
193 }
194 
195 void LoopVectorizeHints::getHintsFromMetadata() {
196  MDNode *LoopID = TheLoop->getLoopID();
197  if (!LoopID)
198  return;
199 
200  // First operand should refer to the loop id itself.
201  assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
202  assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
203 
204  for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
205  const MDString *S = nullptr;
207 
208  // The expected hint is either a MDString or a MDNode with the first
209  // operand a MDString.
210  if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
211  if (!MD || MD->getNumOperands() == 0)
212  continue;
213  S = dyn_cast<MDString>(MD->getOperand(0));
214  for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
215  Args.push_back(MD->getOperand(i));
216  } else {
217  S = dyn_cast<MDString>(LoopID->getOperand(i));
218  assert(Args.size() == 0 && "too many arguments for MDString");
219  }
220 
221  if (!S)
222  continue;
223 
224  // Check if the hint starts with the loop metadata prefix.
225  StringRef Name = S->getString();
226  if (Args.size() == 1)
227  setHint(Name, Args[0]);
228  }
229 }
230 
231 void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
232  if (!Name.startswith(Prefix()))
233  return;
234  Name = Name.substr(Prefix().size(), StringRef::npos);
235 
236  const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
237  if (!C)
238  return;
239  unsigned Val = C->getZExtValue();
240 
241  Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
242  for (auto H : Hints) {
243  if (Name == H->Name) {
244  if (H->validate(Val))
245  H->Value = Val;
246  else
247  LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
248  break;
249  }
250  }
251 }
252 
254  Function *F, Loop *L, const LoopVectorizeHints &Hints) {
255  const char *PassName = Hints.vectorizeAnalysisPassName();
256  bool Failed = false;
257  if (UnsafeAlgebraInst && !Hints.allowReordering()) {
258  ORE.emit([&]() {
260  PassName, "CantReorderFPOps", UnsafeAlgebraInst->getDebugLoc(),
261  UnsafeAlgebraInst->getParent())
262  << "loop not vectorized: cannot prove it is safe to reorder "
263  "floating-point operations";
264  });
265  Failed = true;
266  }
267 
268  // Test if runtime memcheck thresholds are exceeded.
269  bool PragmaThresholdReached =
270  NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
271  bool ThresholdReached =
272  NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
273  if ((ThresholdReached && !Hints.allowReordering()) ||
274  PragmaThresholdReached) {
275  ORE.emit([&]() {
276  return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
277  L->getStartLoc(),
278  L->getHeader())
279  << "loop not vectorized: cannot prove it is safe to reorder "
280  "memory operations";
281  });
282  LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
283  Failed = true;
284  }
285 
286  return Failed;
287 }
288 
289 // Return true if the inner loop \p Lp is uniform with regard to the outer loop
290 // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
291 // executing the inner loop will execute the same iterations). This check is
292 // very constrained for now but it will be relaxed in the future. \p Lp is
293 // considered uniform if it meets all the following conditions:
294 // 1) it has a canonical IV (starting from 0 and with stride 1),
295 // 2) its latch terminator is a conditional branch and,
296 // 3) its latch condition is a compare instruction whose operands are the
297 // canonical IV and an OuterLp invariant.
298 // This check doesn't take into account the uniformity of other conditions not
299 // related to the loop latch because they don't affect the loop uniformity.
300 //
301 // NOTE: We decided to keep all these checks and its associated documentation
302 // together so that we can easily have a picture of the current supported loop
303 // nests. However, some of the current checks don't depend on \p OuterLp and
304 // would be redundantly executed for each \p Lp if we invoked this function for
305 // different candidate outer loops. This is not the case for now because we
306 // don't currently have the infrastructure to evaluate multiple candidate outer
307 // loops and \p OuterLp will be a fixed parameter while we only support explicit
308 // outer loop vectorization. It's also very likely that these checks go away
309 // before introducing the aforementioned infrastructure. However, if this is not
310 // the case, we should move the \p OuterLp independent checks to a separate
311 // function that is only executed once for each \p Lp.
312 static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
313  assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
314 
315  // If Lp is the outer loop, it's uniform by definition.
316  if (Lp == OuterLp)
317  return true;
318  assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
319 
320  // 1.
322  if (!IV) {
323  LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
324  return false;
325  }
326 
327  // 2.
328  BasicBlock *Latch = Lp->getLoopLatch();
329  auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
330  if (!LatchBr || LatchBr->isUnconditional()) {
331  LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
332  return false;
333  }
334 
335  // 3.
336  auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
337  if (!LatchCmp) {
338  LLVM_DEBUG(
339  dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
340  return false;
341  }
342 
343  Value *CondOp0 = LatchCmp->getOperand(0);
344  Value *CondOp1 = LatchCmp->getOperand(1);
345  Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
346  if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
347  !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
348  LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
349  return false;
350  }
351 
352  return true;
353 }
354 
355 // Return true if \p Lp and all its nested loops are uniform with regard to \p
356 // OuterLp.
357 static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
358  if (!isUniformLoop(Lp, OuterLp))
359  return false;
360 
361  // Check if nested loops are uniform.
362  for (Loop *SubLp : *Lp)
363  if (!isUniformLoopNest(SubLp, OuterLp))
364  return false;
365 
366  return true;
367 }
368 
369 /// Check whether it is safe to if-convert this phi node.
370 ///
371 /// Phi nodes with constant expressions that can trap are not safe to if
372 /// convert.
374  for (PHINode &Phi : BB->phis()) {
375  for (Value *V : Phi.incoming_values())
376  if (auto *C = dyn_cast<Constant>(V))
377  if (C->canTrap())
378  return false;
379  }
380  return true;
381 }
382 
384  if (Ty->isPointerTy())
385  return DL.getIntPtrType(Ty);
386 
387  // It is possible that char's or short's overflow when we ask for the loop's
388  // trip count, work around this by changing the type size.
389  if (Ty->getScalarSizeInBits() < 32)
390  return Type::getInt32Ty(Ty->getContext());
391 
392  return Ty;
393 }
394 
395 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
396  Ty0 = convertPointerToIntegerType(DL, Ty0);
397  Ty1 = convertPointerToIntegerType(DL, Ty1);
398  if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
399  return Ty0;
400  return Ty1;
401 }
402 
403 /// Check that the instruction has outside loop users and is not an
404 /// identified reduction variable.
405 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
406  SmallPtrSetImpl<Value *> &AllowedExit) {
407  // Reductions, Inductions and non-header phis are allowed to have exit users. All
408  // other instructions must not have external users.
409  if (!AllowedExit.count(Inst))
410  // Check that all of the users of the loop are inside the BB.
411  for (User *U : Inst->users()) {
412  Instruction *UI = cast<Instruction>(U);
413  // This user may be a reduction exit value.
414  if (!TheLoop->contains(UI)) {
415  LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
416  return true;
417  }
418  }
419  return false;
420 }
421 
423  const ValueToValueMap &Strides =
424  getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
425 
426  int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
427  if (Stride == 1 || Stride == -1)
428  return Stride;
429  return 0;
430 }
431 
433  return LAI->isUniform(V);
434 }
435 
436 bool LoopVectorizationLegality::canVectorizeOuterLoop() {
437  assert(!TheLoop->empty() && "We are not vectorizing an outer loop.");
438  // Store the result and return it at the end instead of exiting early, in case
439  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
440  bool Result = true;
441  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
442 
443  for (BasicBlock *BB : TheLoop->blocks()) {
444  // Check whether the BB terminator is a BranchInst. Any other terminator is
445  // not supported yet.
446  auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
447  if (!Br) {
448  LLVM_DEBUG(dbgs() << "LV: Unsupported basic block terminator.\n");
449  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
450  << "loop control flow is not understood by vectorizer");
451  if (DoExtraAnalysis)
452  Result = false;
453  else
454  return false;
455  }
456 
457  // Check whether the BranchInst is a supported one. Only unconditional
458  // branches, conditional branches with an outer loop invariant condition or
459  // backedges are supported.
460  // FIXME: We skip these checks when VPlan predication is enabled as we
461  // want to allow divergent branches. This whole check will be removed
462  // once VPlan predication is on by default.
463  if (!EnableVPlanPredication && Br && Br->isConditional() &&
464  !TheLoop->isLoopInvariant(Br->getCondition()) &&
465  !LI->isLoopHeader(Br->getSuccessor(0)) &&
466  !LI->isLoopHeader(Br->getSuccessor(1))) {
467  LLVM_DEBUG(dbgs() << "LV: Unsupported conditional branch.\n");
468  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
469  << "loop control flow is not understood by vectorizer");
470  if (DoExtraAnalysis)
471  Result = false;
472  else
473  return false;
474  }
475  }
476 
477  // Check whether inner loops are uniform. At this point, we only support
478  // simple outer loops scenarios with uniform nested loops.
479  if (!isUniformLoopNest(TheLoop /*loop nest*/,
480  TheLoop /*context outer loop*/)) {
481  LLVM_DEBUG(
482  dbgs()
483  << "LV: Not vectorizing: Outer loop contains divergent loops.\n");
484  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
485  << "loop control flow is not understood by vectorizer");
486  if (DoExtraAnalysis)
487  Result = false;
488  else
489  return false;
490  }
491 
492  // Check whether we are able to set up outer loop induction.
493  if (!setupOuterLoopInductions()) {
494  LLVM_DEBUG(
495  dbgs() << "LV: Not vectorizing: Unsupported outer loop Phi(s).\n");
496  ORE->emit(createMissedAnalysis("UnsupportedPhi")
497  << "Unsupported outer loop Phi(s)");
498  if (DoExtraAnalysis)
499  Result = false;
500  else
501  return false;
502  }
503 
504  return Result;
505 }
506 
507 void LoopVectorizationLegality::addInductionPhi(
508  PHINode *Phi, const InductionDescriptor &ID,
509  SmallPtrSetImpl<Value *> &AllowedExit) {
510  Inductions[Phi] = ID;
511 
512  // In case this induction also comes with casts that we know we can ignore
513  // in the vectorized loop body, record them here. All casts could be recorded
514  // here for ignoring, but suffices to record only the first (as it is the
515  // only one that may bw used outside the cast sequence).
516  const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
517  if (!Casts.empty())
518  InductionCastsToIgnore.insert(*Casts.begin());
519 
520  Type *PhiTy = Phi->getType();
521  const DataLayout &DL = Phi->getModule()->getDataLayout();
522 
523  // Get the widest type.
524  if (!PhiTy->isFloatingPointTy()) {
525  if (!WidestIndTy)
526  WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
527  else
528  WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
529  }
530 
531  // Int inductions are special because we only allow one IV.
534  isa<Constant>(ID.getStartValue()) &&
535  cast<Constant>(ID.getStartValue())->isNullValue()) {
536 
537  // Use the phi node with the widest type as induction. Use the last
538  // one if there are multiple (no good reason for doing this other
539  // than it is expedient). We've checked that it begins at zero and
540  // steps by one, so this is a canonical induction variable.
541  if (!PrimaryInduction || PhiTy == WidestIndTy)
542  PrimaryInduction = Phi;
543  }
544 
545  // Both the PHI node itself, and the "post-increment" value feeding
546  // back into the PHI node may have external users.
547  // We can allow those uses, except if the SCEVs we have for them rely
548  // on predicates that only hold within the loop, since allowing the exit
549  // currently means re-using this SCEV outside the loop (see PR33706 for more
550  // details).
551  if (PSE.getUnionPredicate().isAlwaysTrue()) {
552  AllowedExit.insert(Phi);
553  AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
554  }
555 
556  LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
557 }
558 
559 bool LoopVectorizationLegality::setupOuterLoopInductions() {
560  BasicBlock *Header = TheLoop->getHeader();
561 
562  // Returns true if a given Phi is a supported induction.
563  auto isSupportedPhi = [&](PHINode &Phi) -> bool {
565  if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
567  addInductionPhi(&Phi, ID, AllowedExit);
568  return true;
569  } else {
570  // Bail out for any Phi in the outer loop header that is not a supported
571  // induction.
572  LLVM_DEBUG(
573  dbgs()
574  << "LV: Found unsupported PHI for outer loop vectorization.\n");
575  return false;
576  }
577  };
578 
579  if (llvm::all_of(Header->phis(), isSupportedPhi))
580  return true;
581  else
582  return false;
583 }
584 
585 bool LoopVectorizationLegality::canVectorizeInstrs() {
586  BasicBlock *Header = TheLoop->getHeader();
587 
588  // Look for the attribute signaling the absence of NaNs.
589  Function &F = *Header->getParent();
590  HasFunNoNaNAttr =
591  F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
592 
593  // For each block in the loop.
594  for (BasicBlock *BB : TheLoop->blocks()) {
595  // Scan the instructions in the block and look for hazards.
596  for (Instruction &I : *BB) {
597  if (auto *Phi = dyn_cast<PHINode>(&I)) {
598  Type *PhiTy = Phi->getType();
599  // Check that this PHI type is allowed.
600  if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
601  !PhiTy->isPointerTy()) {
602  ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
603  << "loop control flow is not understood by vectorizer");
604  LLVM_DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
605  return false;
606  }
607 
608  // If this PHINode is not in the header block, then we know that we
609  // can convert it to select during if-conversion. No need to check if
610  // the PHIs in this block are induction or reduction variables.
611  if (BB != Header) {
612  // Non-header phi nodes that have outside uses can be vectorized. Add
613  // them to the list of allowed exits.
614  // Unsafe cyclic dependencies with header phis are identified during
615  // legalization for reduction, induction and first order
616  // recurrences.
617  continue;
618  }
619 
620  // We only allow if-converted PHIs with exactly two incoming values.
621  if (Phi->getNumIncomingValues() != 2) {
622  ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
623  << "control flow not understood by vectorizer");
624  LLVM_DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
625  return false;
626  }
627 
628  RecurrenceDescriptor RedDes;
629  if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
630  DT)) {
631  if (RedDes.hasUnsafeAlgebra())
632  Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
633  AllowedExit.insert(RedDes.getLoopExitInstr());
634  Reductions[Phi] = RedDes;
635  continue;
636  }
637 
638  // TODO: Instead of recording the AllowedExit, it would be good to record the
639  // complementary set: NotAllowedExit. These include (but may not be
640  // limited to):
641  // 1. Reduction phis as they represent the one-before-last value, which
642  // is not available when vectorized
643  // 2. Induction phis and increment when SCEV predicates cannot be used
644  // outside the loop - see addInductionPhi
645  // 3. Non-Phis with outside uses when SCEV predicates cannot be used
646  // outside the loop - see call to hasOutsideLoopUser in the non-phi
647  // handling below
648  // 4. FirstOrderRecurrence phis that can possibly be handled by
649  // extraction.
650  // By recording these, we can then reason about ways to vectorize each
651  // of these NotAllowedExit.
653  if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
654  addInductionPhi(Phi, ID, AllowedExit);
655  if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
656  Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
657  continue;
658  }
659 
661  SinkAfter, DT)) {
662  FirstOrderRecurrences.insert(Phi);
663  continue;
664  }
665 
666  // As a last resort, coerce the PHI to a AddRec expression
667  // and re-try classifying it a an induction PHI.
668  if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
669  addInductionPhi(Phi, ID, AllowedExit);
670  continue;
671  }
672 
673  ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
674  << "value that could not be identified as "
675  "reduction is used outside the loop");
676  LLVM_DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
677  return false;
678  } // end of PHI handling
679 
680  // We handle calls that:
681  // * Are debug info intrinsics.
682  // * Have a mapping to an IR intrinsic.
683  // * Have a vector version available.
684  auto *CI = dyn_cast<CallInst>(&I);
685  if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
686  !isa<DbgInfoIntrinsic>(CI) &&
687  !(CI->getCalledFunction() && TLI &&
688  TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
689  // If the call is a recognized math libary call, it is likely that
690  // we can vectorize it given loosened floating-point constraints.
691  LibFunc Func;
692  bool IsMathLibCall =
693  TLI && CI->getCalledFunction() &&
694  CI->getType()->isFloatingPointTy() &&
695  TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
696  TLI->hasOptimizedCodeGen(Func);
697 
698  if (IsMathLibCall) {
699  // TODO: Ideally, we should not use clang-specific language here,
700  // but it's hard to provide meaningful yet generic advice.
701  // Also, should this be guarded by allowExtraAnalysis() and/or be part
702  // of the returned info from isFunctionVectorizable()?
703  ORE->emit(createMissedAnalysis("CantVectorizeLibcall", CI)
704  << "library call cannot be vectorized. "
705  "Try compiling with -fno-math-errno, -ffast-math, "
706  "or similar flags");
707  } else {
708  ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
709  << "call instruction cannot be vectorized");
710  }
711  LLVM_DEBUG(
712  dbgs() << "LV: Found a non-intrinsic callsite.\n");
713  return false;
714  }
715 
716  // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
717  // second argument is the same (i.e. loop invariant)
719  getVectorIntrinsicIDForCall(CI, TLI), 1)) {
720  auto *SE = PSE.getSE();
721  if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
722  ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
723  << "intrinsic instruction cannot be vectorized");
724  LLVM_DEBUG(dbgs()
725  << "LV: Found unvectorizable intrinsic " << *CI << "\n");
726  return false;
727  }
728  }
729 
730  // Check that the instruction return type is vectorizable.
731  // Also, we can't vectorize extractelement instructions.
732  if ((!VectorType::isValidElementType(I.getType()) &&
733  !I.getType()->isVoidTy()) ||
734  isa<ExtractElementInst>(I)) {
735  ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
736  << "instruction return type cannot be vectorized");
737  LLVM_DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
738  return false;
739  }
740 
741  // Check that the stored type is vectorizable.
742  if (auto *ST = dyn_cast<StoreInst>(&I)) {
743  Type *T = ST->getValueOperand()->getType();
745  ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
746  << "store instruction cannot be vectorized");
747  return false;
748  }
749 
750  // FP instructions can allow unsafe algebra, thus vectorizable by
751  // non-IEEE-754 compliant SIMD units.
752  // This applies to floating-point math operations and calls, not memory
753  // operations, shuffles, or casts, as they don't change precision or
754  // semantics.
755  } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
756  !I.isFast()) {
757  LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
758  Hints->setPotentiallyUnsafe();
759  }
760 
761  // Reduction instructions are allowed to have exit users.
762  // All other instructions must not have external users.
763  if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
764  // We can safely vectorize loops where instructions within the loop are
765  // used outside the loop only if the SCEV predicates within the loop is
766  // same as outside the loop. Allowing the exit means reusing the SCEV
767  // outside the loop.
768  if (PSE.getUnionPredicate().isAlwaysTrue()) {
769  AllowedExit.insert(&I);
770  continue;
771  }
772  ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
773  << "value cannot be used outside the loop");
774  return false;
775  }
776  } // next instr.
777  }
778 
779  if (!PrimaryInduction) {
780  LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
781  if (Inductions.empty()) {
782  ORE->emit(createMissedAnalysis("NoInductionVariable")
783  << "loop induction variable could not be identified");
784  return false;
785  } else if (!WidestIndTy) {
786  ORE->emit(createMissedAnalysis("NoIntegerInductionVariable")
787  << "integer loop induction variable could not be identified");
788  return false;
789  }
790  }
791 
792  // Now we know the widest induction type, check if our found induction
793  // is the same size. If it's not, unset it here and InnerLoopVectorizer
794  // will create another.
795  if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
796  PrimaryInduction = nullptr;
797 
798  return true;
799 }
800 
801 bool LoopVectorizationLegality::canVectorizeMemory() {
802  LAI = &(*GetLAA)(*TheLoop);
803  const OptimizationRemarkAnalysis *LAR = LAI->getReport();
804  if (LAR) {
805  ORE->emit([&]() {
806  return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
807  "loop not vectorized: ", *LAR);
808  });
809  }
810  if (!LAI->canVectorizeMemory())
811  return false;
812 
813  if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
814  ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
815  << "write to a loop invariant address could not "
816  "be vectorized");
817  LLVM_DEBUG(
818  dbgs() << "LV: Non vectorizable stores to a uniform address\n");
819  return false;
820  }
821  Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
822  PSE.addPredicate(LAI->getPSE().getUnionPredicate());
823 
824  return true;
825 }
826 
828  Value *In0 = const_cast<Value *>(V);
829  PHINode *PN = dyn_cast_or_null<PHINode>(In0);
830  if (!PN)
831  return false;
832 
833  return Inductions.count(PN);
834 }
835 
837  auto *Inst = dyn_cast<Instruction>(V);
838  return (Inst && InductionCastsToIgnore.count(Inst));
839 }
840 
842  return isInductionPhi(V) || isCastedInductionVariable(V);
843 }
844 
846  return FirstOrderRecurrences.count(Phi);
847 }
848 
850  return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
851 }
852 
853 bool LoopVectorizationLegality::blockCanBePredicated(
854  BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
855  const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
856 
857  for (Instruction &I : *BB) {
858  // Check that we don't have a constant expression that can trap as operand.
859  for (Value *Operand : I.operands()) {
860  if (auto *C = dyn_cast<Constant>(Operand))
861  if (C->canTrap())
862  return false;
863  }
864  // We might be able to hoist the load.
865  if (I.mayReadFromMemory()) {
866  auto *LI = dyn_cast<LoadInst>(&I);
867  if (!LI)
868  return false;
869  if (!SafePtrs.count(LI->getPointerOperand())) {
870  // !llvm.mem.parallel_loop_access implies if-conversion safety.
871  // Otherwise, record that the load needs (real or emulated) masking
872  // and let the cost model decide.
873  if (!IsAnnotatedParallel)
874  MaskedOp.insert(LI);
875  continue;
876  }
877  }
878 
879  if (I.mayWriteToMemory()) {
880  auto *SI = dyn_cast<StoreInst>(&I);
881  if (!SI)
882  return false;
883  // Predicated store requires some form of masking:
884  // 1) masked store HW instruction,
885  // 2) emulation via load-blend-store (only if safe and legal to do so,
886  // be aware on the race conditions), or
887  // 3) element-by-element predicate check and scalar store.
888  MaskedOp.insert(SI);
889  continue;
890  }
891  if (I.mayThrow())
892  return false;
893  }
894 
895  return true;
896 }
897 
898 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
899  if (!EnableIfConversion) {
900  ORE->emit(createMissedAnalysis("IfConversionDisabled")
901  << "if-conversion is disabled");
902  return false;
903  }
904 
905  assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
906 
907  // A list of pointers that we can safely read and write to.
908  SmallPtrSet<Value *, 8> SafePointes;
909 
910  // Collect safe addresses.
911  for (BasicBlock *BB : TheLoop->blocks()) {
912  if (blockNeedsPredication(BB))
913  continue;
914 
915  for (Instruction &I : *BB)
916  if (auto *Ptr = getLoadStorePointerOperand(&I))
917  SafePointes.insert(Ptr);
918  }
919 
920  // Collect the blocks that need predication.
921  BasicBlock *Header = TheLoop->getHeader();
922  for (BasicBlock *BB : TheLoop->blocks()) {
923  // We don't support switch statements inside loops.
924  if (!isa<BranchInst>(BB->getTerminator())) {
925  ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
926  << "loop contains a switch statement");
927  return false;
928  }
929 
930  // We must be able to predicate all blocks that need to be predicated.
931  if (blockNeedsPredication(BB)) {
932  if (!blockCanBePredicated(BB, SafePointes)) {
933  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
934  << "control flow cannot be substituted for a select");
935  return false;
936  }
937  } else if (BB != Header && !canIfConvertPHINodes(BB)) {
938  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
939  << "control flow cannot be substituted for a select");
940  return false;
941  }
942  }
943 
944  // We can if-convert this loop.
945  return true;
946 }
947 
948 // Helper function to canVectorizeLoopNestCFG.
949 bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
950  bool UseVPlanNativePath) {
951  assert((UseVPlanNativePath || Lp->empty()) &&
952  "VPlan-native path is not enabled.");
953 
954  // TODO: ORE should be improved to show more accurate information when an
955  // outer loop can't be vectorized because a nested loop is not understood or
956  // legal. Something like: "outer_loop_location: loop not vectorized:
957  // (inner_loop_location) loop control flow is not understood by vectorizer".
958 
959  // Store the result and return it at the end instead of exiting early, in case
960  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
961  bool Result = true;
962  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
963 
964  // We must have a loop in canonical form. Loops with indirectbr in them cannot
965  // be canonicalized.
966  if (!Lp->getLoopPreheader()) {
967  LLVM_DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n");
968  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
969  << "loop control flow is not understood by vectorizer");
970  if (DoExtraAnalysis)
971  Result = false;
972  else
973  return false;
974  }
975 
976  // We must have a single backedge.
977  if (Lp->getNumBackEdges() != 1) {
978  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
979  << "loop control flow is not understood by vectorizer");
980  if (DoExtraAnalysis)
981  Result = false;
982  else
983  return false;
984  }
985 
986  // We must have a single exiting block.
987  if (!Lp->getExitingBlock()) {
988  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
989  << "loop control flow is not understood by vectorizer");
990  if (DoExtraAnalysis)
991  Result = false;
992  else
993  return false;
994  }
995 
996  // We only handle bottom-tested loops, i.e. loop in which the condition is
997  // checked at the end of each iteration. With that we can assume that all
998  // instructions in the loop are executed the same number of times.
999  if (Lp->getExitingBlock() != Lp->getLoopLatch()) {
1000  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
1001  << "loop control flow is not understood by vectorizer");
1002  if (DoExtraAnalysis)
1003  Result = false;
1004  else
1005  return false;
1006  }
1007 
1008  return Result;
1009 }
1010 
1011 bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1012  Loop *Lp, bool UseVPlanNativePath) {
1013  // Store the result and return it at the end instead of exiting early, in case
1014  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1015  bool Result = true;
1016  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1017  if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1018  if (DoExtraAnalysis)
1019  Result = false;
1020  else
1021  return false;
1022  }
1023 
1024  // Recursively check whether the loop control flow of nested loops is
1025  // understood.
1026  for (Loop *SubLp : *Lp)
1027  if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1028  if (DoExtraAnalysis)
1029  Result = false;
1030  else
1031  return false;
1032  }
1033 
1034  return Result;
1035 }
1036 
1037 bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1038  // Store the result and return it at the end instead of exiting early, in case
1039  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1040  bool Result = true;
1041 
1042  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1043  // Check whether the loop-related control flow in the loop nest is expected by
1044  // vectorizer.
1045  if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1046  if (DoExtraAnalysis)
1047  Result = false;
1048  else
1049  return false;
1050  }
1051 
1052  // We need to have a loop header.
1053  LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1054  << '\n');
1055 
1056  // Specific checks for outer loops. We skip the remaining legal checks at this
1057  // point because they don't support outer loops.
1058  if (!TheLoop->empty()) {
1059  assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1060 
1061  if (!canVectorizeOuterLoop()) {
1062  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Unsupported outer loop.\n");
1063  // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1064  // outer loops.
1065  return false;
1066  }
1067 
1068  LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1069  return Result;
1070  }
1071 
1072  assert(TheLoop->empty() && "Inner loop expected.");
1073  // Check if we can if-convert non-single-bb loops.
1074  unsigned NumBlocks = TheLoop->getNumBlocks();
1075  if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1076  LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1077  if (DoExtraAnalysis)
1078  Result = false;
1079  else
1080  return false;
1081  }
1082 
1083  // Check if we can vectorize the instructions and CFG in this loop.
1084  if (!canVectorizeInstrs()) {
1085  LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1086  if (DoExtraAnalysis)
1087  Result = false;
1088  else
1089  return false;
1090  }
1091 
1092  // Go over each instruction and look at memory deps.
1093  if (!canVectorizeMemory()) {
1094  LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1095  if (DoExtraAnalysis)
1096  Result = false;
1097  else
1098  return false;
1099  }
1100 
1101  LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1102  << (LAI->getRuntimePointerChecking()->Need
1103  ? " (with a runtime bound check)"
1104  : "")
1105  << "!\n");
1106 
1107  unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1108  if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1109  SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1110 
1111  if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
1112  ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
1113  << "Too many SCEV assumptions need to be made and checked "
1114  << "at runtime");
1115  LLVM_DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
1116  if (DoExtraAnalysis)
1117  Result = false;
1118  else
1119  return false;
1120  }
1121 
1122  // Okay! We've done all the tests. If any have failed, return false. Otherwise
1123  // we can vectorize, and at this point we don't have any other mem analysis
1124  // which may limit our maximum vectorization factor, so just return true with
1125  // no restrictions.
1126  return Result;
1127 }
1128 
1130 
1131  LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1132 
1133  if (!PrimaryInduction) {
1134  ORE->emit(createMissedAnalysis("NoPrimaryInduction")
1135  << "Missing a primary induction variable in the loop, which is "
1136  << "needed in order to fold tail by masking as required.");
1137  LLVM_DEBUG(dbgs() << "LV: No primary induction, cannot fold tail by "
1138  << "masking.\n");
1139  return false;
1140  }
1141 
1142  // TODO: handle reductions when tail is folded by masking.
1143  if (!Reductions.empty()) {
1144  ORE->emit(createMissedAnalysis("ReductionFoldingTailByMasking")
1145  << "Cannot fold tail by masking in the presence of reductions.");
1146  LLVM_DEBUG(dbgs() << "LV: Loop has reductions, cannot fold tail by "
1147  << "masking.\n");
1148  return false;
1149  }
1150 
1151  // TODO: handle outside users when tail is folded by masking.
1152  for (auto *AE : AllowedExit) {
1153  // Check that all users of allowed exit values are inside the loop.
1154  for (User *U : AE->users()) {
1155  Instruction *UI = cast<Instruction>(U);
1156  if (TheLoop->contains(UI))
1157  continue;
1158  ORE->emit(createMissedAnalysis("LiveOutFoldingTailByMasking")
1159  << "Cannot fold tail by masking in the presence of live outs.");
1160  LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking, loop has an "
1161  << "outside user for : " << *UI << '\n');
1162  return false;
1163  }
1164  }
1165 
1166  // The list of pointers that we can safely read and write to remains empty.
1167  SmallPtrSet<Value *, 8> SafePointers;
1168 
1169  // Check and mark all blocks for predication, including those that ordinarily
1170  // do not need predication such as the header block.
1171  for (BasicBlock *BB : TheLoop->blocks()) {
1172  if (!blockCanBePredicated(BB, SafePointers)) {
1173  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
1174  << "control flow cannot be substituted for a select");
1175  LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as required.\n");
1176  return false;
1177  }
1178  }
1179 
1180  LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1181  return true;
1182 }
1183 
1184 } // namespace llvm
static bool isUniformLoop(Loop *Lp, Loop *OuterLp)
static unsigned RuntimeMemoryCheckThreshold
performing memory disambiguation checks at runtime do not make more than this number of comparisons...
uint64_t CallInst * C
#define LV_NAME
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:636
Diagnostic information for missed-optimization remarks.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:224
LLVMContext & Context
static Type * getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1)
DiagnosticInfoOptimizationBase::Argument NV
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Instruction * getUnsafeAlgebraInst()
Returns first unsafe algebra instruction in the PHI node&#39;s use-chain.
bool isCastedInductionVariable(const Value *V)
Returns True if V is a cast that is part of an induction def-use chain, and had been proven to be red...
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction *> *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:453
ConstantInt * getConstIntStepValue() const
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode *> AddAttrs)
Create a new LoopID after the loop has been transformed.
Definition: LoopInfo.cpp:741
bool isUniform(Value *V)
Returns true if the value V is uniform within the loop.
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class...
This class represents a function call, abstracting a target machine&#39;s calling convention.
int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp, const ValueToValueMap &StridesMap=ValueToValueMap(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of its element size.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:173
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1185
InductionKind getKind() const
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:863
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
An instruction for reading from memory.
Definition: Instructions.h:167
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
cl::opt< bool > EnableVPlanPredication
Value * getStartValue() const
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:32
#define DEBUG_TYPE
const char * vectorizeAnalysisPassName() const
If hints are provided that force vectorization, use the AlwaysPrint pass name to force the frontend t...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
bool hasUnsafeAlgebra()
Returns true if the recurrence has unsafe algebra which requires a relaxed floating-point model...
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
Definition: LoopInfo.h:226
This file defines the LoopVectorizationLegality class.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
static const unsigned MaxVectorWidth
Maximum SIMD width.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:161
static cl::opt< bool > EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, cl::desc("Enable if-conversion during vectorization."))
Diagnostic information for optimization analysis remarks.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:578
BlockT * getHeader() const
Definition: LoopInfo.h:99
int isConsecutivePtr(Value *Ptr)
Check if this pointer is consecutive when vectorizing.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:200
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool isInductionVariable(const Value *V)
Returns True if V can be considered as an induction variable in this loop.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition: LoopInfo.cpp:238
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:620
Value * getLoadStorePointerOperand(Value *V)
A helper function that returns the pointer operand of a load or store instruction.
An instruction for storing to memory.
Definition: Instructions.h:320
static cl::opt< unsigned > PragmaVectorizeMemoryCheckThreshold("pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks with a " "vectorize(enable) pragma."))
bool blockNeedsPredication(BasicBlock *BB)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
Diagnostic information for optimization analysis remarks related to pointer aliasing.
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:409
StringRef getString() const
Definition: Metadata.cpp:463
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:749
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
Integer induction variable. Step = C.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, SmallPtrSetImpl< Value *> &AllowedExit)
Check that the instruction has outside loop users and is not an identified reduction variable...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:428
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Conditional or Unconditional Branch instruction.
Instruction * getUnsafeAlgebraInst()
Returns induction operator that does not have "fast-math" property and requires FP unsafe mode...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
#define H(x, y, z)
Definition: MD5.cpp:57
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
OptimizationRemarkAnalysis createLVMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I=nullptr)
Create an analysis remark that explains why vectorization failed.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction in TheLoop.
static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp)
bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints)
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition: LoopInfo.cpp:342
size_t size() const
Definition: SmallVector.h:52
static bool isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, DenseMap< Instruction *, Instruction *> &SinkAfter, DominatorTree *DT)
Returns true if Phi is a first-order recurrence.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition: LoopInfo.cpp:57
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:62
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:109
Diagnostic information for optimization analysis remarks related to floating-point non-commutativity...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1166
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
A struct for saving information about induction variables.
bool canFoldTailByMasking()
Return true if we can vectorize this loop while folding its tail by masking.
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition: Error.h:147
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
DenseMap< const Value *, Value * > ValueToValueMap
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
bool isFirstOrderRecurrence(const PHINode *Phi)
Returns True if Phi is a first-order recurrence in this loop.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
static const unsigned MaxInterleaveFactor
Maximum vectorization interleave count.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the intrinsic has a scalar operand.
Definition: VectorUtils.cpp:88
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition: LoopInfo.cpp:112
static bool canIfConvertPHINodes(BasicBlock *BB)
Check whether it is safe to if-convert this phi node.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
bool isInductionPhi(const Value *V)
Returns True if V is a Phi node of an induction variable in this loop.
Class for arbitrary precision integers.
Definition: APInt.h:69
iterator_range< user_iterator > users()
Definition: Value.h:399
bool hasUnsafeAlgebra()
Returns true if the induction type is FP and the binary operator does not have the "fast-math" proper...
const SmallVectorImpl< Instruction * > & getCastInsts() const
Returns a reference to the type cast instructions in the induction update chain, that are redundant w...
LoopVectorizeHints(const Loop *L, bool InterleaveOnlyWhenForced, OptimizationRemarkEmitter &ORE)
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition: LoopInfo.cpp:214
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:324
static const size_t npos
Definition: StringRef.h:50
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Instruction * getLoopExitInstr()
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:194
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:464
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:324
Collection of parameters shared beetween the Loop Vectorizer and the Loop Access Analysis.
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
bool empty() const
Definition: LoopInfo.h:145
const unsigned Kind
void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:72
static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:330
static unsigned VectorizationInterleave
Interleave factor as overridden by the user.
static Type * convertPointerToIntegerType(const DataLayout &DL, Type *Ty)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
static cl::opt< unsigned > VectorizeSCEVCheckThreshold("vectorize-scev-check-threshold", cl::init(16), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed."))
A single uniqued string.
Definition: Metadata.h:603
static cl::opt< unsigned > PragmaVectorizeSCEVCheckThreshold("pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed with a " "vectorize(enable) pragma"))
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
static bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
#define LLVM_DEBUG(X)
Definition: Debug.h:122
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:49
Root of the metadata hierarchy.
Definition: Metadata.h:57
The optimization diagnostic interface.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void emitRemarkWithHints() const
Dumps all the hint information.
const BasicBlock * getParent() const
Definition: Instruction.h:66